{"version":3,"file":"inertia-B3yV-ZeX.js","sources":["../../../node_modules/@mantine/core/esm/core/utils/get-safe-id/get-safe-id.mjs","../../../node_modules/@mantine/core/esm/core/utils/find-element-ancestor/find-element-ancestor.mjs","../../../node_modules/@mantine/core/esm/core/utils/create-scoped-keydown-handler/create-scoped-keydown-handler.mjs","../../../node_modules/@mantine/core/esm/core/utils/create-event-handler/create-event-handler.mjs","../../../node_modules/@mantine/core/esm/core/utils/get-breakpoint-value/get-breakpoint-value.mjs","../../../node_modules/@mantine/core/esm/core/utils/get-sorted-breakpoints/get-sorted-breakpoints.mjs","../../../node_modules/@mantine/core/esm/core/utils/get-base-value/get-base-value.mjs","../../../node_modules/@mantine/core/esm/core/utils/get-context-item-index/get-context-item-index.mjs","../../../node_modules/@mantine/core/esm/core/utils/use-hovered/use-hovered.mjs","../../../node_modules/@mantine/hooks/esm/utils/clamp/clamp.mjs","../../../node_modules/@mantine/hooks/esm/utils/upper-first/upper-first.mjs","../../../node_modules/@mantine/hooks/esm/use-clipboard/use-clipboard.mjs","../../../node_modules/@mantine/hooks/esm/use-debounced-value/use-debounced-value.mjs","../../../node_modules/@mantine/hooks/esm/use-window-event/use-window-event.mjs","../../../node_modules/@mantine/hooks/esm/use-move/use-move.mjs","../../../node_modules/@mantine/hooks/esm/use-pagination/use-pagination.mjs","../../../node_modules/@mantine/hooks/esm/use-resize-observer/use-resize-observer.mjs","../../../node_modules/@mantine/hooks/esm/use-input-state/use-input-state.mjs","../../../node_modules/@mantine/hooks/esm/use-disclosure/use-disclosure.mjs","../../../node_modules/@mantine/hooks/esm/use-timeout/use-timeout.mjs","../../../node_modules/@mantine/hooks/esm/use-previous/use-previous.mjs","../../../node_modules/@mantine/hooks/esm/use-eye-dropper/use-eye-dropper.mjs","../../../node_modules/@mantine/hooks/esm/use-mutation-observer/use-mutation-observer.mjs","../../../node_modules/@mantine/hooks/esm/use-mounted/use-mounted.mjs","../../../node_modules/@mantine/core/esm/core/utils/get-env/get-env.mjs","../../../node_modules/@mantine/core/esm/components/Group/filter-falsy-children/filter-falsy-children.mjs","../../../node_modules/@mantine/core/esm/components/Group/Group.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Group/Group.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBase.context.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/use-lock-scroll.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/use-modal.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBase.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/use-modal-body-id.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBase.module.css.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBaseBody.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBaseCloseButton.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBaseContent.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBaseHeader.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/use-modal-transition.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBaseOverlay.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/use-modal-title-id.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/ModalBaseTitle.mjs","../../../node_modules/@mantine/core/esm/components/ModalBase/NativeScrollArea.mjs","../../../node_modules/@mantine/core/esm/components/Flex/flex-props.mjs","../../../node_modules/@mantine/core/esm/components/Flex/Flex.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Flex/Flex.mjs","../../../node_modules/@mantine/core/esm/components/FloatingIndicator/use-floating-indicator.mjs","../../../node_modules/@mantine/core/esm/components/FloatingIndicator/FloatingIndicator.module.css.mjs","../../../node_modules/@mantine/core/esm/components/FloatingIndicator/FloatingIndicator.mjs","../../../node_modules/@mantine/core/esm/components/Accordion/Accordion.context.mjs","../../../node_modules/@mantine/core/esm/components/Accordion/AccordionChevron.mjs","../../../node_modules/@mantine/core/esm/components/Accordion/AccordionItem.context.mjs","../../../node_modules/@mantine/core/esm/components/Accordion/Accordion.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Accordion/AccordionControl/AccordionControl.mjs","../../../node_modules/@mantine/core/esm/components/Accordion/AccordionItem/AccordionItem.mjs","../../../node_modules/@mantine/core/esm/components/Accordion/AccordionPanel/AccordionPanel.mjs","../../../node_modules/@mantine/core/esm/components/Accordion/Accordion.mjs","../../../node_modules/@mantine/core/esm/components/Alert/Alert.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Alert/Alert.mjs","../../../node_modules/@mantine/core/esm/components/AspectRatio/AspectRatio.module.css.mjs","../../../node_modules/@mantine/core/esm/components/AspectRatio/AspectRatio.mjs","../../../node_modules/@mantine/core/esm/components/Badge/Badge.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Badge/Badge.mjs","../../../node_modules/@mantine/core/esm/components/Card/Card.context.mjs","../../../node_modules/@mantine/core/esm/components/Card/Card.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Card/CardSection/CardSection.mjs","../../../node_modules/@mantine/core/esm/components/Card/Card.mjs","../../../node_modules/@mantine/core/esm/components/Center/Center.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Center/Center.mjs","../../../node_modules/@mantine/core/esm/components/ColorSwatch/ColorSwatch.module.css.mjs","../../../node_modules/@mantine/core/esm/components/ColorSwatch/ColorSwatch.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/ColorPicker.context.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/Thumb/Thumb.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/ColorPicker.module.css.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/ColorSlider/ColorSlider.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/converters/parsers.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/AlphaSlider/AlphaSlider.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/converters/converters.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/HueSlider/HueSlider.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/Saturation/Saturation.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/Swatches/Swatches.mjs","../../../node_modules/@mantine/core/esm/components/ColorPicker/ColorPicker.mjs","../../../node_modules/@mantine/core/esm/components/ColorInput/EyeDropperIcon.mjs","../../../node_modules/@mantine/core/esm/components/ColorInput/ColorInput.module.css.mjs","../../../node_modules/@mantine/core/esm/components/ColorInput/ColorInput.mjs","../../../node_modules/@mantine/core/esm/components/CopyButton/CopyButton.mjs","../../../node_modules/@mantine/core/esm/components/Divider/Divider.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Divider/Divider.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/Drawer.context.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/Drawer.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/DrawerBody.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/DrawerCloseButton.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/DrawerContent.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/DrawerHeader.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/DrawerOverlay.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/DrawerRoot.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/DrawerStack.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/DrawerTitle.mjs","../../../node_modules/@mantine/core/esm/components/Drawer/Drawer.mjs","../../../node_modules/@mantine/core/esm/components/Floating/use-delayed-hover.mjs","../../../node_modules/@mantine/core/esm/components/Grid/Grid.context.mjs","../../../node_modules/@mantine/core/esm/components/Grid/GridCol/GridColVariables.mjs","../../../node_modules/@mantine/core/esm/components/Grid/Grid.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Grid/GridCol/GridCol.mjs","../../../node_modules/@mantine/core/esm/components/Grid/GridVariables.mjs","../../../node_modules/@mantine/core/esm/components/Grid/Grid.mjs","../../../node_modules/@mantine/core/esm/components/Image/Image.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Image/Image.mjs","../../../node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js","../../../node_modules/use-latest/dist/use-latest.esm.js","../../../node_modules/use-composed-ref/dist/use-composed-ref.esm.js","../../../node_modules/react-textarea-autosize/dist/react-textarea-autosize.browser.esm.js","../../../node_modules/@mantine/core/esm/components/Textarea/Textarea.mjs","../../../node_modules/@mantine/core/esm/components/LoadingOverlay/LoadingOverlay.module.css.mjs","../../../node_modules/@mantine/core/esm/components/LoadingOverlay/LoadingOverlay.mjs","../../../node_modules/@mantine/core/esm/components/Menu/Menu.context.mjs","../../../node_modules/@mantine/core/esm/components/Menu/Menu.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Menu/MenuDivider/MenuDivider.mjs","../../../node_modules/@mantine/core/esm/components/Menu/MenuDropdown/MenuDropdown.mjs","../../../node_modules/@mantine/core/esm/components/Menu/MenuItem/MenuItem.mjs","../../../node_modules/@mantine/core/esm/components/Menu/MenuLabel/MenuLabel.mjs","../../../node_modules/@mantine/core/esm/components/Menu/MenuTarget/MenuTarget.mjs","../../../node_modules/@mantine/core/esm/components/Menu/Menu.mjs","../../../node_modules/@mantine/core/esm/components/Modal/Modal.context.mjs","../../../node_modules/@mantine/core/esm/components/Modal/Modal.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Modal/ModalBody.mjs","../../../node_modules/@mantine/core/esm/components/Modal/ModalCloseButton.mjs","../../../node_modules/@mantine/core/esm/components/Modal/ModalContent.mjs","../../../node_modules/@mantine/core/esm/components/Modal/ModalHeader.mjs","../../../node_modules/@mantine/core/esm/components/Modal/ModalOverlay.mjs","../../../node_modules/@mantine/core/esm/components/Modal/ModalRoot.mjs","../../../node_modules/@mantine/core/esm/components/Modal/ModalStack.mjs","../../../node_modules/@mantine/core/esm/components/Modal/ModalTitle.mjs","../../../node_modules/@mantine/core/esm/components/Modal/Modal.mjs","../../../node_modules/@mantine/core/esm/components/NavLink/NavLink.module.css.mjs","../../../node_modules/@mantine/core/esm/components/NavLink/NavLink.mjs","../../../node_modules/react-number-format/dist/react-number-format.es.js","../../../node_modules/@mantine/core/esm/components/NumberInput/NumberInputChevron.mjs","../../../node_modules/@mantine/core/esm/components/NumberInput/NumberInput.module.css.mjs","../../../node_modules/@mantine/core/esm/components/NumberInput/NumberInput.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/Pagination.context.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/Pagination.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/PaginationControl/PaginationControl.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/Pagination.icons.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/PaginationDots/PaginationDots.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/PaginationEdges/PaginationEdges.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/PaginationItems/PaginationItems.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/PaginationRoot/PaginationRoot.mjs","../../../node_modules/@mantine/core/esm/components/Pagination/Pagination.mjs","../../../node_modules/@mantine/core/esm/components/Radio/RadioGroup.context.mjs","../../../node_modules/@mantine/core/esm/components/Radio/RadioCard/RadioCard.context.mjs","../../../node_modules/@mantine/core/esm/components/Radio/RadioCard/RadioCard.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Radio/RadioCard/RadioCard.mjs","../../../node_modules/@mantine/core/esm/components/Radio/RadioGroup/RadioGroup.mjs","../../../node_modules/@mantine/core/esm/components/Radio/RadioIcon.mjs","../../../node_modules/@mantine/core/esm/components/Radio/RadioIndicator/RadioIndicator.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Radio/RadioIndicator/RadioIndicator.mjs","../../../node_modules/@mantine/core/esm/components/Radio/Radio.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Radio/Radio.mjs","../../../node_modules/@mantine/core/esm/components/Transition/get-transition-props/get-transition-props.mjs","../../../node_modules/@mantine/core/esm/components/Tooltip/TooltipFloating/use-floating-tooltip.mjs","../../../node_modules/@mantine/core/esm/components/Tooltip/Tooltip.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Tooltip/TooltipFloating/TooltipFloating.mjs","../../../node_modules/@mantine/core/esm/components/Tooltip/TooltipGroup/TooltipGroup.context.mjs","../../../node_modules/@mantine/core/esm/components/Tooltip/TooltipGroup/TooltipGroup.mjs","../../../node_modules/@mantine/core/esm/components/Tooltip/use-tooltip.mjs","../../../node_modules/@mantine/core/esm/components/Tooltip/Tooltip.mjs","../../../node_modules/@mantine/core/esm/components/SegmentedControl/SegmentedControl.module.css.mjs","../../../node_modules/@mantine/core/esm/components/SegmentedControl/SegmentedControl.mjs","../../../node_modules/@mantine/core/esm/components/Select/Select.mjs","../../../node_modules/@mantine/core/esm/components/SimpleGrid/SimpleGridVariables.mjs","../../../node_modules/@mantine/core/esm/components/SimpleGrid/SimpleGrid.module.css.mjs","../../../node_modules/@mantine/core/esm/components/SimpleGrid/SimpleGrid.mjs","../../../node_modules/@mantine/core/esm/components/Skeleton/Skeleton.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Skeleton/Skeleton.mjs","../../../node_modules/@mantine/core/esm/components/Spoiler/Spoiler.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Spoiler/Spoiler.mjs","../../../node_modules/@mantine/core/esm/components/Switch/SwitchGroup.context.mjs","../../../node_modules/@mantine/core/esm/components/Switch/SwitchGroup/SwitchGroup.mjs","../../../node_modules/@mantine/core/esm/components/Switch/Switch.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Switch/Switch.mjs","../../../node_modules/@mantine/core/esm/components/Table/Table.context.mjs","../../../node_modules/@mantine/core/esm/components/Table/Table.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Table/Table.components.mjs","../../../node_modules/@mantine/core/esm/components/Table/TableDataRenderer.mjs","../../../node_modules/@mantine/core/esm/components/Table/TableScrollContainer.mjs","../../../node_modules/@mantine/core/esm/components/Table/Table.mjs","../../../node_modules/@mantine/core/esm/components/Tabs/Tabs.context.mjs","../../../node_modules/@mantine/core/esm/components/Tabs/Tabs.module.css.mjs","../../../node_modules/@mantine/core/esm/components/Tabs/TabsList/TabsList.mjs","../../../node_modules/@mantine/core/esm/components/Tabs/TabsPanel/TabsPanel.mjs","../../../node_modules/@mantine/core/esm/components/Tabs/TabsTab/TabsTab.mjs","../../../node_modules/@mantine/core/esm/components/Tabs/Tabs.mjs","../../../node_modules/@mantine/core/esm/components/ThemeIcon/ThemeIcon.module.css.mjs","../../../node_modules/@mantine/core/esm/components/ThemeIcon/ThemeIcon.mjs","../../../node_modules/@mantine/core/esm/components/TypographyStylesProvider/TypographyStylesProvider.module.css.mjs","../../../node_modules/@mantine/core/esm/components/TypographyStylesProvider/TypographyStylesProvider.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconAdjustmentsHorizontal.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconArrowBackUp.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconArrowLeft.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconArrowRight.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconArrowUpRight.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBookmark.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBrandFacebook.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBrandInstagram.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarCheck.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarDown.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarEvent.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarTime.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarUp.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendar.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconClockEdit.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconClockHour4.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconClock.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCopy.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconDeviceFloppy.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconDotsVertical.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconExternalLink.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconEye.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconInfoCircle.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconLink.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMenu2.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconNavigationPin.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconNotes.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconPencil.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconPhoto.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconRefresh.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconTag.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconUpload.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconUser.mjs","../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMapPinFilled.mjs","../../../app/frontend/components/Cards/ArtistCard.tsx","../../../app/frontend/components/Drawer/PostDrawerContent.tsx","../../../app/frontend/components/Drawer/EventDrawerContent.tsx","../../../app/frontend/components/Drawer/ArtistDrawerContent.tsx","../../../app/frontend/components/Drawer/DynamicDrawer.tsx","../../../app/frontend/pages/Artists/ArtistIndex.tsx","../../../node_modules/prop-types/lib/ReactPropTypesSecret.js","../../../node_modules/prop-types/factoryWithThrowingShims.js","../../../node_modules/prop-types/index.js","../../../node_modules/orderedmap/dist/index.js","../../../node_modules/prosemirror-model/dist/index.js","../../../node_modules/prosemirror-transform/dist/index.js","../../../node_modules/prosemirror-state/dist/index.js","../../../node_modules/prosemirror-view/dist/index.js","../../../node_modules/w3c-keyname/index.js","../../../node_modules/prosemirror-keymap/dist/index.js","../../../node_modules/prosemirror-commands/dist/index.js","../../../node_modules/prosemirror-schema-list/dist/index.js","../../../node_modules/@tiptap/core/dist/index.js","../../../node_modules/linkifyjs/dist/linkify.es.js","../../../node_modules/@tiptap/extension-link/dist/index.js","../../../node_modules/@mantine/tiptap/esm/RichTextEditor.module.css.mjs","../../../node_modules/@mantine/tiptap/esm/labels.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditor.context.mjs","../../../node_modules/@tiptap/react/dist/index.js","../../../node_modules/@mantine/tiptap/esm/RichTextEditorContent/RichTextEditorContent.mjs","../../../node_modules/@mantine/tiptap/esm/icons/Icons.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditorControl/RichTextEditorControl.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditorControl/controls.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditorControl/RichTextEditorLinkControl.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditorControl/RichTextEditorColorPickerControl.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditorControl/RichTextEditorColorControl.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditorControlsGroup/RichTextEditorControlsGroup.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditorToolbar/RichTextEditorToolbar.mjs","../../../node_modules/@mantine/tiptap/esm/RichTextEditor.mjs","../../../node_modules/@tiptap/extension-highlight/dist/index.js","../../../node_modules/@tiptap/extension-blockquote/dist/index.js","../../../node_modules/@tiptap/extension-bold/dist/index.js","../../../node_modules/@tiptap/extension-bullet-list/dist/index.js","../../../node_modules/@tiptap/extension-code/dist/index.js","../../../node_modules/@tiptap/extension-code-block/dist/index.js","../../../node_modules/@tiptap/extension-document/dist/index.js","../../../node_modules/prosemirror-dropcursor/dist/index.js","../../../node_modules/@tiptap/extension-dropcursor/dist/index.js","../../../node_modules/prosemirror-gapcursor/dist/index.js","../../../node_modules/@tiptap/extension-gapcursor/dist/index.js","../../../node_modules/@tiptap/extension-hard-break/dist/index.js","../../../node_modules/@tiptap/extension-heading/dist/index.js","../../../node_modules/rope-sequence/dist/index.js","../../../node_modules/prosemirror-history/dist/index.js","../../../node_modules/@tiptap/extension-history/dist/index.js","../../../node_modules/@tiptap/extension-horizontal-rule/dist/index.js","../../../node_modules/@tiptap/extension-italic/dist/index.js","../../../node_modules/@tiptap/extension-list-item/dist/index.js","../../../node_modules/@tiptap/extension-ordered-list/dist/index.js","../../../node_modules/@tiptap/extension-paragraph/dist/index.js","../../../node_modules/@tiptap/extension-strike/dist/index.js","../../../node_modules/@tiptap/extension-text/dist/index.js","../../../node_modules/@tiptap/starter-kit/dist/index.js","../../../node_modules/@tiptap/extension-underline/dist/index.js","../../../node_modules/@tiptap/extension-text-align/dist/index.js","../../../node_modules/react-dropzone-esm/dist/esm/file.mjs","../../../node_modules/react-dropzone-esm/dist/esm/file-selector.mjs","../../../node_modules/react-dropzone-esm/dist/esm/attr-accept.mjs","../../../node_modules/react-dropzone-esm/dist/esm/utils.mjs","../../../node_modules/react-dropzone-esm/dist/esm/index.mjs","../../../node_modules/@mantine/dropzone/esm/Dropzone.context.mjs","../../../node_modules/@mantine/dropzone/esm/DropzoneStatus.mjs","../../../node_modules/@mantine/dropzone/esm/Dropzone.module.css.mjs","../../../node_modules/@mantine/dropzone/esm/Dropzone.mjs","../../../node_modules/@mantine/dropzone/esm/DropzoneFullScreen.mjs","../../../node_modules/@mantine/dropzone/esm/mime-types.mjs","../../../node_modules/@mantine/dropzone/esm/index.mjs","../../../node_modules/cropperjs/dist/cropper.esm.js","../../../node_modules/react-cropper/dist/react-cropper.es.js","../../../app/frontend/components/ImageCropper.tsx","../../../app/frontend/components/ImageUploadModal.tsx","../../../app/frontend/pages/Artists/EditArtist.tsx","../../../app/frontend/components/FormLayout.tsx","../../../app/frontend/pages/DanceStyles/EditDanceStyle.tsx","../../../app/frontend/pages/DanceStyles/NewDanceStyle.tsx","../../../node_modules/dayjs/dayjs.min.js","../../../node_modules/@mantine/dates/esm/utils/get-formatted-date.mjs","../../../node_modules/@mantine/dates/esm/utils/handle-control-key-down.mjs","../../../node_modules/dayjs/plugin/timezone.js","../../../node_modules/dayjs/plugin/utc.js","../../../node_modules/@mantine/dates/esm/utils/get-timezone-offset.mjs","../../../node_modules/@mantine/dates/esm/utils/shift-timezone.mjs","../../../node_modules/@mantine/dates/esm/utils/get-default-clamped-date.mjs","../../../node_modules/@mantine/dates/esm/components/DatesProvider/DatesProvider.mjs","../../../node_modules/@mantine/dates/esm/components/DatesProvider/use-dates-context.mjs","../../../node_modules/@mantine/dates/esm/components/HiddenDatesInput/HiddenDatesInput.mjs","../../../node_modules/@mantine/dates/esm/components/TimeInput/TimeInput.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/TimeInput/TimeInput.mjs","../../../node_modules/@mantine/dates/esm/components/Day/Day.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/Day/Day.mjs","../../../node_modules/@mantine/dates/esm/components/WeekdaysRow/get-weekdays-names/get-weekdays-names.mjs","../../../node_modules/@mantine/dates/esm/components/WeekdaysRow/WeekdaysRow.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/WeekdaysRow/WeekdaysRow.mjs","../../../node_modules/@mantine/dates/esm/components/Month/get-end-of-week/get-end-of-week.mjs","../../../node_modules/@mantine/dates/esm/components/Month/get-start-of-week/get-start-of-week.mjs","../../../node_modules/@mantine/dates/esm/components/Month/get-month-days/get-month-days.mjs","../../../node_modules/@mantine/dates/esm/components/Month/is-after-min-date/is-after-min-date.mjs","../../../node_modules/@mantine/dates/esm/components/Month/is-before-max-date/is-before-max-date.mjs","../../../node_modules/@mantine/dates/esm/components/Month/get-date-in-tab-order/get-date-in-tab-order.mjs","../../../node_modules/dayjs/plugin/isoWeek.js","../../../node_modules/@mantine/dates/esm/components/Month/get-week-number/get-week-number.mjs","../../../node_modules/@mantine/dates/esm/components/Month/Month.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/Month/Month.mjs","../../../node_modules/@mantine/dates/esm/components/PickerControl/PickerControl.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/PickerControl/PickerControl.mjs","../../../node_modules/@mantine/dates/esm/components/YearsList/is-year-disabled/is-year-disabled.mjs","../../../node_modules/@mantine/dates/esm/components/YearsList/get-year-in-tab-order/get-year-in-tab-order.mjs","../../../node_modules/@mantine/dates/esm/components/YearsList/get-years-data/get-years-data.mjs","../../../node_modules/@mantine/dates/esm/components/YearsList/YearsList.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/YearsList/YearsList.mjs","../../../node_modules/@mantine/dates/esm/components/MonthsList/is-month-disabled/is-month-disabled.mjs","../../../node_modules/@mantine/dates/esm/components/MonthsList/get-month-in-tab-order/get-month-in-tab-order.mjs","../../../node_modules/@mantine/dates/esm/components/MonthsList/get-months-data/get-months-data.mjs","../../../node_modules/@mantine/dates/esm/components/MonthsList/MonthsList.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/MonthsList/MonthsList.mjs","../../../node_modules/@mantine/dates/esm/components/CalendarHeader/CalendarHeader.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/CalendarHeader/CalendarHeader.mjs","../../../node_modules/@mantine/dates/esm/components/DecadeLevel/get-decade-range/get-decade-range.mjs","../../../node_modules/@mantine/dates/esm/components/DecadeLevel/DecadeLevel.mjs","../../../node_modules/@mantine/dates/esm/components/YearLevel/YearLevel.mjs","../../../node_modules/@mantine/dates/esm/components/MonthLevel/MonthLevel.mjs","../../../node_modules/@mantine/dates/esm/components/LevelsGroup/LevelsGroup.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/LevelsGroup/LevelsGroup.mjs","../../../node_modules/@mantine/dates/esm/components/DecadeLevelGroup/DecadeLevelGroup.mjs","../../../node_modules/@mantine/dates/esm/components/YearLevelGroup/YearLevelGroup.mjs","../../../node_modules/@mantine/dates/esm/components/MonthLevelGroup/MonthLevelGroup.mjs","../../../node_modules/@mantine/dates/esm/components/PickerInputBase/PickerInputBase.module.css.mjs","../../../node_modules/@mantine/dates/esm/components/PickerInputBase/PickerInputBase.mjs","../../../node_modules/@mantine/dates/esm/hooks/use-uncontrolled-dates/use-uncontrolled-dates.mjs","../../../node_modules/@mantine/dates/esm/components/Calendar/clamp-level/clamp-level.mjs","../../../node_modules/@mantine/dates/esm/components/Calendar/Calendar.mjs","../../../node_modules/@mantine/dates/esm/components/Calendar/pick-calendar-levels-props/pick-calendar-levels-props.mjs","../../../node_modules/@mantine/dates/esm/hooks/use-dates-state/is-in-range/is-in-range.mjs","../../../node_modules/@mantine/dates/esm/hooks/use-dates-state/use-dates-state.mjs","../../../node_modules/@mantine/dates/esm/components/DatePicker/DatePicker.mjs","../../../node_modules/@mantine/dates/esm/hooks/use-dates-input/use-dates-input.mjs","../../../node_modules/@mantine/dates/esm/components/DatePickerInput/DatePickerInput.mjs","../../../node_modules/@react-google-maps/api/dist/esm.js","../../../app/frontend/components/AddressAutocompleteMap.tsx","../../../app/frontend/components/RecurringEventFields.tsx","../../../app/frontend/pages/Events/CreateEvent.tsx","../../../app/frontend/components/DangerZoneCard.tsx","../../../node_modules/date-fns-tz/dist/esm/_lib/tzIntlTimeZoneName/index.js","../../../node_modules/date-fns-tz/dist/esm/_lib/tzTokenizeDate/index.js","../../../node_modules/date-fns-tz/dist/esm/_lib/newDateUTC/index.js","../../../node_modules/date-fns-tz/dist/esm/_lib/tzParseTimezone/index.js","../../../node_modules/date-fns-tz/dist/esm/format/formatters/index.js","../../../node_modules/date-fns-tz/dist/esm/_lib/getTimezoneOffsetInMilliseconds/index.js","../../../node_modules/date-fns-tz/dist/esm/_lib/tzPattern/index.js","../../../node_modules/date-fns-tz/dist/esm/toDate/index.js","../../../node_modules/date-fns-tz/dist/esm/format/index.js","../../../app/frontend/pages/Events/EditEvent.tsx","../../../app/frontend/pages/Organizer/EditOrganizer.tsx","../../../app/frontend/pages/Organizer/NewOrganizer.tsx","../../../app/frontend/pages/Organizer/OrganizerIndex.tsx","../../../node_modules/react-side-effect/lib/index.js","../../../node_modules/react-fast-compare/index.js","../../../node_modules/object-assign/index.js","../../../node_modules/react-helmet/es/Helmet.js","../../../node_modules/preact/dist/preact.module.js","../../../node_modules/preact/hooks/dist/hooks.module.js","../../../node_modules/preact/compat/dist/compat.module.js","../../../node_modules/@fullcalendar/core/internal-common.js","../../../node_modules/@fullcalendar/core/index.js","../../../node_modules/@fullcalendar/react/dist/index.js","../../../node_modules/@fullcalendar/daygrid/internal.js","../../../node_modules/@fullcalendar/daygrid/index.js","../../../app/frontend/components/Cards/EventCard.tsx","../../../app/frontend/components/ManageBadge.tsx","../../../app/frontend/components/LoginModal.tsx","../../../app/frontend/hooks/useLoginModal.ts","../../../app/frontend/pages/Organizer/OrganizerShow.tsx","../../../node_modules/cookie/dist/index.js","../../../node_modules/react-router/dist/development/chunk-IR6S3I6Y.mjs","../../../node_modules/@tanstack/query-core/build/modern/subscribable.js","../../../node_modules/@tanstack/query-core/build/modern/utils.js","../../../node_modules/@tanstack/query-core/build/modern/focusManager.js","../../../node_modules/@tanstack/query-core/build/modern/onlineManager.js","../../../node_modules/@tanstack/query-core/build/modern/thenable.js","../../../node_modules/@tanstack/query-core/build/modern/retryer.js","../../../node_modules/@tanstack/query-core/build/modern/notifyManager.js","../../../node_modules/@tanstack/query-core/build/modern/removable.js","../../../node_modules/@tanstack/query-core/build/modern/query.js","../../../node_modules/@tanstack/query-core/build/modern/queryCache.js","../../../node_modules/@tanstack/query-core/build/modern/mutation.js","../../../node_modules/@tanstack/query-core/build/modern/mutationCache.js","../../../node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js","../../../node_modules/@tanstack/query-core/build/modern/queryClient.js","../../../node_modules/@tanstack/query-core/build/modern/mutationObserver.js","../../../node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js","../../../node_modules/@tanstack/react-query/build/modern/utils.js","../../../node_modules/@tanstack/react-query/build/modern/useMutation.js","../../../app/frontend/components/PrivateLessons/LessonDetailsForm.tsx","../../../app/frontend/components/PrivateLessons/TimeSlotCalendar.tsx","../../../app/frontend/components/PrivateLessons/TimeSlotDrawer.tsx","../../../app/frontend/pages/PrivateLessonPages/EditPrivateLessonPage.tsx","../../../app/frontend/pages/PrivateLessonPages/ShowPrivateLessonPage.tsx","../../../app/frontend/pages/PrivateLessonPages/UserLessonIndex.tsx","../../../app/frontend/pages/Users/IndexUsers.tsx","../../../app/frontend/components/PrivateLessons/PrivateLessonsManagement.tsx","../../../app/frontend/pages/Users/UserSettings.tsx","../../../app/frontend/entrypoints/inertia.ts"],"sourcesContent":["'use client';\nfunction getSafeId(uid, errorMessage) {\n return (value) => {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(errorMessage);\n }\n return `${uid}-${value}`;\n };\n}\n\nexport { getSafeId };\n//# sourceMappingURL=get-safe-id.mjs.map\n","'use client';\nfunction findElementAncestor(element, selector) {\n let _element = element;\n while ((_element = _element.parentElement) && !_element.matches(selector)) {\n }\n return _element;\n}\n\nexport { findElementAncestor };\n//# sourceMappingURL=find-element-ancestor.mjs.map\n","'use client';\nimport { findElementAncestor } from '../find-element-ancestor/find-element-ancestor.mjs';\n\nfunction getPreviousIndex(current, elements, loop) {\n for (let i = current - 1; i >= 0; i -= 1) {\n if (!elements[i].disabled) {\n return i;\n }\n }\n if (loop) {\n for (let i = elements.length - 1; i > -1; i -= 1) {\n if (!elements[i].disabled) {\n return i;\n }\n }\n }\n return current;\n}\nfunction getNextIndex(current, elements, loop) {\n for (let i = current + 1; i < elements.length; i += 1) {\n if (!elements[i].disabled) {\n return i;\n }\n }\n if (loop) {\n for (let i = 0; i < elements.length; i += 1) {\n if (!elements[i].disabled) {\n return i;\n }\n }\n }\n return current;\n}\nfunction onSameLevel(target, sibling, parentSelector) {\n return findElementAncestor(target, parentSelector) === findElementAncestor(sibling, parentSelector);\n}\nfunction createScopedKeydownHandler({\n parentSelector,\n siblingSelector,\n onKeyDown,\n loop = true,\n activateOnFocus = false,\n dir = \"rtl\",\n orientation\n}) {\n return (event) => {\n onKeyDown?.(event);\n const elements = Array.from(\n findElementAncestor(event.currentTarget, parentSelector)?.querySelectorAll(\n siblingSelector\n ) || []\n ).filter((node) => onSameLevel(event.currentTarget, node, parentSelector));\n const current = elements.findIndex((el) => event.currentTarget === el);\n const _nextIndex = getNextIndex(current, elements, loop);\n const _previousIndex = getPreviousIndex(current, elements, loop);\n const nextIndex = dir === \"rtl\" ? _previousIndex : _nextIndex;\n const previousIndex = dir === \"rtl\" ? _nextIndex : _previousIndex;\n switch (event.key) {\n case \"ArrowRight\": {\n if (orientation === \"horizontal\") {\n event.stopPropagation();\n event.preventDefault();\n elements[nextIndex].focus();\n activateOnFocus && elements[nextIndex].click();\n }\n break;\n }\n case \"ArrowLeft\": {\n if (orientation === \"horizontal\") {\n event.stopPropagation();\n event.preventDefault();\n elements[previousIndex].focus();\n activateOnFocus && elements[previousIndex].click();\n }\n break;\n }\n case \"ArrowUp\": {\n if (orientation === \"vertical\") {\n event.stopPropagation();\n event.preventDefault();\n elements[_previousIndex].focus();\n activateOnFocus && elements[_previousIndex].click();\n }\n break;\n }\n case \"ArrowDown\": {\n if (orientation === \"vertical\") {\n event.stopPropagation();\n event.preventDefault();\n elements[_nextIndex].focus();\n activateOnFocus && elements[_nextIndex].click();\n }\n break;\n }\n case \"Home\": {\n event.stopPropagation();\n event.preventDefault();\n !elements[0].disabled && elements[0].focus();\n break;\n }\n case \"End\": {\n event.stopPropagation();\n event.preventDefault();\n const last = elements.length - 1;\n !elements[last].disabled && elements[last].focus();\n break;\n }\n }\n };\n}\n\nexport { createScopedKeydownHandler };\n//# sourceMappingURL=create-scoped-keydown-handler.mjs.map\n","'use client';\nfunction createEventHandler(parentEventHandler, eventHandler) {\n return (event) => {\n parentEventHandler?.(event);\n eventHandler?.(event);\n };\n}\n\nexport { createEventHandler };\n//# sourceMappingURL=create-event-handler.mjs.map\n","'use client';\nimport { px } from '../units-converters/px.mjs';\n\nfunction getBreakpointValue(breakpoint, breakpoints) {\n if (breakpoint in breakpoints) {\n return px(breakpoints[breakpoint]);\n }\n return px(breakpoint);\n}\n\nexport { getBreakpointValue };\n//# sourceMappingURL=get-breakpoint-value.mjs.map\n","'use client';\nimport { getBreakpointValue } from '../get-breakpoint-value/get-breakpoint-value.mjs';\n\nfunction getSortedBreakpoints(values, breakpoints) {\n const convertedBreakpoints = values.map((breakpoint) => ({\n value: breakpoint,\n px: getBreakpointValue(breakpoint, breakpoints)\n }));\n convertedBreakpoints.sort((a, b) => a.px - b.px);\n return convertedBreakpoints;\n}\n\nexport { getSortedBreakpoints };\n//# sourceMappingURL=get-sorted-breakpoints.mjs.map\n","'use client';\nfunction getBaseValue(value) {\n if (typeof value === \"object\" && value !== null) {\n if (\"base\" in value) {\n return value.base;\n }\n return void 0;\n }\n return value;\n}\n\nexport { getBaseValue };\n//# sourceMappingURL=get-base-value.mjs.map\n","'use client';\nimport { findElementAncestor } from '../find-element-ancestor/find-element-ancestor.mjs';\n\nfunction getContextItemIndex(elementSelector, parentSelector, node) {\n if (!node) {\n return null;\n }\n return Array.from(\n findElementAncestor(node, parentSelector)?.querySelectorAll(elementSelector) || []\n ).findIndex((element) => element === node);\n}\n\nexport { getContextItemIndex };\n//# sourceMappingURL=get-context-item-index.mjs.map\n","'use client';\nimport { useState } from 'react';\n\nfunction useHovered() {\n const [hovered, setHovered] = useState(-1);\n const resetHovered = () => setHovered(-1);\n return [hovered, { setHovered, resetHovered }];\n}\n\nexport { useHovered };\n//# sourceMappingURL=use-hovered.mjs.map\n","'use client';\nfunction clamp(value, min, max) {\n if (min === void 0 && max === void 0) {\n return value;\n }\n if (min !== void 0 && max === void 0) {\n return Math.max(value, min);\n }\n if (min === void 0 && max !== void 0) {\n return Math.min(value, max);\n }\n return Math.min(Math.max(value, min), max);\n}\n\nexport { clamp };\n//# sourceMappingURL=clamp.mjs.map\n","'use client';\nfunction upperFirst(value) {\n return typeof value !== \"string\" ? \"\" : value.charAt(0).toUpperCase() + value.slice(1);\n}\n\nexport { upperFirst };\n//# sourceMappingURL=upper-first.mjs.map\n","'use client';\nimport { useState } from 'react';\n\nfunction useClipboard({ timeout = 2e3 } = {}) {\n const [error, setError] = useState(null);\n const [copied, setCopied] = useState(false);\n const [copyTimeout, setCopyTimeout] = useState(null);\n const handleCopyResult = (value) => {\n window.clearTimeout(copyTimeout);\n setCopyTimeout(window.setTimeout(() => setCopied(false), timeout));\n setCopied(value);\n };\n const copy = (valueToCopy) => {\n if (\"clipboard\" in navigator) {\n navigator.clipboard.writeText(valueToCopy).then(() => handleCopyResult(true)).catch((err) => setError(err));\n } else {\n setError(new Error(\"useClipboard: navigator.clipboard is not supported\"));\n }\n };\n const reset = () => {\n setCopied(false);\n setError(null);\n window.clearTimeout(copyTimeout);\n };\n return { copy, reset, error, copied };\n}\n\nexport { useClipboard };\n//# sourceMappingURL=use-clipboard.mjs.map\n","'use client';\nimport { useState, useRef, useEffect } from 'react';\n\nfunction useDebouncedValue(value, wait, options = { leading: false }) {\n const [_value, setValue] = useState(value);\n const mountedRef = useRef(false);\n const timeoutRef = useRef(null);\n const cooldownRef = useRef(false);\n const cancel = () => window.clearTimeout(timeoutRef.current);\n useEffect(() => {\n if (mountedRef.current) {\n if (!cooldownRef.current && options.leading) {\n cooldownRef.current = true;\n setValue(value);\n } else {\n cancel();\n timeoutRef.current = window.setTimeout(() => {\n cooldownRef.current = false;\n setValue(value);\n }, wait);\n }\n }\n }, [value, options.leading, wait]);\n useEffect(() => {\n mountedRef.current = true;\n return cancel;\n }, []);\n return [_value, cancel];\n}\n\nexport { useDebouncedValue };\n//# sourceMappingURL=use-debounced-value.mjs.map\n","'use client';\nimport { useEffect } from 'react';\n\nfunction useWindowEvent(type, listener, options) {\n useEffect(() => {\n window.addEventListener(type, listener, options);\n return () => window.removeEventListener(type, listener, options);\n }, [type, listener]);\n}\n\nexport { useWindowEvent };\n//# sourceMappingURL=use-window-event.mjs.map\n","'use client';\nimport { useRef, useState, useEffect } from 'react';\nimport { clamp } from '../utils/clamp/clamp.mjs';\n\nfunction clampUseMovePosition(position) {\n return {\n x: clamp(position.x, 0, 1),\n y: clamp(position.y, 0, 1)\n };\n}\nfunction useMove(onChange, handlers, dir = \"ltr\") {\n const ref = useRef(null);\n const mounted = useRef(false);\n const isSliding = useRef(false);\n const frame = useRef(0);\n const [active, setActive] = useState(false);\n useEffect(() => {\n mounted.current = true;\n }, []);\n useEffect(() => {\n const node = ref.current;\n const onScrub = ({ x, y }) => {\n cancelAnimationFrame(frame.current);\n frame.current = requestAnimationFrame(() => {\n if (mounted.current && node) {\n node.style.userSelect = \"none\";\n const rect = node.getBoundingClientRect();\n if (rect.width && rect.height) {\n const _x = clamp((x - rect.left) / rect.width, 0, 1);\n onChange({\n x: dir === \"ltr\" ? _x : 1 - _x,\n y: clamp((y - rect.top) / rect.height, 0, 1)\n });\n }\n }\n });\n };\n const bindEvents = () => {\n document.addEventListener(\"mousemove\", onMouseMove);\n document.addEventListener(\"mouseup\", stopScrubbing);\n document.addEventListener(\"touchmove\", onTouchMove);\n document.addEventListener(\"touchend\", stopScrubbing);\n };\n const unbindEvents = () => {\n document.removeEventListener(\"mousemove\", onMouseMove);\n document.removeEventListener(\"mouseup\", stopScrubbing);\n document.removeEventListener(\"touchmove\", onTouchMove);\n document.removeEventListener(\"touchend\", stopScrubbing);\n };\n const startScrubbing = () => {\n if (!isSliding.current && mounted.current) {\n isSliding.current = true;\n typeof handlers?.onScrubStart === \"function\" && handlers.onScrubStart();\n setActive(true);\n bindEvents();\n }\n };\n const stopScrubbing = () => {\n if (isSliding.current && mounted.current) {\n isSliding.current = false;\n setActive(false);\n unbindEvents();\n setTimeout(() => {\n typeof handlers?.onScrubEnd === \"function\" && handlers.onScrubEnd();\n }, 0);\n }\n };\n const onMouseDown = (event) => {\n startScrubbing();\n event.preventDefault();\n onMouseMove(event);\n };\n const onMouseMove = (event) => onScrub({ x: event.clientX, y: event.clientY });\n const onTouchStart = (event) => {\n if (event.cancelable) {\n event.preventDefault();\n }\n startScrubbing();\n onTouchMove(event);\n };\n const onTouchMove = (event) => {\n if (event.cancelable) {\n event.preventDefault();\n }\n onScrub({ x: event.changedTouches[0].clientX, y: event.changedTouches[0].clientY });\n };\n node?.addEventListener(\"mousedown\", onMouseDown);\n node?.addEventListener(\"touchstart\", onTouchStart, { passive: false });\n return () => {\n if (node) {\n node.removeEventListener(\"mousedown\", onMouseDown);\n node.removeEventListener(\"touchstart\", onTouchStart);\n }\n };\n }, [dir, onChange]);\n return { ref, active };\n}\n\nexport { clampUseMovePosition, useMove };\n//# sourceMappingURL=use-move.mjs.map\n","'use client';\nimport { useMemo } from 'react';\nimport { useUncontrolled } from '../use-uncontrolled/use-uncontrolled.mjs';\n\nfunction range(start, end) {\n const length = end - start + 1;\n return Array.from({ length }, (_, index) => index + start);\n}\nconst DOTS = \"dots\";\nfunction usePagination({\n total,\n siblings = 1,\n boundaries = 1,\n page,\n initialPage = 1,\n onChange\n}) {\n const _total = Math.max(Math.trunc(total), 0);\n const [activePage, setActivePage] = useUncontrolled({\n value: page,\n onChange,\n defaultValue: initialPage,\n finalValue: initialPage\n });\n const setPage = (pageNumber) => {\n if (pageNumber <= 0) {\n setActivePage(1);\n } else if (pageNumber > _total) {\n setActivePage(_total);\n } else {\n setActivePage(pageNumber);\n }\n };\n const next = () => setPage(activePage + 1);\n const previous = () => setPage(activePage - 1);\n const first = () => setPage(1);\n const last = () => setPage(_total);\n const paginationRange = useMemo(() => {\n const totalPageNumbers = siblings * 2 + 3 + boundaries * 2;\n if (totalPageNumbers >= _total) {\n return range(1, _total);\n }\n const leftSiblingIndex = Math.max(activePage - siblings, boundaries);\n const rightSiblingIndex = Math.min(activePage + siblings, _total - boundaries);\n const shouldShowLeftDots = leftSiblingIndex > boundaries + 2;\n const shouldShowRightDots = rightSiblingIndex < _total - (boundaries + 1);\n if (!shouldShowLeftDots && shouldShowRightDots) {\n const leftItemCount = siblings * 2 + boundaries + 2;\n return [...range(1, leftItemCount), DOTS, ...range(_total - (boundaries - 1), _total)];\n }\n if (shouldShowLeftDots && !shouldShowRightDots) {\n const rightItemCount = boundaries + 1 + 2 * siblings;\n return [...range(1, boundaries), DOTS, ...range(_total - rightItemCount, _total)];\n }\n return [\n ...range(1, boundaries),\n DOTS,\n ...range(leftSiblingIndex, rightSiblingIndex),\n DOTS,\n ...range(_total - boundaries + 1, _total)\n ];\n }, [_total, siblings, activePage]);\n return {\n range: paginationRange,\n active: activePage,\n setPage,\n next,\n previous,\n first,\n last\n };\n}\n\nexport { DOTS, usePagination };\n//# sourceMappingURL=use-pagination.mjs.map\n","'use client';\nimport { useRef, useState, useMemo, useEffect } from 'react';\n\nconst defaultState = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n bottom: 0,\n right: 0\n};\nfunction useResizeObserver(options) {\n const frameID = useRef(0);\n const ref = useRef(null);\n const [rect, setRect] = useState(defaultState);\n const observer = useMemo(\n () => typeof window !== \"undefined\" ? new ResizeObserver((entries) => {\n const entry = entries[0];\n if (entry) {\n cancelAnimationFrame(frameID.current);\n frameID.current = requestAnimationFrame(() => {\n if (ref.current) {\n setRect(entry.contentRect);\n }\n });\n }\n }) : null,\n []\n );\n useEffect(() => {\n if (ref.current) {\n observer?.observe(ref.current, options);\n }\n return () => {\n observer?.disconnect();\n if (frameID.current) {\n cancelAnimationFrame(frameID.current);\n }\n };\n }, [ref.current]);\n return [ref, rect];\n}\nfunction useElementSize(options) {\n const [ref, { width, height }] = useResizeObserver(options);\n return { ref, width, height };\n}\n\nexport { useElementSize, useResizeObserver };\n//# sourceMappingURL=use-resize-observer.mjs.map\n","'use client';\nimport { useState } from 'react';\n\nfunction getInputOnChange(setValue) {\n return (val) => {\n if (!val) {\n setValue(val);\n } else if (typeof val === \"function\") {\n setValue(val);\n } else if (typeof val === \"object\" && \"nativeEvent\" in val) {\n const { currentTarget } = val;\n if (currentTarget.type === \"checkbox\") {\n setValue(currentTarget.checked);\n } else {\n setValue(currentTarget.value);\n }\n } else {\n setValue(val);\n }\n };\n}\nfunction useInputState(initialState) {\n const [value, setValue] = useState(initialState);\n return [value, getInputOnChange(setValue)];\n}\n\nexport { getInputOnChange, useInputState };\n//# sourceMappingURL=use-input-state.mjs.map\n","'use client';\nimport { useState, useCallback } from 'react';\n\nfunction useDisclosure(initialState = false, callbacks) {\n const { onOpen, onClose } = callbacks || {};\n const [opened, setOpened] = useState(initialState);\n const open = useCallback(() => {\n setOpened((isOpened) => {\n if (!isOpened) {\n onOpen?.();\n return true;\n }\n return isOpened;\n });\n }, [onOpen]);\n const close = useCallback(() => {\n setOpened((isOpened) => {\n if (isOpened) {\n onClose?.();\n return false;\n }\n return isOpened;\n });\n }, [onClose]);\n const toggle = useCallback(() => {\n opened ? close() : open();\n }, [close, open, opened]);\n return [opened, { open, close, toggle }];\n}\n\nexport { useDisclosure };\n//# sourceMappingURL=use-disclosure.mjs.map\n","'use client';\nimport { useRef, useCallback, useEffect } from 'react';\n\nfunction useTimeout(callback, delay, options = { autoInvoke: false }) {\n const timeoutRef = useRef(null);\n const start = useCallback(\n (...callbackParams) => {\n if (!timeoutRef.current) {\n timeoutRef.current = window.setTimeout(() => {\n callback(callbackParams);\n timeoutRef.current = null;\n }, delay);\n }\n },\n [delay]\n );\n const clear = useCallback(() => {\n if (timeoutRef.current) {\n window.clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n }, []);\n useEffect(() => {\n if (options.autoInvoke) {\n start();\n }\n return clear;\n }, [clear, start]);\n return { start, clear };\n}\n\nexport { useTimeout };\n//# sourceMappingURL=use-timeout.mjs.map\n","'use client';\nimport { useRef, useEffect } from 'react';\n\nfunction usePrevious(value) {\n const ref = useRef(void 0);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n return ref.current;\n}\n\nexport { usePrevious };\n//# sourceMappingURL=use-previous.mjs.map\n","'use client';\nimport { useState, useCallback } from 'react';\nimport { useIsomorphicEffect } from '../use-isomorphic-effect/use-isomorphic-effect.mjs';\n\nfunction isOpera() {\n return navigator.userAgent.includes(\"OPR\");\n}\nfunction useEyeDropper() {\n const [supported, setSupported] = useState(false);\n useIsomorphicEffect(() => {\n setSupported(typeof window !== \"undefined\" && !isOpera() && \"EyeDropper\" in window);\n }, []);\n const open = useCallback(\n (options = {}) => {\n if (supported) {\n const eyeDropper = new window.EyeDropper();\n return eyeDropper.open(options);\n }\n return Promise.resolve(void 0);\n },\n [supported]\n );\n return { supported, open };\n}\n\nexport { useEyeDropper };\n//# sourceMappingURL=use-eye-dropper.mjs.map\n","'use client';\nimport { useRef, useEffect } from 'react';\n\nfunction useMutationObserver(callback, options, target) {\n const observer = useRef(null);\n const ref = useRef(null);\n useEffect(() => {\n const targetElement = typeof target === \"function\" ? target() : target;\n if (targetElement || ref.current) {\n observer.current = new MutationObserver(callback);\n observer.current.observe(targetElement || ref.current, options);\n }\n return () => {\n observer.current?.disconnect();\n };\n }, [callback, options]);\n return ref;\n}\n\nexport { useMutationObserver };\n//# sourceMappingURL=use-mutation-observer.mjs.map\n","'use client';\nimport { useState, useEffect } from 'react';\n\nfunction useMounted() {\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n return mounted;\n}\n\nexport { useMounted };\n//# sourceMappingURL=use-mounted.mjs.map\n","'use client';\nfunction getEnv() {\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_ENV) {\n return process.env.NODE_ENV;\n }\n return \"development\";\n}\n\nexport { getEnv };\n//# sourceMappingURL=get-env.mjs.map\n","'use client';\nimport { Children } from 'react';\n\nfunction filterFalsyChildren(children) {\n return Children.toArray(children).filter(Boolean);\n}\n\nexport { filterFalsyChildren };\n//# sourceMappingURL=filter-falsy-children.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_4081bf90\"};\n\nexport { classes as default };\n//# sourceMappingURL=Group.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport { getSpacing } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { filterFalsyChildren } from './filter-falsy-children/filter-falsy-children.mjs';\nimport classes from './Group.module.css.mjs';\n\nconst defaultProps = {\n preventGrowOverflow: true,\n gap: \"md\",\n align: \"center\",\n justify: \"flex-start\",\n wrap: \"wrap\"\n};\nconst varsResolver = createVarsResolver(\n (_, { grow, preventGrowOverflow, gap, align, justify, wrap }, { childWidth }) => ({\n root: {\n \"--group-child-width\": grow && preventGrowOverflow ? childWidth : void 0,\n \"--group-gap\": getSpacing(gap),\n \"--group-align\": align,\n \"--group-justify\": justify,\n \"--group-wrap\": wrap\n }\n })\n);\nconst Group = factory((_props, ref) => {\n const props = useProps(\"Group\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n children,\n gap,\n align,\n justify,\n wrap,\n grow,\n preventGrowOverflow,\n vars,\n variant,\n __size,\n mod,\n ...others\n } = props;\n const filteredChildren = filterFalsyChildren(children);\n const childrenCount = filteredChildren.length;\n const resolvedGap = getSpacing(gap ?? \"md\");\n const childWidth = `calc(${100 / childrenCount}% - (${resolvedGap} - ${resolvedGap} / ${childrenCount}))`;\n const stylesCtx = { childWidth };\n const getStyles = useStyles({\n name: \"Group\",\n props,\n stylesCtx,\n className,\n style,\n classes,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(\n Box,\n {\n ...getStyles(\"root\"),\n ref,\n variant,\n mod: [{ grow }, mod],\n size: __size,\n ...others,\n children: filteredChildren\n }\n );\n});\nGroup.classes = classes;\nGroup.displayName = \"@mantine/core/Group\";\n\nexport { Group };\n//# sourceMappingURL=Group.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [ModalBaseProvider, useModalBaseContext] = createSafeContext(\n \"ModalBase component was not found in tree\"\n);\n\nexport { ModalBaseProvider, useModalBaseContext };\n//# sourceMappingURL=ModalBase.context.mjs.map\n","'use client';\nimport { useState, useRef, useEffect } from 'react';\nimport { useReducedMotion } from '@mantine/hooks';\n\nfunction useLockScroll({ opened, transitionDuration }) {\n const [shouldLockScroll, setShouldLockScroll] = useState(opened);\n const timeout = useRef(-1);\n const reduceMotion = useReducedMotion();\n const _transitionDuration = reduceMotion ? 0 : transitionDuration;\n useEffect(() => {\n if (opened) {\n setShouldLockScroll(true);\n window.clearTimeout(timeout.current);\n } else if (_transitionDuration === 0) {\n setShouldLockScroll(false);\n } else {\n timeout.current = window.setTimeout(() => setShouldLockScroll(false), _transitionDuration);\n }\n return () => window.clearTimeout(timeout.current);\n }, [opened, _transitionDuration]);\n return shouldLockScroll;\n}\n\nexport { useLockScroll };\n//# sourceMappingURL=use-lock-scroll.mjs.map\n","'use client';\nimport { useState } from 'react';\nimport { useId, useWindowEvent, useFocusReturn } from '@mantine/hooks';\nimport { useLockScroll } from './use-lock-scroll.mjs';\n\nfunction useModal({\n id,\n transitionProps,\n opened,\n trapFocus,\n closeOnEscape,\n onClose,\n returnFocus\n}) {\n const _id = useId(id);\n const [titleMounted, setTitleMounted] = useState(false);\n const [bodyMounted, setBodyMounted] = useState(false);\n const transitionDuration = typeof transitionProps?.duration === \"number\" ? transitionProps?.duration : 200;\n const shouldLockScroll = useLockScroll({ opened, transitionDuration });\n useWindowEvent(\n \"keydown\",\n (event) => {\n if (event.key === \"Escape\" && closeOnEscape && opened) {\n const shouldTrigger = event.target?.getAttribute(\"data-mantine-stop-propagation\") !== \"true\";\n shouldTrigger && onClose();\n }\n },\n { capture: true }\n );\n useFocusReturn({ opened, shouldReturnFocus: trapFocus && returnFocus });\n return {\n _id,\n titleMounted,\n bodyMounted,\n shouldLockScroll,\n setTitleMounted,\n setBodyMounted\n };\n}\n\nexport { useModal };\n//# sourceMappingURL=use-modal.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport { RemoveScroll } from 'react-remove-scroll';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport { getShadow, getSpacing } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../Portal/Portal.mjs';\nimport { OptionalPortal } from '../Portal/OptionalPortal.mjs';\nimport { ModalBaseProvider } from './ModalBase.context.mjs';\nimport { useModal } from './use-modal.mjs';\n\nconst ModalBase = forwardRef(\n ({\n keepMounted,\n opened,\n onClose,\n id,\n transitionProps,\n onExitTransitionEnd,\n onEnterTransitionEnd,\n trapFocus,\n closeOnEscape,\n returnFocus,\n closeOnClickOutside,\n withinPortal,\n portalProps,\n lockScroll,\n children,\n zIndex,\n shadow,\n padding,\n __vars,\n unstyled,\n removeScrollProps,\n ...others\n }, ref) => {\n const { _id, titleMounted, bodyMounted, shouldLockScroll, setTitleMounted, setBodyMounted } = useModal({ id, transitionProps, opened, trapFocus, closeOnEscape, onClose, returnFocus });\n const { key: removeScrollKey, ...otherRemoveScrollProps } = removeScrollProps || {};\n return /* @__PURE__ */ jsx(OptionalPortal, { ...portalProps, withinPortal, children: /* @__PURE__ */ jsx(\n ModalBaseProvider,\n {\n value: {\n opened,\n onClose,\n closeOnClickOutside,\n onExitTransitionEnd,\n onEnterTransitionEnd,\n transitionProps: { ...transitionProps, keepMounted },\n getTitleId: () => `${_id}-title`,\n getBodyId: () => `${_id}-body`,\n titleMounted,\n bodyMounted,\n setTitleMounted,\n setBodyMounted,\n trapFocus,\n closeOnEscape,\n zIndex,\n unstyled\n },\n children: /* @__PURE__ */ jsx(\n RemoveScroll,\n {\n enabled: shouldLockScroll && lockScroll,\n ...otherRemoveScrollProps,\n children: /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n ...others,\n __vars: {\n ...__vars,\n \"--mb-z-index\": (zIndex || getDefaultZIndex(\"modal\")).toString(),\n \"--mb-shadow\": getShadow(shadow),\n \"--mb-padding\": getSpacing(padding)\n },\n children\n }\n )\n },\n removeScrollKey\n )\n }\n ) });\n }\n);\nModalBase.displayName = \"@mantine/core/ModalBase\";\n\nexport { ModalBase };\n//# sourceMappingURL=ModalBase.mjs.map\n","'use client';\nimport { useEffect } from 'react';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\n\nfunction useModalBodyId() {\n const ctx = useModalBaseContext();\n useEffect(() => {\n ctx.setBodyMounted(true);\n return () => ctx.setBodyMounted(false);\n }, []);\n return ctx.getBodyId();\n}\n\nexport { useModalBodyId };\n//# sourceMappingURL=use-modal-body-id.mjs.map\n","'use client';\nvar classes = {\"title\":\"m_615af6c9\",\"header\":\"m_b5489c3c\",\"inner\":\"m_60c222c7\",\"content\":\"m_fd1ab0aa\",\"close\":\"m_606cb269\",\"body\":\"m_5df29311\"};\n\nexport { classes as default };\n//# sourceMappingURL=ModalBase.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport cx from 'clsx';\nimport '@mantine/hooks';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\nimport { useModalBodyId } from './use-modal-body-id.mjs';\nimport classes from './ModalBase.module.css.mjs';\n\nconst ModalBaseBody = forwardRef(\n ({ className, ...others }, ref) => {\n const bodyId = useModalBodyId();\n const ctx = useModalBaseContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n ...others,\n id: bodyId,\n className: cx({ [classes.body]: !ctx.unstyled }, className)\n }\n );\n }\n);\nModalBaseBody.displayName = \"@mantine/core/ModalBaseBody\";\n\nexport { ModalBaseBody };\n//# sourceMappingURL=ModalBaseBody.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport cx from 'clsx';\nimport '../CloseButton/CloseIcon.mjs';\nimport { CloseButton } from '../CloseButton/CloseButton.mjs';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\nimport classes from './ModalBase.module.css.mjs';\n\nconst ModalBaseCloseButton = forwardRef(\n ({ className, onClick, ...others }, ref) => {\n const ctx = useModalBaseContext();\n return /* @__PURE__ */ jsx(\n CloseButton,\n {\n ref,\n ...others,\n onClick: (event) => {\n ctx.onClose();\n onClick?.(event);\n },\n className: cx({ [classes.close]: !ctx.unstyled }, className),\n unstyled: ctx.unstyled\n }\n );\n }\n);\nModalBaseCloseButton.displayName = \"@mantine/core/ModalBaseCloseButton\";\n\nexport { ModalBaseCloseButton };\n//# sourceMappingURL=ModalBaseCloseButton.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport cx from 'clsx';\nimport { FocusTrap } from '../FocusTrap/FocusTrap.mjs';\nimport { Paper } from '../Paper/Paper.mjs';\nimport { Transition } from '../Transition/Transition.mjs';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\nimport classes from './ModalBase.module.css.mjs';\n\nconst ModalBaseContent = forwardRef(\n ({ transitionProps, className, innerProps, onKeyDown, style, ...others }, ref) => {\n const ctx = useModalBaseContext();\n return /* @__PURE__ */ jsx(\n Transition,\n {\n mounted: ctx.opened,\n transition: \"pop\",\n ...ctx.transitionProps,\n onExited: () => {\n ctx.onExitTransitionEnd?.();\n ctx.transitionProps?.onExited?.();\n },\n onEntered: () => {\n ctx.onEnterTransitionEnd?.();\n ctx.transitionProps?.onEntered?.();\n },\n ...transitionProps,\n children: (transitionStyles) => /* @__PURE__ */ jsx(\n \"div\",\n {\n ...innerProps,\n className: cx({ [classes.inner]: !ctx.unstyled }, innerProps.className),\n children: /* @__PURE__ */ jsx(FocusTrap, { active: ctx.opened && ctx.trapFocus, innerRef: ref, children: /* @__PURE__ */ jsx(\n Paper,\n {\n ...others,\n component: \"section\",\n role: \"dialog\",\n tabIndex: -1,\n \"aria-modal\": true,\n \"aria-describedby\": ctx.bodyMounted ? ctx.getBodyId() : void 0,\n \"aria-labelledby\": ctx.titleMounted ? ctx.getTitleId() : void 0,\n style: [style, transitionStyles],\n className: cx({ [classes.content]: !ctx.unstyled }, className),\n unstyled: ctx.unstyled,\n children: others.children\n }\n ) })\n }\n )\n }\n );\n }\n);\nModalBaseContent.displayName = \"@mantine/core/ModalBaseContent\";\n\nexport { ModalBaseContent };\n//# sourceMappingURL=ModalBaseContent.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport cx from 'clsx';\nimport '@mantine/hooks';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\nimport classes from './ModalBase.module.css.mjs';\n\nconst ModalBaseHeader = forwardRef(\n ({ className, ...others }, ref) => {\n const ctx = useModalBaseContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n component: \"header\",\n ref,\n className: cx({ [classes.header]: !ctx.unstyled }, className),\n ...others\n }\n );\n }\n);\nModalBaseHeader.displayName = \"@mantine/core/ModalBaseHeader\";\n\nexport { ModalBaseHeader };\n//# sourceMappingURL=ModalBaseHeader.mjs.map\n","'use client';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\n\nconst DEFAULT_TRANSITION = {\n duration: 200,\n timingFunction: \"ease\",\n transition: \"fade\"\n};\nfunction useModalTransition(transitionOverride) {\n const ctx = useModalBaseContext();\n return { ...DEFAULT_TRANSITION, ...ctx.transitionProps, ...transitionOverride };\n}\n\nexport { useModalTransition };\n//# sourceMappingURL=use-modal-transition.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport { Overlay } from '../Overlay/Overlay.mjs';\nimport { Transition } from '../Transition/Transition.mjs';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\nimport { useModalTransition } from './use-modal-transition.mjs';\n\nconst ModalBaseOverlay = forwardRef(\n ({ onClick, transitionProps, style, visible, ...others }, ref) => {\n const ctx = useModalBaseContext();\n const transition = useModalTransition(transitionProps);\n return /* @__PURE__ */ jsx(\n Transition,\n {\n mounted: visible !== void 0 ? visible : ctx.opened,\n ...transition,\n transition: \"fade\",\n children: (transitionStyles) => /* @__PURE__ */ jsx(\n Overlay,\n {\n ref,\n fixed: true,\n style: [style, transitionStyles],\n zIndex: ctx.zIndex,\n unstyled: ctx.unstyled,\n onClick: (event) => {\n onClick?.(event);\n ctx.closeOnClickOutside && ctx.onClose();\n },\n ...others\n }\n )\n }\n );\n }\n);\nModalBaseOverlay.displayName = \"@mantine/core/ModalBaseOverlay\";\n\nexport { ModalBaseOverlay };\n//# sourceMappingURL=ModalBaseOverlay.mjs.map\n","'use client';\nimport { useEffect } from 'react';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\n\nfunction useModalTitle() {\n const ctx = useModalBaseContext();\n useEffect(() => {\n ctx.setTitleMounted(true);\n return () => ctx.setTitleMounted(false);\n }, []);\n return ctx.getTitleId();\n}\n\nexport { useModalTitle };\n//# sourceMappingURL=use-modal-title-id.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport cx from 'clsx';\nimport '@mantine/hooks';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useModalBaseContext } from './ModalBase.context.mjs';\nimport { useModalTitle } from './use-modal-title-id.mjs';\nimport classes from './ModalBase.module.css.mjs';\n\nconst ModalBaseTitle = forwardRef(\n ({ className, ...others }, ref) => {\n const id = useModalTitle();\n const ctx = useModalBaseContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n component: \"h2\",\n ref,\n className: cx({ [classes.title]: !ctx.unstyled }, className),\n ...others,\n id\n }\n );\n }\n);\nModalBaseTitle.displayName = \"@mantine/core/ModalBaseTitle\";\n\nexport { ModalBaseTitle };\n//# sourceMappingURL=ModalBaseTitle.mjs.map\n","'use client';\nimport { jsx, Fragment } from 'react/jsx-runtime';\n\nfunction NativeScrollArea({ children }) {\n return /* @__PURE__ */ jsx(Fragment, { children });\n}\n\nexport { NativeScrollArea };\n//# sourceMappingURL=NativeScrollArea.mjs.map\n","'use client';\nconst FLEX_STYLE_PROPS_DATA = {\n gap: { type: \"spacing\", property: \"gap\" },\n rowGap: { type: \"spacing\", property: \"rowGap\" },\n columnGap: { type: \"spacing\", property: \"columnGap\" },\n align: { type: \"identity\", property: \"alignItems\" },\n justify: { type: \"identity\", property: \"justifyContent\" },\n wrap: { type: \"identity\", property: \"flexWrap\" },\n direction: { type: \"identity\", property: \"flexDirection\" }\n};\n\nexport { FLEX_STYLE_PROPS_DATA };\n//# sourceMappingURL=flex-props.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_8bffd616\"};\n\nexport { classes as default };\n//# sourceMappingURL=Flex.module.css.mjs.map\n","'use client';\nimport { jsxs, Fragment, jsx } from 'react/jsx-runtime';\nimport { filterProps } from '../../core/utils/filter-props/filter-props.mjs';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { InlineStyles } from '../../core/InlineStyles/InlineStyles.mjs';\nimport { parseStyleProps } from '../../core/Box/style-props/parse-style-props/parse-style-props.mjs';\nimport { useRandomClassName } from '../../core/Box/use-random-classname/use-random-classname.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../core/factory/polymorphic-factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { FLEX_STYLE_PROPS_DATA } from './flex-props.mjs';\nimport classes from './Flex.module.css.mjs';\n\nconst defaultProps = {};\nconst Flex = polymorphicFactory((_props, ref) => {\n const props = useProps(\"Flex\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n gap,\n rowGap,\n columnGap,\n align,\n justify,\n wrap,\n direction,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Flex\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars\n });\n const theme = useMantineTheme();\n const responsiveClassName = useRandomClassName();\n const parsedStyleProps = parseStyleProps({\n styleProps: { gap, rowGap, columnGap, align, justify, wrap, direction },\n theme,\n data: FLEX_STYLE_PROPS_DATA\n });\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n parsedStyleProps.hasResponsiveStyles && /* @__PURE__ */ jsx(\n InlineStyles,\n {\n selector: `.${responsiveClassName}`,\n styles: parsedStyleProps.styles,\n media: parsedStyleProps.media\n }\n ),\n /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n ...getStyles(\"root\", {\n className: responsiveClassName,\n style: filterProps(parsedStyleProps.inlineStyles)\n }),\n ...others\n }\n )\n ] });\n});\nFlex.classes = classes;\nFlex.displayName = \"@mantine/core/Flex\";\n\nexport { Flex };\n//# sourceMappingURL=Flex.mjs.map\n","'use client';\nimport { useRef, useState, useEffect } from 'react';\nimport { useTimeout, useMutationObserver } from '@mantine/hooks';\nimport 'react/jsx-runtime';\nimport { getEnv } from '../../core/utils/get-env/get-env.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { toInt } from '../ScrollArea/utils/to-int.mjs';\n\nfunction isParent(parentElement, childElement) {\n if (!childElement || !parentElement) {\n return false;\n }\n let parent = childElement.parentNode;\n while (parent != null) {\n if (parent === parentElement) {\n return true;\n }\n parent = parent.parentNode;\n }\n return false;\n}\nfunction useFloatingIndicator({\n target,\n parent,\n ref,\n displayAfterTransitionEnd\n}) {\n const transitionTimeout = useRef(-1);\n const [initialized, setInitialized] = useState(false);\n const [hidden, setHidden] = useState(\n typeof displayAfterTransitionEnd === \"boolean\" ? displayAfterTransitionEnd : false\n );\n const updatePosition = () => {\n if (!target || !parent || !ref.current) {\n return;\n }\n const targetRect = target.getBoundingClientRect();\n const parentRect = parent.getBoundingClientRect();\n const targetComputedStyle = window.getComputedStyle(target);\n const parentComputedStyle = window.getComputedStyle(parent);\n const borderTopWidth = toInt(targetComputedStyle.borderTopWidth) + toInt(parentComputedStyle.borderTopWidth);\n const borderLeftWidth = toInt(targetComputedStyle.borderLeftWidth) + toInt(parentComputedStyle.borderLeftWidth);\n const position = {\n top: targetRect.top - parentRect.top - borderTopWidth,\n left: targetRect.left - parentRect.left - borderLeftWidth,\n width: targetRect.width,\n height: targetRect.height\n };\n ref.current.style.transform = `translateY(${position.top}px) translateX(${position.left}px)`;\n ref.current.style.width = `${position.width}px`;\n ref.current.style.height = `${position.height}px`;\n };\n const updatePositionWithoutAnimation = () => {\n window.clearTimeout(transitionTimeout.current);\n if (ref.current) {\n ref.current.style.transitionDuration = \"0ms\";\n }\n updatePosition();\n transitionTimeout.current = window.setTimeout(() => {\n if (ref.current) {\n ref.current.style.transitionDuration = \"\";\n }\n }, 30);\n };\n const targetResizeObserver = useRef(null);\n const parentResizeObserver = useRef(null);\n useEffect(() => {\n updatePosition();\n if (target) {\n targetResizeObserver.current = new ResizeObserver(updatePositionWithoutAnimation);\n targetResizeObserver.current.observe(target);\n if (parent) {\n parentResizeObserver.current = new ResizeObserver(updatePositionWithoutAnimation);\n parentResizeObserver.current.observe(parent);\n }\n return () => {\n targetResizeObserver.current?.disconnect();\n parentResizeObserver.current?.disconnect();\n };\n }\n return void 0;\n }, [parent, target]);\n useEffect(() => {\n if (parent) {\n const handleTransitionEnd = (event) => {\n if (isParent(event.target, parent)) {\n updatePositionWithoutAnimation();\n setHidden(false);\n }\n };\n parent.addEventListener(\"transitionend\", handleTransitionEnd);\n return () => {\n parent.removeEventListener(\"transitionend\", handleTransitionEnd);\n };\n }\n return void 0;\n }, [parent]);\n useTimeout(\n () => {\n if (getEnv() !== \"test\") {\n setInitialized(true);\n }\n },\n 20,\n { autoInvoke: true }\n );\n useMutationObserver(\n (mutations) => {\n mutations.forEach((mutation) => {\n if (mutation.type === \"attributes\" && mutation.attributeName === \"dir\") {\n updatePositionWithoutAnimation();\n }\n });\n },\n { attributes: true, attributeFilter: [\"dir\"] },\n () => document.documentElement\n );\n return { initialized, hidden };\n}\n\nexport { useFloatingIndicator };\n//# sourceMappingURL=use-floating-indicator.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_96b553a6\"};\n\nexport { classes as default };\n//# sourceMappingURL=FloatingIndicator.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useRef } from 'react';\nimport { useMergedRef } from '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useFloatingIndicator } from './use-floating-indicator.mjs';\nimport classes from './FloatingIndicator.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver(\n (_theme, { transitionDuration }) => ({\n root: {\n \"--transition-duration\": typeof transitionDuration === \"number\" ? `${transitionDuration}ms` : transitionDuration\n }\n })\n);\nconst FloatingIndicator = factory((_props, ref) => {\n const props = useProps(\"FloatingIndicator\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n target,\n parent,\n transitionDuration,\n mod,\n displayAfterTransitionEnd,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"FloatingIndicator\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const innerRef = useRef(null);\n const { initialized, hidden } = useFloatingIndicator({\n target,\n parent,\n ref: innerRef,\n displayAfterTransitionEnd\n });\n const mergedRef = useMergedRef(ref, innerRef);\n if (!target || !parent) {\n return null;\n }\n return /* @__PURE__ */ jsx(Box, { ref: mergedRef, mod: [{ initialized, hidden }, mod], ...getStyles(\"root\"), ...others });\n});\nFloatingIndicator.displayName = \"@mantine/core/FloatingIndicator\";\nFloatingIndicator.classes = classes;\n\nexport { FloatingIndicator };\n//# sourceMappingURL=FloatingIndicator.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [AccordionProvider, useAccordionContext] = createSafeContext(\n \"Accordion component was not found in the tree\"\n);\n\nexport { AccordionProvider, useAccordionContext };\n//# sourceMappingURL=Accordion.context.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nfunction AccordionChevron({ style, size = 16, ...others }) {\n return /* @__PURE__ */ jsx(\n \"svg\",\n {\n viewBox: \"0 0 15 15\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\",\n style: { ...style, width: rem(size), height: rem(size), display: \"block\" },\n ...others,\n children: /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z\",\n fill: \"currentColor\",\n fillRule: \"evenodd\",\n clipRule: \"evenodd\"\n }\n )\n }\n );\n}\nAccordionChevron.displayName = \"@mantine/core/AccordionChevron\";\n\nexport { AccordionChevron };\n//# sourceMappingURL=AccordionChevron.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [AccordionItemProvider, useAccordionItemContext] = createSafeContext(\"Accordion.Item component was not found in the tree\");\n\nexport { AccordionItemProvider, useAccordionItemContext };\n//# sourceMappingURL=AccordionItem.context.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_9bdbb667\",\"panel\":\"m_df78851f\",\"content\":\"m_4ba554d4\",\"itemTitle\":\"m_8fa820a0\",\"control\":\"m_4ba585b8\",\"control--default\":\"m_6939a5e9\",\"control--contained\":\"m_4271d21b\",\"label\":\"m_df3ffa0f\",\"chevron\":\"m_3f35ae96\",\"icon\":\"m_9bd771fe\",\"item\":\"m_9bd7b098\",\"item--default\":\"m_fe19b709\",\"item--contained\":\"m_1f921b3b\",\"item--filled\":\"m_2cdf939a\",\"item--separated\":\"m_9f59b069\"};\n\nexport { classes as default };\n//# sourceMappingURL=Accordion.module.css.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport 'react';\nimport { createScopedKeydownHandler } from '../../../core/utils/create-scoped-keydown-handler/create-scoped-keydown-handler.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { UnstyledButton } from '../../UnstyledButton/UnstyledButton.mjs';\nimport { useAccordionContext } from '../Accordion.context.mjs';\nimport { useAccordionItemContext } from '../AccordionItem.context.mjs';\nimport classes from '../Accordion.module.css.mjs';\n\nconst defaultProps = {};\nconst AccordionControl = factory((props, ref) => {\n const {\n classNames,\n className,\n style,\n styles,\n vars,\n chevron,\n icon,\n onClick,\n onKeyDown,\n children,\n disabled,\n mod,\n ...others\n } = useProps(\"AccordionControl\", defaultProps, props);\n const { value } = useAccordionItemContext();\n const ctx = useAccordionContext();\n const isActive = ctx.isItemActive(value);\n const shouldWrapWithHeading = typeof ctx.order === \"number\";\n const Heading = `h${ctx.order}`;\n const content = /* @__PURE__ */ jsxs(\n UnstyledButton,\n {\n ...others,\n ...ctx.getStyles(\"control\", { className, classNames, style, styles, variant: ctx.variant }),\n unstyled: ctx.unstyled,\n mod: [\n \"accordion-control\",\n { active: isActive, \"chevron-position\": ctx.chevronPosition, disabled },\n mod\n ],\n ref,\n onClick: (event) => {\n onClick?.(event);\n ctx.onChange(value);\n },\n type: \"button\",\n disabled,\n \"aria-expanded\": isActive,\n \"aria-controls\": ctx.getRegionId(value),\n id: ctx.getControlId(value),\n onKeyDown: createScopedKeydownHandler({\n siblingSelector: \"[data-accordion-control]\",\n parentSelector: \"[data-accordion]\",\n activateOnFocus: false,\n loop: ctx.loop,\n orientation: \"vertical\",\n onKeyDown\n }),\n children: [\n /* @__PURE__ */ jsx(\n Box,\n {\n component: \"span\",\n mod: { rotate: !ctx.disableChevronRotation && isActive, position: ctx.chevronPosition },\n ...ctx.getStyles(\"chevron\", { classNames, styles }),\n children: chevron || ctx.chevron\n }\n ),\n /* @__PURE__ */ jsx(\"span\", { ...ctx.getStyles(\"label\", { classNames, styles }), children }),\n icon && /* @__PURE__ */ jsx(\n Box,\n {\n component: \"span\",\n mod: { \"chevron-position\": ctx.chevronPosition },\n ...ctx.getStyles(\"icon\", { classNames, styles }),\n children: icon\n }\n )\n ]\n }\n );\n return shouldWrapWithHeading ? /* @__PURE__ */ jsx(Heading, { ...ctx.getStyles(\"itemTitle\", { classNames, styles }), children: content }) : content;\n});\nAccordionControl.displayName = \"@mantine/core/AccordionControl\";\nAccordionControl.classes = classes;\n\nexport { AccordionControl };\n//# sourceMappingURL=AccordionControl.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useAccordionContext } from '../Accordion.context.mjs';\nimport { AccordionItemProvider } from '../AccordionItem.context.mjs';\nimport classes from '../Accordion.module.css.mjs';\n\nconst defaultProps = {};\nconst AccordionItem = factory((props, ref) => {\n const { classNames, className, style, styles, vars, value, mod, ...others } = useProps(\n \"AccordionItem\",\n defaultProps,\n props\n );\n const ctx = useAccordionContext();\n return /* @__PURE__ */ jsx(AccordionItemProvider, { value: { value }, children: /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n mod: [{ active: ctx.isItemActive(value) }, mod],\n ...ctx.getStyles(\"item\", { className, classNames, styles, style, variant: ctx.variant }),\n ...others\n }\n ) });\n});\nAccordionItem.displayName = \"@mantine/core/AccordionItem\";\nAccordionItem.classes = classes;\n\nexport { AccordionItem };\n//# sourceMappingURL=AccordionItem.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Collapse } from '../../Collapse/Collapse.mjs';\nimport { useAccordionContext } from '../Accordion.context.mjs';\nimport { useAccordionItemContext } from '../AccordionItem.context.mjs';\nimport classes from '../Accordion.module.css.mjs';\n\nconst defaultProps = {};\nconst AccordionPanel = factory((props, ref) => {\n const { classNames, className, style, styles, vars, children, ...others } = useProps(\n \"AccordionPanel\",\n defaultProps,\n props\n );\n const { value } = useAccordionItemContext();\n const ctx = useAccordionContext();\n return /* @__PURE__ */ jsx(\n Collapse,\n {\n ref,\n ...ctx.getStyles(\"panel\", { className, classNames, style, styles }),\n ...others,\n in: ctx.isItemActive(value),\n transitionDuration: ctx.transitionDuration ?? 200,\n role: \"region\",\n id: ctx.getRegionId(value),\n \"aria-labelledby\": ctx.getControlId(value),\n children: /* @__PURE__ */ jsx(\"div\", { ...ctx.getStyles(\"content\", { classNames, styles }), children })\n }\n );\n});\nAccordionPanel.displayName = \"@mantine/core/AccordionPanel\";\nAccordionPanel.classes = classes;\n\nexport { AccordionPanel };\n//# sourceMappingURL=AccordionPanel.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useId, useUncontrolled } from '@mantine/hooks';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport { getSafeId } from '../../core/utils/get-safe-id/get-safe-id.mjs';\nimport { getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { getWithProps } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { AccordionProvider } from './Accordion.context.mjs';\nimport { AccordionChevron } from './AccordionChevron.mjs';\nimport { AccordionControl } from './AccordionControl/AccordionControl.mjs';\nimport { AccordionItem } from './AccordionItem/AccordionItem.mjs';\nimport { AccordionPanel } from './AccordionPanel/AccordionPanel.mjs';\nimport classes from './Accordion.module.css.mjs';\n\nconst defaultProps = {\n multiple: false,\n disableChevronRotation: false,\n chevronPosition: \"right\",\n variant: \"default\",\n chevron: /* @__PURE__ */ jsx(AccordionChevron, {})\n};\nconst varsResolver = createVarsResolver(\n (_, { transitionDuration, chevronSize, radius }) => ({\n root: {\n \"--accordion-transition-duration\": transitionDuration === void 0 ? void 0 : `${transitionDuration}ms`,\n \"--accordion-chevron-size\": chevronSize === void 0 ? void 0 : rem(chevronSize),\n \"--accordion-radius\": radius === void 0 ? void 0 : getRadius(radius)\n }\n })\n);\nfunction Accordion(_props) {\n const props = useProps(\"Accordion\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n children,\n multiple,\n value,\n defaultValue,\n onChange,\n id,\n loop,\n transitionDuration,\n disableChevronRotation,\n chevronPosition,\n chevronSize,\n order,\n chevron,\n variant,\n radius,\n ...others\n } = props;\n const uid = useId(id);\n const [_value, handleChange] = useUncontrolled({\n value,\n defaultValue,\n finalValue: multiple ? [] : null,\n onChange\n });\n const isItemActive = (itemValue) => Array.isArray(_value) ? _value.includes(itemValue) : itemValue === _value;\n const handleItemChange = (itemValue) => {\n const nextValue = Array.isArray(_value) ? _value.includes(itemValue) ? _value.filter((selectedValue) => selectedValue !== itemValue) : [..._value, itemValue] : itemValue === _value ? null : itemValue;\n handleChange(nextValue);\n };\n const getStyles = useStyles({\n name: \"Accordion\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(\n AccordionProvider,\n {\n value: {\n isItemActive,\n onChange: handleItemChange,\n getControlId: getSafeId(\n `${uid}-control`,\n \"Accordion.Item component was rendered with invalid value or without value\"\n ),\n getRegionId: getSafeId(\n `${uid}-panel`,\n \"Accordion.Item component was rendered with invalid value or without value\"\n ),\n transitionDuration,\n disableChevronRotation,\n chevronPosition,\n order,\n chevron,\n loop,\n getStyles,\n variant,\n unstyled\n },\n children: /* @__PURE__ */ jsx(Box, { ...getStyles(\"root\"), id: uid, ...others, variant, \"data-accordion\": true, children })\n }\n );\n}\nconst extendAccordion = (c) => c;\nAccordion.extend = extendAccordion;\nAccordion.withProps = getWithProps(Accordion);\nAccordion.classes = classes;\nAccordion.displayName = \"@mantine/core/Accordion\";\nAccordion.Item = AccordionItem;\nAccordion.Panel = AccordionPanel;\nAccordion.Control = AccordionControl;\nAccordion.Chevron = AccordionChevron;\n\nexport { Accordion };\n//# sourceMappingURL=Accordion.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_66836ed3\",\"wrapper\":\"m_a5d60502\",\"body\":\"m_667c2793\",\"title\":\"m_6a03f287\",\"label\":\"m_698f4f23\",\"icon\":\"m_667f2a6a\",\"message\":\"m_7fa78076\",\"closeButton\":\"m_87f54839\"};\n\nexport { classes as default };\n//# sourceMappingURL=Alert.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { useId } from '@mantine/hooks';\nimport 'react';\nimport { getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../CloseButton/CloseIcon.mjs';\nimport { CloseButton } from '../CloseButton/CloseButton.mjs';\nimport classes from './Alert.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver(\n (theme, { radius, color, variant, autoContrast }) => {\n const colors = theme.variantColorResolver({\n color: color || theme.primaryColor,\n theme,\n variant: variant || \"light\",\n autoContrast\n });\n return {\n root: {\n \"--alert-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--alert-bg\": color || variant ? colors.background : void 0,\n \"--alert-color\": colors.color,\n \"--alert-bd\": color || variant ? colors.border : void 0\n }\n };\n }\n);\nconst Alert = factory((_props, ref) => {\n const props = useProps(\"Alert\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n radius,\n color,\n title,\n children,\n id,\n icon,\n withCloseButton,\n onClose,\n closeButtonLabel,\n variant,\n autoContrast,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Alert\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const rootId = useId(id);\n const titleId = title && `${rootId}-title` || void 0;\n const bodyId = `${rootId}-body`;\n return /* @__PURE__ */ jsx(\n Box,\n {\n id: rootId,\n ...getStyles(\"root\", { variant }),\n variant,\n ref,\n ...others,\n role: \"alert\",\n \"aria-describedby\": bodyId,\n \"aria-labelledby\": titleId,\n children: /* @__PURE__ */ jsxs(\"div\", { ...getStyles(\"wrapper\"), children: [\n icon && /* @__PURE__ */ jsx(\"div\", { ...getStyles(\"icon\"), children: icon }),\n /* @__PURE__ */ jsxs(\"div\", { ...getStyles(\"body\"), children: [\n title && /* @__PURE__ */ jsx(\"div\", { ...getStyles(\"title\"), \"data-with-close-button\": withCloseButton || void 0, children: /* @__PURE__ */ jsx(\"span\", { id: titleId, ...getStyles(\"label\"), children: title }) }),\n children && /* @__PURE__ */ jsx(\"div\", { id: bodyId, ...getStyles(\"message\"), \"data-variant\": variant, children })\n ] }),\n withCloseButton && /* @__PURE__ */ jsx(\n CloseButton,\n {\n ...getStyles(\"closeButton\"),\n onClick: onClose,\n variant: \"transparent\",\n size: 16,\n iconSize: 16,\n \"aria-label\": closeButtonLabel,\n unstyled\n }\n )\n ] })\n }\n );\n});\nAlert.classes = classes;\nAlert.displayName = \"@mantine/core/Alert\";\n\nexport { Alert };\n//# sourceMappingURL=Alert.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_71ac47fc\"};\n\nexport { classes as default };\n//# sourceMappingURL=AspectRatio.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './AspectRatio.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver((_, { ratio }) => ({\n root: {\n \"--ar-ratio\": ratio?.toString()\n }\n}));\nconst AspectRatio = factory((_props, ref) => {\n const props = useProps(\"AspectRatio\", defaultProps, _props);\n const { classNames, className, style, styles, unstyled, vars, ratio, ...others } = props;\n const getStyles = useStyles({\n name: \"AspectRatio\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\"), ...others });\n});\nAspectRatio.classes = classes;\nAspectRatio.displayName = \"@mantine/core/AspectRatio\";\n\nexport { AspectRatio };\n//# sourceMappingURL=AspectRatio.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_347db0ec\",\"root--dot\":\"m_fbd81e3d\",\"label\":\"m_5add502a\",\"section\":\"m_91fdda9b\"};\n\nexport { classes as default };\n//# sourceMappingURL=Badge.module.css.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport 'react';\nimport { getSize, getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { getThemeColor } from '../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../core/factory/polymorphic-factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './Badge.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver(\n (theme, { radius, color, gradient, variant, size, autoContrast }) => {\n const colors = theme.variantColorResolver({\n color: color || theme.primaryColor,\n theme,\n gradient,\n variant: variant || \"filled\",\n autoContrast\n });\n return {\n root: {\n \"--badge-height\": getSize(size, \"badge-height\"),\n \"--badge-padding-x\": getSize(size, \"badge-padding-x\"),\n \"--badge-fz\": getSize(size, \"badge-fz\"),\n \"--badge-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--badge-bg\": color || variant ? colors.background : void 0,\n \"--badge-color\": color || variant ? colors.color : void 0,\n \"--badge-bd\": color || variant ? colors.border : void 0,\n \"--badge-dot-color\": variant === \"dot\" ? getThemeColor(color, theme) : void 0\n }\n };\n }\n);\nconst Badge = polymorphicFactory((_props, ref) => {\n const props = useProps(\"Badge\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n radius,\n color,\n gradient,\n leftSection,\n rightSection,\n children,\n variant,\n fullWidth,\n autoContrast,\n circle,\n mod,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Badge\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsxs(\n Box,\n {\n variant,\n mod: [\n {\n block: fullWidth,\n circle,\n \"with-right-section\": !!rightSection,\n \"with-left-section\": !!leftSection\n },\n mod\n ],\n ...getStyles(\"root\", { variant }),\n ref,\n ...others,\n children: [\n leftSection && /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"section\"), \"data-position\": \"left\", children: leftSection }),\n /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"label\"), children }),\n rightSection && /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"section\"), \"data-position\": \"right\", children: rightSection })\n ]\n }\n );\n});\nBadge.classes = classes;\nBadge.displayName = \"@mantine/core/Badge\";\n\nexport { Badge };\n//# sourceMappingURL=Badge.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [CardProvider, useCardContext] = createSafeContext(\n \"Card component was not found in tree\"\n);\n\nexport { CardProvider, useCardContext };\n//# sourceMappingURL=Card.context.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_e615b15f\",\"section\":\"m_599a2148\"};\n\nexport { classes as default };\n//# sourceMappingURL=Card.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../../core/factory/polymorphic-factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useCardContext } from '../Card.context.mjs';\nimport classes from '../Card.module.css.mjs';\n\nconst defaultProps = {};\nconst CardSection = polymorphicFactory((_props, ref) => {\n const props = useProps(\"CardSection\", defaultProps, _props);\n const { classNames, className, style, styles, vars, withBorder, inheritPadding, mod, ...others } = props;\n const ctx = useCardContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n mod: [{ \"with-border\": withBorder, \"inherit-padding\": inheritPadding }, mod],\n ...ctx.getStyles(\"section\", { className, style, styles, classNames }),\n ...others\n }\n );\n});\nCardSection.classes = classes;\nCardSection.displayName = \"@mantine/core/CardSection\";\n\nexport { CardSection };\n//# sourceMappingURL=CardSection.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { Children, cloneElement } from 'react';\nimport { getSpacing } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport '../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../core/factory/polymorphic-factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Paper } from '../Paper/Paper.mjs';\nimport { CardProvider } from './Card.context.mjs';\nimport { CardSection } from './CardSection/CardSection.mjs';\nimport classes from './Card.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver((_, { padding }) => ({\n root: {\n \"--card-padding\": getSpacing(padding)\n }\n}));\nconst Card = polymorphicFactory((_props, ref) => {\n const props = useProps(\"Card\", defaultProps, _props);\n const { classNames, className, style, styles, unstyled, vars, children, padding, ...others } = props;\n const getStyles = useStyles({\n name: \"Card\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const _children = Children.toArray(children);\n const content = _children.map((child, index) => {\n if (typeof child === \"object\" && child && \"type\" in child && child.type === CardSection) {\n return cloneElement(child, {\n \"data-first-section\": index === 0 || void 0,\n \"data-last-section\": index === _children.length - 1 || void 0\n });\n }\n return child;\n });\n return /* @__PURE__ */ jsx(CardProvider, { value: { getStyles }, children: /* @__PURE__ */ jsx(Paper, { ref, unstyled, ...getStyles(\"root\"), ...others, children: content }) });\n});\nCard.classes = classes;\nCard.displayName = \"@mantine/core/Card\";\nCard.Section = CardSection;\n\nexport { Card };\n//# sourceMappingURL=Card.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_4451eb3a\"};\n\nexport { classes as default };\n//# sourceMappingURL=Center.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../core/factory/polymorphic-factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './Center.module.css.mjs';\n\nconst defaultProps = {};\nconst Center = polymorphicFactory((_props, ref) => {\n const props = useProps(\"Center\", defaultProps, _props);\n const { classNames, className, style, styles, unstyled, vars, inline, mod, ...others } = props;\n const getStyles = useStyles({\n name: \"Center\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars\n });\n return /* @__PURE__ */ jsx(Box, { ref, mod: [{ inline }, mod], ...getStyles(\"root\"), ...others });\n});\nCenter.classes = classes;\nCenter.displayName = \"@mantine/core/Center\";\n\nexport { Center };\n//# sourceMappingURL=Center.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_de3d2490\",\"colorOverlay\":\"m_862f3d1b\",\"shadowOverlay\":\"m_98ae7f22\",\"alphaOverlay\":\"m_95709ac0\",\"childrenOverlay\":\"m_93e74e3\"};\n\nexport { classes as default };\n//# sourceMappingURL=ColorSwatch.module.css.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport { getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../core/factory/polymorphic-factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './ColorSwatch.module.css.mjs';\n\nconst defaultProps = {\n withShadow: true\n};\nconst varsResolver = createVarsResolver((_, { radius, size }) => ({\n root: {\n \"--cs-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--cs-size\": rem(size)\n }\n}));\nconst ColorSwatch = polymorphicFactory((_props, ref) => {\n const props = useProps(\"ColorSwatch\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n color,\n size,\n radius,\n withShadow,\n children,\n variant,\n ...others\n } = useProps(\"ColorSwatch\", defaultProps, props);\n const getStyles = useStyles({\n name: \"ColorSwatch\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsxs(\n Box,\n {\n ref,\n variant,\n size,\n ...getStyles(\"root\", { focusable: true }),\n ...others,\n children: [\n /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"alphaOverlay\") }),\n withShadow && /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"shadowOverlay\") }),\n /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"colorOverlay\", { style: { backgroundColor: color } }) }),\n /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"childrenOverlay\"), children })\n ]\n }\n );\n});\nColorSwatch.classes = classes;\nColorSwatch.displayName = \"@mantine/core/ColorSwatch\";\n\nexport { ColorSwatch };\n//# sourceMappingURL=ColorSwatch.mjs.map\n","'use client';\nimport 'react';\nimport 'react/jsx-runtime';\nimport { createOptionalContext } from '../../core/utils/create-optional-context/create-optional-context.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [ColorPickerProvider, useColorPickerContext] = createOptionalContext(null);\n\nexport { ColorPickerProvider, useColorPickerContext };\n//# sourceMappingURL=ColorPicker.context.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst Thumb = forwardRef(({ position, ...others }, ref) => /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n __vars: {\n \"--thumb-y-offset\": `${position.y * 100}%`,\n \"--thumb-x-offset\": `${position.x * 100}%`\n },\n ...others\n }\n));\nThumb.displayName = \"@mantine/core/ColorPickerThumb\";\n\nexport { Thumb };\n//# sourceMappingURL=Thumb.mjs.map\n","'use client';\nvar classes = {\"wrapper\":\"m_fee9c77\",\"preview\":\"m_9dddfbac\",\"body\":\"m_bffecc3e\",\"sliders\":\"m_3283bb96\",\"thumb\":\"m_40d572ba\",\"swatch\":\"m_d8ee6fd8\",\"swatches\":\"m_5711e686\",\"saturation\":\"m_202a296e\",\"saturationOverlay\":\"m_11b3db02\",\"slider\":\"m_d856d47d\",\"sliderOverlay\":\"m_8f327113\"};\n\nexport { classes as default };\n//# sourceMappingURL=ColorPicker.module.css.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useState, useRef, createElement } from 'react';\nimport { useMove, useDidUpdate, useMergedRef, clampUseMovePosition } from '@mantine/hooks';\nimport { rem } from '../../../core/utils/units-converters/rem.mjs';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useColorPickerContext } from '../ColorPicker.context.mjs';\nimport { Thumb } from '../Thumb/Thumb.mjs';\nimport classes from '../ColorPicker.module.css.mjs';\n\nconst defaultProps = {};\nconst ColorSlider = factory((_props, ref) => {\n const props = useProps(\"ColorSlider\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n onChange,\n onChangeEnd,\n maxValue,\n round,\n size = \"md\",\n focusable = true,\n value,\n overlays,\n thumbColor = \"transparent\",\n onScrubStart,\n onScrubEnd,\n __staticSelector = \"ColorPicker\",\n ...others\n } = props;\n const _getStyles = useStyles({\n name: __staticSelector,\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled\n });\n const ctxGetStyles = useColorPickerContext()?.getStyles;\n const getStyles = ctxGetStyles || _getStyles;\n const theme = useMantineTheme();\n const [position, setPosition] = useState({ y: 0, x: value / maxValue });\n const positionRef = useRef(position);\n const getChangeValue = (val) => round ? Math.round(val * maxValue) : val * maxValue;\n const { ref: sliderRef } = useMove(\n ({ x, y }) => {\n positionRef.current = { x, y };\n onChange?.(getChangeValue(x));\n },\n {\n onScrubEnd: () => {\n const { x } = positionRef.current;\n onChangeEnd?.(getChangeValue(x));\n onScrubEnd?.();\n },\n onScrubStart\n }\n );\n useDidUpdate(() => {\n setPosition({ y: 0, x: value / maxValue });\n }, [value]);\n const handleArrow = (event, pos) => {\n event.preventDefault();\n const _position = clampUseMovePosition(pos);\n onChange?.(getChangeValue(_position.x));\n onChangeEnd?.(getChangeValue(_position.x));\n };\n const handleKeyDown = (event) => {\n switch (event.key) {\n case \"ArrowRight\": {\n handleArrow(event, { x: position.x + 0.05, y: position.y });\n break;\n }\n case \"ArrowLeft\": {\n handleArrow(event, { x: position.x - 0.05, y: position.y });\n break;\n }\n }\n };\n const layers = overlays.map((overlay, index) => /* @__PURE__ */ createElement(\"div\", { ...getStyles(\"sliderOverlay\"), style: overlay, key: index }));\n return /* @__PURE__ */ jsxs(\n Box,\n {\n ...others,\n ref: useMergedRef(sliderRef, ref),\n ...getStyles(\"slider\"),\n role: \"slider\",\n \"aria-valuenow\": value,\n \"aria-valuemax\": maxValue,\n \"aria-valuemin\": 0,\n tabIndex: focusable ? 0 : -1,\n onKeyDown: handleKeyDown,\n \"data-focus-ring\": theme.focusRing,\n __vars: {\n \"--cp-thumb-size\": `var(--cp-thumb-size-${size})`\n },\n children: [\n layers,\n /* @__PURE__ */ jsx(\n Thumb,\n {\n position,\n ...getStyles(\"thumb\", { style: { top: rem(1), background: thumbColor } })\n }\n )\n ]\n }\n );\n});\nColorSlider.displayName = \"@mantine/core/ColorSlider\";\n\nexport { ColorSlider };\n//# sourceMappingURL=ColorSlider.mjs.map\n","'use client';\nfunction round(number, digits = 0, base = 10 ** digits) {\n return Math.round(base * number) / base;\n}\nfunction hslaToHsva({ h, s, l, a }) {\n const ss = s * ((l < 50 ? l : 100 - l) / 100);\n return {\n h,\n s: ss > 0 ? 2 * ss / (l + ss) * 100 : 0,\n v: l + ss,\n a\n };\n}\nconst angleUnits = {\n grad: 360 / 400,\n turn: 360,\n rad: 360 / (Math.PI * 2)\n};\nfunction parseHue(value, unit = \"deg\") {\n return Number(value) * (angleUnits[unit] || 1);\n}\nconst HSL_REGEXP = /hsla?\\(?\\s*(-?\\d*\\.?\\d+)(deg|rad|grad|turn)?[,\\s]+(-?\\d*\\.?\\d+)%?[,\\s]+(-?\\d*\\.?\\d+)%?,?\\s*[/\\s]*(-?\\d*\\.?\\d+)?(%)?\\s*\\)?/i;\nfunction parseHsla(color) {\n const match = HSL_REGEXP.exec(color);\n if (!match) {\n return { h: 0, s: 0, v: 0, a: 1 };\n }\n return hslaToHsva({\n h: parseHue(match[1], match[2]),\n s: Number(match[3]),\n l: Number(match[4]),\n a: match[5] === void 0 ? 1 : Number(match[5]) / (match[6] ? 100 : 1)\n });\n}\nfunction rgbaToHsva({ r, g, b, a }) {\n const max = Math.max(r, g, b);\n const delta = max - Math.min(r, g, b);\n const hh = delta ? max === r ? (g - b) / delta : max === g ? 2 + (b - r) / delta : 4 + (r - g) / delta : 0;\n return {\n h: round(60 * (hh < 0 ? hh + 6 : hh), 3),\n s: round(max ? delta / max * 100 : 0, 3),\n v: round(max / 255 * 100, 3),\n a\n };\n}\nfunction parseHex(color) {\n const hex = color[0] === \"#\" ? color.slice(1) : color;\n if (hex.length === 3) {\n return rgbaToHsva({\n r: parseInt(hex[0] + hex[0], 16),\n g: parseInt(hex[1] + hex[1], 16),\n b: parseInt(hex[2] + hex[2], 16),\n a: 1\n });\n }\n return rgbaToHsva({\n r: parseInt(hex.slice(0, 2), 16),\n g: parseInt(hex.slice(2, 4), 16),\n b: parseInt(hex.slice(4, 6), 16),\n a: 1\n });\n}\nfunction parseHexa(color) {\n const hex = color[0] === \"#\" ? color.slice(1) : color;\n const roundA = (a2) => round(parseInt(a2, 16) / 255, 3);\n if (hex.length === 4) {\n const withoutOpacity2 = hex.slice(0, 3);\n const a2 = roundA(hex[3] + hex[3]);\n const hsvaColor2 = { ...parseHex(withoutOpacity2), a: a2 };\n return hsvaColor2;\n }\n const withoutOpacity = hex.slice(0, 6);\n const a = roundA(hex.slice(6, 8));\n const hsvaColor = { ...parseHex(withoutOpacity), a };\n return hsvaColor;\n}\nconst RGB_REGEXP = /rgba?\\(?\\s*(-?\\d*\\.?\\d+)(%)?[,\\s]+(-?\\d*\\.?\\d+)(%)?[,\\s]+(-?\\d*\\.?\\d+)(%)?,?\\s*[/\\s]*(-?\\d*\\.?\\d+)?(%)?\\s*\\)?/i;\nfunction parseRgba(color) {\n const match = RGB_REGEXP.exec(color);\n if (!match) {\n return { h: 0, s: 0, v: 0, a: 1 };\n }\n return rgbaToHsva({\n r: Number(match[1]) / (match[2] ? 100 / 255 : 1),\n g: Number(match[3]) / (match[4] ? 100 / 255 : 1),\n b: Number(match[5]) / (match[6] ? 100 / 255 : 1),\n a: match[7] === void 0 ? 1 : Number(match[7]) / (match[8] ? 100 : 1)\n });\n}\nconst VALIDATION_REGEXP = {\n hex: /^#?([0-9A-F]{3}){1,2}$/i,\n hexa: /^#?([0-9A-F]{4}){1,2}$/i,\n rgb: /^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*(\\d+(?:\\.\\d+)?))?\\)$/i,\n rgba: /^rgba\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*(\\d+(?:\\.\\d+)?))?\\)$/i,\n hsl: /hsl\\(\\s*(\\d+)\\s*,\\s*(\\d+(?:\\.\\d+)?%)\\s*,\\s*(\\d+(?:\\.\\d+)?%)\\)/i,\n hsla: /^hsla\\((\\d+),\\s*([\\d.]+)%,\\s*([\\d.]+)%,\\s*(\\d*(?:\\.\\d+)?)\\)$/i\n};\nconst CONVERTERS = {\n hex: parseHex,\n hexa: parseHexa,\n rgb: parseRgba,\n rgba: parseRgba,\n hsl: parseHsla,\n hsla: parseHsla\n};\nfunction isColorValid(color) {\n for (const [, regexp] of Object.entries(VALIDATION_REGEXP)) {\n if (regexp.test(color)) {\n return true;\n }\n }\n return false;\n}\nfunction parseColor(color) {\n if (typeof color !== \"string\") {\n return { h: 0, s: 0, v: 0, a: 1 };\n }\n if (color === \"transparent\") {\n return { h: 0, s: 0, v: 0, a: 0 };\n }\n const trimmed = color.trim();\n for (const [rule, regexp] of Object.entries(VALIDATION_REGEXP)) {\n if (regexp.test(trimmed)) {\n return CONVERTERS[rule](trimmed);\n }\n }\n return { h: 0, s: 0, v: 0, a: 1 };\n}\n\nexport { isColorValid, parseColor, parseHex, parseHexa, parseHsla, parseHue, parseRgba, round };\n//# sourceMappingURL=parsers.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport { rem } from '../../../core/utils/units-converters/rem.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ColorSlider } from '../ColorSlider/ColorSlider.mjs';\nimport { round } from '../converters/parsers.mjs';\n\nconst defaultProps = {};\nconst AlphaSlider = forwardRef((props, ref) => {\n const { value, onChange, onChangeEnd, color, ...others } = useProps(\n \"AlphaSlider\",\n defaultProps,\n props\n );\n return /* @__PURE__ */ jsx(\n ColorSlider,\n {\n ...others,\n ref,\n value,\n onChange: (val) => onChange?.(round(val, 2)),\n onChangeEnd: (val) => onChangeEnd?.(round(val, 2)),\n maxValue: 1,\n round: false,\n \"data-alpha\": true,\n overlays: [\n {\n backgroundImage: \"linear-gradient(45deg, var(--slider-checkers) 25%, transparent 25%), linear-gradient(-45deg, var(--slider-checkers) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--slider-checkers) 75%), linear-gradient(-45deg, var(--mantine-color-body) 75%, var(--slider-checkers) 75%)\",\n backgroundSize: `${rem(8)} ${rem(8)}`,\n backgroundPosition: `0 0, 0 ${rem(4)}, ${rem(4)} ${rem(-4)}, ${rem(-4)} 0`\n },\n {\n backgroundImage: `linear-gradient(90deg, transparent, ${color})`\n },\n {\n boxShadow: `rgba(0, 0, 0, .1) 0 0 0 ${rem(1)} inset, rgb(0, 0, 0, .15) 0 0 ${rem(\n 4\n )} inset`\n }\n ]\n }\n );\n});\nAlphaSlider.displayName = \"@mantine/core/AlphaSlider\";\n\nexport { AlphaSlider };\n//# sourceMappingURL=AlphaSlider.mjs.map\n","'use client';\nimport { round } from './parsers.mjs';\n\nfunction hsvaToRgbaObject({ h, s, v, a }) {\n const _h = h / 360 * 6;\n const _s = s / 100;\n const _v = v / 100;\n const hh = Math.floor(_h);\n const l = _v * (1 - _s);\n const c = _v * (1 - (_h - hh) * _s);\n const d = _v * (1 - (1 - _h + hh) * _s);\n const module = hh % 6;\n return {\n r: round([_v, c, l, l, d, _v][module] * 255),\n g: round([d, _v, _v, c, l, l][module] * 255),\n b: round([l, l, d, _v, _v, c][module] * 255),\n a: round(a, 2)\n };\n}\nfunction hsvaToRgba(color, includeAlpha) {\n const { r, g, b, a } = hsvaToRgbaObject(color);\n if (!includeAlpha) {\n return `rgb(${r}, ${g}, ${b})`;\n }\n return `rgba(${r}, ${g}, ${b}, ${round(a, 2)})`;\n}\nfunction hsvaToHsl({ h, s, v, a }, includeAlpha) {\n const hh = (200 - s) * v / 100;\n const result = {\n h: Math.round(h),\n s: Math.round(hh > 0 && hh < 200 ? s * v / 100 / (hh <= 100 ? hh : 200 - hh) * 100 : 0),\n l: Math.round(hh / 2)\n };\n if (!includeAlpha) {\n return `hsl(${result.h}, ${result.s}%, ${result.l}%)`;\n }\n return `hsla(${result.h}, ${result.s}%, ${result.l}%, ${round(a, 2)})`;\n}\nfunction formatHexPart(number) {\n const hex = number.toString(16);\n return hex.length < 2 ? `0${hex}` : hex;\n}\nfunction hsvaToHex(color) {\n const { r, g, b } = hsvaToRgbaObject(color);\n return `#${formatHexPart(r)}${formatHexPart(g)}${formatHexPart(b)}`;\n}\nfunction hsvaToHexa(color) {\n const a = Math.round(color.a * 255);\n return `${hsvaToHex(color)}${formatHexPart(a)}`;\n}\nconst CONVERTERS = {\n hex: hsvaToHex,\n hexa: (color) => hsvaToHexa(color),\n rgb: (color) => hsvaToRgba(color, false),\n rgba: (color) => hsvaToRgba(color, true),\n hsl: (color) => hsvaToHsl(color, false),\n hsla: (color) => hsvaToHsl(color, true)\n};\nfunction convertHsvaTo(format, color) {\n if (!color) {\n return \"#000000\";\n }\n if (!(format in CONVERTERS)) {\n return CONVERTERS.hex(color);\n }\n return CONVERTERS[format](color);\n}\n\nexport { convertHsvaTo, hsvaToHex, hsvaToHexa, hsvaToHsl, hsvaToRgba, hsvaToRgbaObject };\n//# sourceMappingURL=converters.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport { rem } from '../../../core/utils/units-converters/rem.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ColorSlider } from '../ColorSlider/ColorSlider.mjs';\n\nconst HueSlider = forwardRef((props, ref) => {\n const { value, onChange, onChangeEnd, color, ...others } = useProps(\"HueSlider\", {}, props);\n return /* @__PURE__ */ jsx(\n ColorSlider,\n {\n ...others,\n ref,\n value,\n onChange,\n onChangeEnd,\n maxValue: 360,\n thumbColor: `hsl(${value}, 100%, 50%)`,\n round: true,\n \"data-hue\": true,\n overlays: [\n {\n backgroundImage: \"linear-gradient(to right,hsl(0,100%,50%),hsl(60,100%,50%),hsl(120,100%,50%),hsl(170,100%,50%),hsl(240,100%,50%),hsl(300,100%,50%),hsl(360,100%,50%))\"\n },\n {\n boxShadow: `rgba(0, 0, 0, .1) 0 0 0 ${rem(1)} inset, rgb(0, 0, 0, .15) 0 0 ${rem(\n 4\n )} inset`\n }\n ]\n }\n );\n});\nHueSlider.displayName = \"@mantine/core/HueSlider\";\n\nexport { HueSlider };\n//# sourceMappingURL=HueSlider.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useState, useRef, useEffect } from 'react';\nimport { useMove, clampUseMovePosition } from '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useColorPickerContext } from '../ColorPicker.context.mjs';\nimport { convertHsvaTo } from '../converters/converters.mjs';\nimport { Thumb } from '../Thumb/Thumb.mjs';\n\nfunction Saturation({\n className,\n onChange,\n onChangeEnd,\n value,\n saturationLabel,\n focusable = true,\n size,\n color,\n onScrubStart,\n onScrubEnd,\n ...others\n}) {\n const { getStyles } = useColorPickerContext();\n const [position, setPosition] = useState({ x: value.s / 100, y: 1 - value.v / 100 });\n const positionRef = useRef(position);\n const { ref } = useMove(\n ({ x, y }) => {\n positionRef.current = { x, y };\n onChange({ s: Math.round(x * 100), v: Math.round((1 - y) * 100) });\n },\n {\n onScrubEnd: () => {\n const { x, y } = positionRef.current;\n onChangeEnd({ s: Math.round(x * 100), v: Math.round((1 - y) * 100) });\n onScrubEnd?.();\n },\n onScrubStart\n }\n );\n useEffect(() => {\n setPosition({ x: value.s / 100, y: 1 - value.v / 100 });\n }, [value.s, value.v]);\n const handleArrow = (event, pos) => {\n event.preventDefault();\n const _position = clampUseMovePosition(pos);\n onChange({ s: Math.round(_position.x * 100), v: Math.round((1 - _position.y) * 100) });\n onChangeEnd({ s: Math.round(_position.x * 100), v: Math.round((1 - _position.y) * 100) });\n };\n const handleKeyDown = (event) => {\n switch (event.key) {\n case \"ArrowUp\": {\n handleArrow(event, { y: position.y - 0.05, x: position.x });\n break;\n }\n case \"ArrowDown\": {\n handleArrow(event, { y: position.y + 0.05, x: position.x });\n break;\n }\n case \"ArrowRight\": {\n handleArrow(event, { x: position.x + 0.05, y: position.y });\n break;\n }\n case \"ArrowLeft\": {\n handleArrow(event, { x: position.x - 0.05, y: position.y });\n break;\n }\n }\n };\n return /* @__PURE__ */ jsxs(\n Box,\n {\n ...getStyles(\"saturation\"),\n ref,\n ...others,\n role: \"slider\",\n \"aria-label\": saturationLabel,\n \"aria-valuenow\": position.x,\n \"aria-valuetext\": convertHsvaTo(\"rgba\", value),\n tabIndex: focusable ? 0 : -1,\n onKeyDown: handleKeyDown,\n children: [\n /* @__PURE__ */ jsx(\n \"div\",\n {\n ...getStyles(\"saturationOverlay\", {\n style: { backgroundColor: `hsl(${value.h}, 100%, 50%)` }\n })\n }\n ),\n /* @__PURE__ */ jsx(\n \"div\",\n {\n ...getStyles(\"saturationOverlay\", {\n style: { backgroundImage: \"linear-gradient(90deg, #fff, transparent)\" }\n })\n }\n ),\n /* @__PURE__ */ jsx(\n \"div\",\n {\n ...getStyles(\"saturationOverlay\", {\n style: { backgroundImage: \"linear-gradient(0deg, #000, transparent)\" }\n })\n }\n ),\n /* @__PURE__ */ jsx(Thumb, { position, ...getStyles(\"thumb\", { style: { backgroundColor: color } }) })\n ]\n }\n );\n}\nSaturation.displayName = \"@mantine/core/Saturation\";\n\nexport { Saturation };\n//# sourceMappingURL=Saturation.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef, createElement } from 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ColorSwatch } from '../../ColorSwatch/ColorSwatch.mjs';\nimport { useColorPickerContext } from '../ColorPicker.context.mjs';\n\nconst Swatches = forwardRef(\n ({\n className,\n datatype,\n setValue,\n onChangeEnd,\n size,\n focusable,\n data,\n swatchesPerRow,\n ...others\n }, ref) => {\n const ctx = useColorPickerContext();\n const colors = data.map((color, index) => /* @__PURE__ */ createElement(\n ColorSwatch,\n {\n ...ctx.getStyles(\"swatch\"),\n unstyled: ctx.unstyled,\n component: \"button\",\n type: \"button\",\n color,\n key: index,\n radius: \"sm\",\n onClick: () => {\n setValue(color);\n onChangeEnd?.(color);\n },\n \"aria-label\": color,\n tabIndex: focusable ? 0 : -1,\n \"data-swatch\": true\n }\n ));\n return /* @__PURE__ */ jsx(Box, { ...ctx.getStyles(\"swatches\"), ref, ...others, children: colors });\n }\n);\nSwatches.displayName = \"@mantine/core/Swatches\";\n\nexport { Swatches };\n//# sourceMappingURL=Swatches.mjs.map\n","'use client';\nimport { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { useRef, useState } from 'react';\nimport { useUncontrolled, useDidUpdate } from '@mantine/hooks';\nimport { getSize, getSpacing } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ColorSwatch } from '../ColorSwatch/ColorSwatch.mjs';\nimport { AlphaSlider } from './AlphaSlider/AlphaSlider.mjs';\nimport { ColorPickerProvider } from './ColorPicker.context.mjs';\nimport { convertHsvaTo } from './converters/converters.mjs';\nimport { parseColor, isColorValid } from './converters/parsers.mjs';\nimport { HueSlider } from './HueSlider/HueSlider.mjs';\nimport { Saturation } from './Saturation/Saturation.mjs';\nimport { Swatches } from './Swatches/Swatches.mjs';\nimport classes from './ColorPicker.module.css.mjs';\n\nconst defaultProps = {\n swatchesPerRow: 7,\n withPicker: true,\n focusable: true,\n size: \"md\",\n __staticSelector: \"ColorPicker\"\n};\nconst varsResolver = createVarsResolver((_, { size, swatchesPerRow }) => ({\n wrapper: {\n \"--cp-preview-size\": getSize(size, \"cp-preview-size\"),\n \"--cp-width\": getSize(size, \"cp-width\"),\n \"--cp-body-spacing\": getSpacing(size),\n \"--cp-swatch-size\": `${100 / swatchesPerRow}%`,\n \"--cp-thumb-size\": getSize(size, \"cp-thumb-size\"),\n \"--cp-saturation-height\": getSize(size, \"cp-saturation-height\")\n }\n}));\nconst ColorPicker = factory((_props, ref) => {\n const props = useProps(\"ColorPicker\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n format,\n value,\n defaultValue,\n onChange,\n onChangeEnd,\n withPicker,\n size,\n saturationLabel,\n hueLabel,\n alphaLabel,\n focusable,\n swatches,\n swatchesPerRow,\n fullWidth,\n onColorSwatchClick,\n __staticSelector,\n mod,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector,\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n rootSelector: \"wrapper\",\n vars,\n varsResolver\n });\n const formatRef = useRef(format);\n const valueRef = useRef(\"\");\n const scrubTimeoutRef = useRef(-1);\n const isScrubbingRef = useRef(false);\n const withAlpha = format === \"hexa\" || format === \"rgba\" || format === \"hsla\";\n const [_value, setValue, controlled] = useUncontrolled({\n value,\n defaultValue,\n finalValue: \"#FFFFFF\",\n onChange\n });\n const [parsed, setParsed] = useState(parseColor(_value));\n const startScrubbing = () => {\n window.clearTimeout(scrubTimeoutRef.current);\n isScrubbingRef.current = true;\n };\n const stopScrubbing = () => {\n window.clearTimeout(scrubTimeoutRef.current);\n scrubTimeoutRef.current = window.setTimeout(() => {\n isScrubbingRef.current = false;\n }, 200);\n };\n const handleChange = (color) => {\n setParsed((current) => {\n const next = { ...current, ...color };\n valueRef.current = convertHsvaTo(formatRef.current, next);\n return next;\n });\n setValue(valueRef.current);\n };\n useDidUpdate(() => {\n if (isColorValid(value) && !isScrubbingRef.current) {\n setParsed(parseColor(value));\n }\n }, [value]);\n useDidUpdate(() => {\n formatRef.current = format;\n setValue(convertHsvaTo(format, parsed));\n }, [format]);\n return /* @__PURE__ */ jsx(ColorPickerProvider, { value: { getStyles, unstyled }, children: /* @__PURE__ */ jsxs(\n Box,\n {\n ref,\n ...getStyles(\"wrapper\"),\n size,\n mod: [{ \"full-width\": fullWidth }, mod],\n ...others,\n children: [\n withPicker && /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsx(\n Saturation,\n {\n value: parsed,\n onChange: handleChange,\n onChangeEnd: ({ s, v }) => onChangeEnd?.(convertHsvaTo(formatRef.current, { ...parsed, s, v })),\n color: _value,\n size,\n focusable,\n saturationLabel,\n onScrubStart: startScrubbing,\n onScrubEnd: stopScrubbing\n }\n ),\n /* @__PURE__ */ jsxs(\"div\", { ...getStyles(\"body\"), children: [\n /* @__PURE__ */ jsxs(\"div\", { ...getStyles(\"sliders\"), children: [\n /* @__PURE__ */ jsx(\n HueSlider,\n {\n value: parsed.h,\n onChange: (h) => handleChange({ h }),\n onChangeEnd: (h) => onChangeEnd?.(convertHsvaTo(formatRef.current, { ...parsed, h })),\n size,\n focusable,\n \"aria-label\": hueLabel,\n onScrubStart: startScrubbing,\n onScrubEnd: stopScrubbing\n }\n ),\n withAlpha && /* @__PURE__ */ jsx(\n AlphaSlider,\n {\n value: parsed.a,\n onChange: (a) => handleChange({ a }),\n onChangeEnd: (a) => {\n onChangeEnd?.(convertHsvaTo(formatRef.current, { ...parsed, a }));\n },\n size,\n color: convertHsvaTo(\"hex\", parsed),\n focusable,\n \"aria-label\": alphaLabel,\n onScrubStart: startScrubbing,\n onScrubEnd: stopScrubbing\n }\n )\n ] }),\n withAlpha && /* @__PURE__ */ jsx(\n ColorSwatch,\n {\n color: _value,\n radius: \"sm\",\n size: \"var(--cp-preview-size)\",\n ...getStyles(\"preview\")\n }\n )\n ] })\n ] }),\n Array.isArray(swatches) && /* @__PURE__ */ jsx(\n Swatches,\n {\n data: swatches,\n swatchesPerRow,\n focusable,\n setValue,\n onChangeEnd: (color) => {\n const convertedColor = convertHsvaTo(format, parseColor(color));\n onColorSwatchClick?.(convertedColor);\n onChangeEnd?.(convertedColor);\n if (!controlled) {\n setParsed(parseColor(color));\n }\n }\n }\n )\n ]\n }\n ) });\n});\nColorPicker.classes = classes;\nColorPicker.displayName = \"@mantine/core/ColorPicker\";\n\nexport { ColorPicker };\n//# sourceMappingURL=ColorPicker.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\n\nfunction EyeDropperIcon({ style, ...others }) {\n return /* @__PURE__ */ jsxs(\n \"svg\",\n {\n xmlns: \"http://www.w3.org/2000/svg\",\n style: {\n width: \"var(--ci-eye-dropper-icon-size)\",\n height: \"var(--ci-eye-dropper-icon-size)\",\n ...style\n },\n viewBox: \"0 0 24 24\",\n strokeWidth: \"1.5\",\n stroke: \"currentColor\",\n fill: \"none\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n ...others,\n children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 7l6 6\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 16l11.7 -11.7a1 1 0 0 1 1.4 0l2.6 2.6a1 1 0 0 1 0 1.4l-11.7 11.7h-4v-4z\" })\n ]\n }\n );\n}\n\nexport { EyeDropperIcon };\n//# sourceMappingURL=EyeDropperIcon.mjs.map\n","'use client';\nvar classes = {\"eyeDropperIcon\":\"m_b077c2bc\",\"colorPreview\":\"m_c5ccdcab\",\"dropdown\":\"m_5ece2cd7\"};\n\nexport { classes as default };\n//# sourceMappingURL=ColorInput.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { useState, useEffect } from 'react';\nimport { useUncontrolled, useEyeDropper, useDidUpdate } from '@mantine/hooks';\nimport { getSize } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { useResolvedStylesApi } from '../../core/styles-api/use-resolved-styles-api/use-resolved-styles-api.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ActionIcon } from '../ActionIcon/ActionIcon.mjs';\nimport '../ActionIcon/ActionIconGroup/ActionIconGroup.mjs';\nimport '../ActionIcon/ActionIconGroupSection/ActionIconGroupSection.mjs';\nimport { ColorPicker } from '../ColorPicker/ColorPicker.mjs';\nimport '../ColorPicker/AlphaSlider/AlphaSlider.mjs';\nimport '../ColorPicker/HueSlider/HueSlider.mjs';\nimport { convertHsvaTo } from '../ColorPicker/converters/converters.mjs';\nimport { parseColor, isColorValid } from '../ColorPicker/converters/parsers.mjs';\nimport { ColorSwatch } from '../ColorSwatch/ColorSwatch.mjs';\nimport { Input } from '../Input/Input.mjs';\nimport '../Input/InputWrapper/InputWrapper.mjs';\nimport '../Input/InputDescription/InputDescription.mjs';\nimport '../Input/InputError/InputError.mjs';\nimport '../Input/InputLabel/InputLabel.mjs';\nimport '../Input/InputPlaceholder/InputPlaceholder.mjs';\nimport '../Input/InputClearButton/InputClearButton.mjs';\nimport { useInputProps } from '../Input/use-input-props.mjs';\nimport '../Input/InputWrapper.context.mjs';\nimport { InputBase } from '../InputBase/InputBase.mjs';\nimport { Popover } from '../Popover/Popover.mjs';\nimport '../Popover/PopoverDropdown/PopoverDropdown.mjs';\nimport '../Popover/PopoverTarget/PopoverTarget.mjs';\nimport { EyeDropperIcon } from './EyeDropperIcon.mjs';\nimport classes from './ColorInput.module.css.mjs';\n\nconst defaultProps = {\n format: \"hex\",\n fixOnBlur: true,\n withPreview: true,\n swatchesPerRow: 7,\n withPicker: true,\n popoverProps: { transitionProps: { transition: \"fade\", duration: 0 } },\n withEyeDropper: true\n};\nconst varsResolver = createVarsResolver((_, { size }) => ({\n eyeDropperIcon: {\n \"--ci-eye-dropper-icon-size\": getSize(size, \"ci-eye-dropper-icon-size\")\n },\n colorPreview: {\n \"--ci-preview-size\": getSize(size, \"ci-preview-size\")\n }\n}));\nconst ColorInput = factory((_props, ref) => {\n const props = useProps(\"ColorInput\", defaultProps, _props);\n const {\n classNames,\n styles,\n unstyled,\n disallowInput,\n fixOnBlur,\n popoverProps,\n withPreview,\n withEyeDropper,\n eyeDropperIcon,\n closeOnColorSwatchClick,\n eyeDropperButtonProps,\n value,\n defaultValue,\n onChange,\n onChangeEnd,\n onClick,\n onFocus,\n onBlur,\n inputProps,\n format,\n wrapperProps,\n readOnly,\n withPicker,\n swatches,\n disabled,\n leftSection,\n rightSection,\n swatchesPerRow,\n ...others\n } = useInputProps(\"ColorInput\", defaultProps, _props);\n const getStyles = useStyles({\n name: \"ColorInput\",\n props,\n classes,\n classNames,\n styles,\n unstyled,\n rootSelector: \"wrapper\",\n vars: props.vars,\n varsResolver\n });\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n const [dropdownOpened, setDropdownOpened] = useState(false);\n const [lastValidValue, setLastValidValue] = useState(\"\");\n const [_value, setValue] = useUncontrolled({\n value,\n defaultValue,\n finalValue: \"\",\n onChange\n });\n const { supported: eyeDropperSupported, open: openEyeDropper } = useEyeDropper();\n const eyeDropper = /* @__PURE__ */ jsx(\n ActionIcon,\n {\n ...eyeDropperButtonProps,\n ...getStyles(\"eyeDropperButton\", {\n className: eyeDropperButtonProps?.className,\n style: eyeDropperButtonProps?.style\n }),\n variant: \"subtle\",\n color: \"gray\",\n size: inputProps.size,\n unstyled,\n onClick: () => openEyeDropper().then((payload) => {\n if (payload?.sRGBHex) {\n const color = convertHsvaTo(format, parseColor(payload.sRGBHex));\n setValue(color);\n onChangeEnd?.(color);\n }\n }).catch(() => {\n }),\n children: eyeDropperIcon || /* @__PURE__ */ jsx(EyeDropperIcon, { ...getStyles(\"eyeDropperIcon\") })\n }\n );\n const handleInputFocus = (event) => {\n onFocus?.(event);\n setDropdownOpened(true);\n };\n const handleInputBlur = (event) => {\n fixOnBlur && setValue(lastValidValue);\n onBlur?.(event);\n setDropdownOpened(false);\n };\n const handleInputClick = (event) => {\n onClick?.(event);\n setDropdownOpened(true);\n };\n useEffect(() => {\n if (isColorValid(_value) || _value.trim() === \"\") {\n setLastValidValue(_value);\n }\n }, [_value]);\n useDidUpdate(() => {\n if (isColorValid(_value)) {\n setValue(convertHsvaTo(format, parseColor(_value)));\n }\n }, [format]);\n return /* @__PURE__ */ jsx(\n Input.Wrapper,\n {\n ...wrapperProps,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n __staticSelector: \"ColorInput\",\n children: /* @__PURE__ */ jsxs(\n Popover,\n {\n __staticSelector: \"ColorInput\",\n position: \"bottom-start\",\n offset: 5,\n opened: dropdownOpened,\n ...popoverProps,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n withRoles: false,\n disabled: readOnly || withPicker === false && (!Array.isArray(swatches) || swatches.length === 0),\n children: [\n /* @__PURE__ */ jsx(Popover.Target, { children: /* @__PURE__ */ jsx(\n Input,\n {\n autoComplete: \"off\",\n ...others,\n ...inputProps,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n disabled,\n ref,\n __staticSelector: \"ColorInput\",\n onFocus: handleInputFocus,\n onBlur: handleInputBlur,\n onClick: handleInputClick,\n spellCheck: false,\n value: _value,\n onChange: (event) => {\n const inputValue = event.currentTarget.value;\n setValue(inputValue);\n if (isColorValid(inputValue)) {\n onChangeEnd?.(convertHsvaTo(format, parseColor(inputValue)));\n }\n },\n leftSection: leftSection || (withPreview ? /* @__PURE__ */ jsx(\n ColorSwatch,\n {\n color: isColorValid(_value) ? _value : \"#fff\",\n size: \"var(--ci-preview-size)\",\n ...getStyles(\"colorPreview\")\n }\n ) : null),\n readOnly: disallowInput || readOnly,\n pointer: disallowInput,\n unstyled,\n rightSection: rightSection || (withEyeDropper && !disabled && !readOnly && eyeDropperSupported ? eyeDropper : null)\n }\n ) }),\n /* @__PURE__ */ jsx(\n Popover.Dropdown,\n {\n onMouseDown: (event) => event.preventDefault(),\n className: classes.dropdown,\n children: /* @__PURE__ */ jsx(\n ColorPicker,\n {\n __staticSelector: \"ColorInput\",\n value: _value,\n onChange: setValue,\n onChangeEnd,\n format,\n swatches,\n swatchesPerRow,\n withPicker,\n size: inputProps.size,\n focusable: false,\n unstyled,\n styles: resolvedStyles,\n classNames: resolvedClassNames,\n onColorSwatchClick: () => closeOnColorSwatchClick && setDropdownOpened(false)\n }\n )\n }\n )\n ]\n }\n )\n }\n );\n});\nColorInput.classes = InputBase.classes;\nColorInput.displayName = \"@mantine/core/ColorInput\";\n\nexport { ColorInput };\n//# sourceMappingURL=ColorInput.mjs.map\n","'use client';\nimport { jsx, Fragment } from 'react/jsx-runtime';\nimport { useClipboard } from '@mantine/hooks';\nimport 'react';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst defaultProps = {\n timeout: 1e3\n};\nfunction CopyButton(props) {\n const { children, timeout, value, ...others } = useProps(\"CopyButton\", defaultProps, props);\n const clipboard = useClipboard({ timeout });\n const copy = () => clipboard.copy(value);\n return /* @__PURE__ */ jsx(Fragment, { children: children({ copy, copied: clipboard.copied, ...others }) });\n}\nCopyButton.displayName = \"@mantine/core/CopyButton\";\n\nexport { CopyButton };\n//# sourceMappingURL=CopyButton.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_3eebeb36\",\"label\":\"m_9e365f20\"};\n\nexport { classes as default };\n//# sourceMappingURL=Divider.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport { getSize } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { getThemeColor } from '../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './Divider.module.css.mjs';\n\nconst defaultProps = {\n orientation: \"horizontal\"\n};\nconst varsResolver = createVarsResolver((theme, { color, variant, size }) => ({\n root: {\n \"--divider-color\": color ? getThemeColor(color, theme) : void 0,\n \"--divider-border-style\": variant,\n \"--divider-size\": getSize(size, \"divider-size\")\n }\n}));\nconst Divider = factory((_props, ref) => {\n const props = useProps(\"Divider\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n color,\n orientation,\n label,\n labelPosition,\n mod,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Divider\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n mod: [{ orientation, \"with-label\": !!label }, mod],\n ...getStyles(\"root\"),\n ...others,\n role: \"separator\",\n children: label && /* @__PURE__ */ jsx(Box, { component: \"span\", mod: { position: labelPosition }, ...getStyles(\"label\"), children: label })\n }\n );\n});\nDivider.classes = classes;\nDivider.displayName = \"@mantine/core/Divider\";\n\nexport { Divider };\n//# sourceMappingURL=Divider.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [DrawerProvider, useDrawerContext] = createSafeContext(\n \"Drawer component was not found in tree\"\n);\n\nexport { DrawerProvider, useDrawerContext };\n//# sourceMappingURL=Drawer.context.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_f11b401e\",\"header\":\"m_5a7c2c9\",\"content\":\"m_b8a05bbd\",\"inner\":\"m_31cd769a\"};\n\nexport { classes as default };\n//# sourceMappingURL=Drawer.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport { ModalBaseBody } from '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { useDrawerContext } from './Drawer.context.mjs';\nimport classes from './Drawer.module.css.mjs';\n\nconst defaultProps = {};\nconst DrawerBody = factory((_props, ref) => {\n const props = useProps(\"DrawerBody\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useDrawerContext();\n return /* @__PURE__ */ jsx(\n ModalBaseBody,\n {\n ref,\n ...ctx.getStyles(\"body\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nDrawerBody.classes = classes;\nDrawerBody.displayName = \"@mantine/core/DrawerBody\";\n\nexport { DrawerBody };\n//# sourceMappingURL=DrawerBody.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport { ModalBaseCloseButton } from '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { useDrawerContext } from './Drawer.context.mjs';\nimport classes from './Drawer.module.css.mjs';\n\nconst defaultProps = {};\nconst DrawerCloseButton = factory((_props, ref) => {\n const props = useProps(\"DrawerCloseButton\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useDrawerContext();\n return /* @__PURE__ */ jsx(\n ModalBaseCloseButton,\n {\n ref,\n ...ctx.getStyles(\"close\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nDrawerCloseButton.classes = classes;\nDrawerCloseButton.displayName = \"@mantine/core/DrawerCloseButton\";\n\nexport { DrawerCloseButton };\n//# sourceMappingURL=DrawerCloseButton.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport { ModalBaseContent } from '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { NativeScrollArea } from '../ModalBase/NativeScrollArea.mjs';\nimport { useDrawerContext } from './Drawer.context.mjs';\nimport classes from './Drawer.module.css.mjs';\n\nconst defaultProps = {};\nconst DrawerContent = factory((_props, ref) => {\n const props = useProps(\"DrawerContent\", defaultProps, _props);\n const { classNames, className, style, styles, vars, children, radius, __hidden, ...others } = props;\n const ctx = useDrawerContext();\n const Scroll = ctx.scrollAreaComponent || NativeScrollArea;\n return /* @__PURE__ */ jsx(\n ModalBaseContent,\n {\n ...ctx.getStyles(\"content\", { className, style, styles, classNames }),\n innerProps: ctx.getStyles(\"inner\", { className, style, styles, classNames }),\n ref,\n ...others,\n radius: radius || ctx.radius || 0,\n \"data-hidden\": __hidden || void 0,\n children: /* @__PURE__ */ jsx(Scroll, { style: { height: \"calc(100vh - var(--drawer-offset) * 2)\" }, children })\n }\n );\n});\nDrawerContent.classes = classes;\nDrawerContent.displayName = \"@mantine/core/DrawerContent\";\n\nexport { DrawerContent };\n//# sourceMappingURL=DrawerContent.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport { ModalBaseHeader } from '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { useDrawerContext } from './Drawer.context.mjs';\nimport classes from './Drawer.module.css.mjs';\n\nconst defaultProps = {};\nconst DrawerHeader = factory((_props, ref) => {\n const props = useProps(\"DrawerHeader\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useDrawerContext();\n return /* @__PURE__ */ jsx(\n ModalBaseHeader,\n {\n ref,\n ...ctx.getStyles(\"header\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nDrawerHeader.classes = classes;\nDrawerHeader.displayName = \"@mantine/core/DrawerHeader\";\n\nexport { DrawerHeader };\n//# sourceMappingURL=DrawerHeader.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport { ModalBaseOverlay } from '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { useDrawerContext } from './Drawer.context.mjs';\nimport classes from './Drawer.module.css.mjs';\n\nconst defaultProps = {};\nconst DrawerOverlay = factory((_props, ref) => {\n const props = useProps(\"DrawerOverlay\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useDrawerContext();\n return /* @__PURE__ */ jsx(\n ModalBaseOverlay,\n {\n ref,\n ...ctx.getStyles(\"overlay\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nDrawerOverlay.classes = classes;\nDrawerOverlay.displayName = \"@mantine/core/DrawerOverlay\";\n\nexport { DrawerOverlay };\n//# sourceMappingURL=DrawerOverlay.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport { getSize } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport { useDirection } from '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ModalBase } from '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { DrawerProvider } from './Drawer.context.mjs';\nimport classes from './Drawer.module.css.mjs';\n\nfunction getDrawerAlign(position) {\n switch (position) {\n case \"top\":\n return \"flex-start\";\n case \"bottom\":\n return \"flex-end\";\n default:\n return void 0;\n }\n}\nfunction getDrawerFlex(position) {\n if (position === \"top\" || position === \"bottom\") {\n return \"0 0 calc(100% - var(--drawer-offset, 0rem) * 2)\";\n }\n return void 0;\n}\nconst transitions = {\n top: \"slide-down\",\n bottom: \"slide-up\",\n left: \"slide-right\",\n right: \"slide-left\"\n};\nconst rtlTransitions = {\n top: \"slide-down\",\n bottom: \"slide-up\",\n right: \"slide-right\",\n left: \"slide-left\"\n};\nconst defaultProps = {\n closeOnClickOutside: true,\n withinPortal: true,\n lockScroll: true,\n trapFocus: true,\n returnFocus: true,\n closeOnEscape: true,\n keepMounted: false,\n zIndex: getDefaultZIndex(\"modal\"),\n position: \"left\"\n};\nconst varsResolver = createVarsResolver((_, { position, size, offset }) => ({\n root: {\n \"--drawer-size\": getSize(size, \"drawer-size\"),\n \"--drawer-flex\": getDrawerFlex(position),\n \"--drawer-height\": position === \"left\" || position === \"right\" ? void 0 : \"var(--drawer-size)\",\n \"--drawer-align\": getDrawerAlign(position),\n \"--drawer-justify\": position === \"right\" ? \"flex-end\" : void 0,\n \"--drawer-offset\": rem(offset)\n }\n}));\nconst DrawerRoot = factory((_props, ref) => {\n const props = useProps(\"DrawerRoot\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n scrollAreaComponent,\n position,\n transitionProps,\n radius,\n ...others\n } = props;\n const { dir } = useDirection();\n const getStyles = useStyles({\n name: \"Drawer\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const drawerTransition = (dir === \"rtl\" ? rtlTransitions : transitions)[position];\n return /* @__PURE__ */ jsx(DrawerProvider, { value: { scrollAreaComponent, getStyles, radius }, children: /* @__PURE__ */ jsx(\n ModalBase,\n {\n ref,\n ...getStyles(\"root\"),\n transitionProps: { transition: drawerTransition, ...transitionProps },\n unstyled,\n ...others\n }\n ) });\n});\nDrawerRoot.classes = classes;\nDrawerRoot.displayName = \"@mantine/core/DrawerRoot\";\n\nexport { DrawerRoot };\n//# sourceMappingURL=DrawerRoot.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useState } from 'react';\nimport { createOptionalContext } from '../../core/utils/create-optional-context/create-optional-context.mjs';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [DrawerStackProvider, useDrawerStackContext] = createOptionalContext();\nfunction DrawerStack({ children }) {\n const [stack, setStack] = useState([]);\n const [maxZIndex, setMaxZIndex] = useState(getDefaultZIndex(\"modal\"));\n return /* @__PURE__ */ jsx(\n DrawerStackProvider,\n {\n value: {\n stack,\n addModal: (id, zIndex) => {\n setStack((current) => [.../* @__PURE__ */ new Set([...current, id])]);\n setMaxZIndex(\n (current) => typeof zIndex === \"number\" && typeof current === \"number\" ? Math.max(current, zIndex) : current\n );\n },\n removeModal: (id) => setStack((current) => current.filter((currentId) => currentId !== id)),\n getZIndex: (id) => `calc(${maxZIndex} + ${stack.indexOf(id)} + 1)`,\n currentId: stack[stack.length - 1],\n maxZIndex\n },\n children\n }\n );\n}\nDrawerStack.displayName = \"@mantine/core/DrawerStack\";\n\nexport { DrawerStack, useDrawerStackContext };\n//# sourceMappingURL=DrawerStack.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport { ModalBaseTitle } from '../ModalBase/ModalBaseTitle.mjs';\nimport { useDrawerContext } from './Drawer.context.mjs';\nimport classes from './Drawer.module.css.mjs';\n\nconst defaultProps = {};\nconst DrawerTitle = factory((_props, ref) => {\n const props = useProps(\"DrawerTitle\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useDrawerContext();\n return /* @__PURE__ */ jsx(\n ModalBaseTitle,\n {\n ref,\n ...ctx.getStyles(\"title\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nDrawerTitle.classes = classes;\nDrawerTitle.displayName = \"@mantine/core/DrawerTitle\";\n\nexport { DrawerTitle };\n//# sourceMappingURL=DrawerTitle.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useEffect } from 'react';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { DrawerBody } from './DrawerBody.mjs';\nimport { DrawerCloseButton } from './DrawerCloseButton.mjs';\nimport { DrawerContent } from './DrawerContent.mjs';\nimport { DrawerHeader } from './DrawerHeader.mjs';\nimport { DrawerOverlay } from './DrawerOverlay.mjs';\nimport { DrawerRoot } from './DrawerRoot.mjs';\nimport { DrawerStack, useDrawerStackContext } from './DrawerStack.mjs';\nimport { DrawerTitle } from './DrawerTitle.mjs';\nimport classes from './Drawer.module.css.mjs';\n\nconst defaultProps = {\n closeOnClickOutside: true,\n withinPortal: true,\n lockScroll: true,\n trapFocus: true,\n returnFocus: true,\n closeOnEscape: true,\n keepMounted: false,\n zIndex: getDefaultZIndex(\"modal\"),\n withOverlay: true,\n withCloseButton: true\n};\nconst Drawer = factory((_props, ref) => {\n const {\n title,\n withOverlay,\n overlayProps,\n withCloseButton,\n closeButtonProps,\n children,\n opened,\n stackId,\n zIndex,\n ...others\n } = useProps(\"Drawer\", defaultProps, _props);\n const ctx = useDrawerStackContext();\n const hasHeader = !!title || withCloseButton;\n const stackProps = ctx && stackId ? {\n closeOnEscape: ctx.currentId === stackId,\n trapFocus: ctx.currentId === stackId,\n zIndex: ctx.getZIndex(stackId)\n } : {};\n const overlayVisible = withOverlay === false ? false : stackId && ctx ? ctx.currentId === stackId : opened;\n useEffect(() => {\n if (ctx && stackId) {\n opened ? ctx.addModal(stackId, zIndex || getDefaultZIndex(\"modal\")) : ctx.removeModal(stackId);\n }\n }, [opened, stackId, zIndex]);\n return /* @__PURE__ */ jsxs(\n DrawerRoot,\n {\n ref,\n opened,\n zIndex: ctx && stackId ? ctx.getZIndex(stackId) : zIndex,\n ...others,\n ...stackProps,\n children: [\n withOverlay && /* @__PURE__ */ jsx(\n DrawerOverlay,\n {\n visible: overlayVisible,\n transitionProps: ctx && stackId ? { duration: 0 } : void 0,\n ...overlayProps\n }\n ),\n /* @__PURE__ */ jsxs(DrawerContent, { __hidden: ctx && stackId && opened ? stackId !== ctx.currentId : false, children: [\n hasHeader && /* @__PURE__ */ jsxs(DrawerHeader, { children: [\n title && /* @__PURE__ */ jsx(DrawerTitle, { children: title }),\n withCloseButton && /* @__PURE__ */ jsx(DrawerCloseButton, { ...closeButtonProps })\n ] }),\n /* @__PURE__ */ jsx(DrawerBody, { children })\n ] })\n ]\n }\n );\n});\nDrawer.classes = classes;\nDrawer.displayName = \"@mantine/core/Drawer\";\nDrawer.Root = DrawerRoot;\nDrawer.Overlay = DrawerOverlay;\nDrawer.Content = DrawerContent;\nDrawer.Body = DrawerBody;\nDrawer.Header = DrawerHeader;\nDrawer.Title = DrawerTitle;\nDrawer.CloseButton = DrawerCloseButton;\nDrawer.Stack = DrawerStack;\n\nexport { Drawer };\n//# sourceMappingURL=Drawer.mjs.map\n","'use client';\nimport { useRef, useEffect } from 'react';\n\nfunction useDelayedHover({ open, close, openDelay, closeDelay }) {\n const openTimeout = useRef(-1);\n const closeTimeout = useRef(-1);\n const clearTimeouts = () => {\n window.clearTimeout(openTimeout.current);\n window.clearTimeout(closeTimeout.current);\n };\n const openDropdown = () => {\n clearTimeouts();\n if (openDelay === 0 || openDelay === void 0) {\n open();\n } else {\n openTimeout.current = window.setTimeout(open, openDelay);\n }\n };\n const closeDropdown = () => {\n clearTimeouts();\n if (closeDelay === 0 || closeDelay === void 0) {\n close();\n } else {\n closeTimeout.current = window.setTimeout(close, closeDelay);\n }\n };\n useEffect(() => clearTimeouts, []);\n return { openDropdown, closeDropdown };\n}\n\nexport { useDelayedHover };\n//# sourceMappingURL=use-delayed-hover.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [GridProvider, useGridContext] = createSafeContext(\n \"Grid component was not found in tree\"\n);\n\nexport { GridProvider, useGridContext };\n//# sourceMappingURL=Grid.context.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { keys } from '../../../core/utils/keys/keys.mjs';\nimport { filterProps } from '../../../core/utils/filter-props/filter-props.mjs';\nimport 'react';\nimport { getSortedBreakpoints } from '../../../core/utils/get-sorted-breakpoints/get-sorted-breakpoints.mjs';\nimport { getBaseValue } from '../../../core/utils/get-base-value/get-base-value.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { InlineStyles } from '../../../core/InlineStyles/InlineStyles.mjs';\nimport '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useGridContext } from '../Grid.context.mjs';\n\nconst getColumnFlexBasis = (colSpan, columns) => {\n if (colSpan === \"content\") {\n return \"auto\";\n }\n if (colSpan === \"auto\") {\n return \"0rem\";\n }\n return colSpan ? `${100 / (columns / colSpan)}%` : void 0;\n};\nconst getColumnMaxWidth = (colSpan, columns, grow) => {\n if (grow || colSpan === \"auto\") {\n return \"100%\";\n }\n if (colSpan === \"content\") {\n return \"unset\";\n }\n return getColumnFlexBasis(colSpan, columns);\n};\nconst getColumnFlexGrow = (colSpan, grow) => {\n if (!colSpan) {\n return void 0;\n }\n return colSpan === \"auto\" || grow ? \"1\" : \"auto\";\n};\nconst getColumnOffset = (offset, columns) => offset === 0 ? \"0\" : offset ? `${100 / (columns / offset)}%` : void 0;\nfunction GridColVariables({ span, order, offset, selector }) {\n const theme = useMantineTheme();\n const ctx = useGridContext();\n const _breakpoints = ctx.breakpoints || theme.breakpoints;\n const baseValue = getBaseValue(span);\n const baseSpan = baseValue === void 0 ? 12 : getBaseValue(span);\n const baseStyles = filterProps({\n \"--col-order\": getBaseValue(order)?.toString(),\n \"--col-flex-grow\": getColumnFlexGrow(baseSpan, ctx.grow),\n \"--col-flex-basis\": getColumnFlexBasis(baseSpan, ctx.columns),\n \"--col-width\": baseSpan === \"content\" ? \"auto\" : void 0,\n \"--col-max-width\": getColumnMaxWidth(baseSpan, ctx.columns, ctx.grow),\n \"--col-offset\": getColumnOffset(getBaseValue(offset), ctx.columns)\n });\n const queries = keys(_breakpoints).reduce(\n (acc, breakpoint) => {\n if (!acc[breakpoint]) {\n acc[breakpoint] = {};\n }\n if (typeof order === \"object\" && order[breakpoint] !== void 0) {\n acc[breakpoint][\"--col-order\"] = order[breakpoint]?.toString();\n }\n if (typeof span === \"object\" && span[breakpoint] !== void 0) {\n acc[breakpoint][\"--col-flex-grow\"] = getColumnFlexGrow(span[breakpoint], ctx.grow);\n acc[breakpoint][\"--col-flex-basis\"] = getColumnFlexBasis(span[breakpoint], ctx.columns);\n acc[breakpoint][\"--col-width\"] = span[breakpoint] === \"content\" ? \"auto\" : void 0;\n acc[breakpoint][\"--col-max-width\"] = getColumnMaxWidth(\n span[breakpoint],\n ctx.columns,\n ctx.grow\n );\n }\n if (typeof offset === \"object\" && offset[breakpoint] !== void 0) {\n acc[breakpoint][\"--col-offset\"] = getColumnOffset(offset[breakpoint], ctx.columns);\n }\n return acc;\n },\n {}\n );\n const sortedBreakpoints = getSortedBreakpoints(keys(queries), _breakpoints).filter(\n (breakpoint) => keys(queries[breakpoint.value]).length > 0\n );\n const values = sortedBreakpoints.map((breakpoint) => ({\n query: ctx.type === \"container\" ? `mantine-grid (min-width: ${_breakpoints[breakpoint.value]})` : `(min-width: ${_breakpoints[breakpoint.value]})`,\n styles: queries[breakpoint.value]\n }));\n return /* @__PURE__ */ jsx(\n InlineStyles,\n {\n styles: baseStyles,\n media: ctx.type === \"container\" ? void 0 : values,\n container: ctx.type === \"container\" ? values : void 0,\n selector\n }\n );\n}\n\nexport { GridColVariables };\n//# sourceMappingURL=GridColVariables.mjs.map\n","'use client';\nvar classes = {\"container\":\"m_8478a6da\",\"root\":\"m_410352e9\",\"inner\":\"m_dee7bd2f\",\"col\":\"m_96bdd299\"};\n\nexport { classes as default };\n//# sourceMappingURL=Grid.module.css.mjs.map\n","'use client';\nimport { jsxs, Fragment, jsx } from 'react/jsx-runtime';\nimport cx from 'clsx';\nimport 'react';\nimport '@mantine/hooks';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useRandomClassName } from '../../../core/Box/use-random-classname/use-random-classname.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useGridContext } from '../Grid.context.mjs';\nimport { GridColVariables } from './GridColVariables.mjs';\nimport classes from '../Grid.module.css.mjs';\n\nconst defaultProps = {\n span: 12\n};\nconst GridCol = factory((_props, ref) => {\n const props = useProps(\"GridCol\", defaultProps, _props);\n const { classNames, className, style, styles, vars, span, order, offset, ...others } = props;\n const ctx = useGridContext();\n const responsiveClassName = useRandomClassName();\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsx(\n GridColVariables,\n {\n selector: `.${responsiveClassName}`,\n span,\n order,\n offset\n }\n ),\n /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n ...ctx.getStyles(\"col\", {\n className: cx(className, responsiveClassName),\n style,\n classNames,\n styles\n }),\n ...others\n }\n )\n ] });\n});\nGridCol.classes = classes;\nGridCol.displayName = \"@mantine/core/GridCol\";\n\nexport { GridCol };\n//# sourceMappingURL=GridCol.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { keys } from '../../core/utils/keys/keys.mjs';\nimport { filterProps } from '../../core/utils/filter-props/filter-props.mjs';\nimport 'react';\nimport { getSpacing } from '../../core/utils/get-size/get-size.mjs';\nimport { getSortedBreakpoints } from '../../core/utils/get-sorted-breakpoints/get-sorted-breakpoints.mjs';\nimport { getBaseValue } from '../../core/utils/get-base-value/get-base-value.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { InlineStyles } from '../../core/InlineStyles/InlineStyles.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nfunction GridVariables({ gutter, selector, breakpoints, type }) {\n const theme = useMantineTheme();\n const _breakpoints = breakpoints || theme.breakpoints;\n const baseStyles = filterProps({\n \"--grid-gutter\": getSpacing(getBaseValue(gutter))\n });\n const queries = keys(_breakpoints).reduce(\n (acc, breakpoint) => {\n if (!acc[breakpoint]) {\n acc[breakpoint] = {};\n }\n if (typeof gutter === \"object\" && gutter[breakpoint] !== void 0) {\n acc[breakpoint][\"--grid-gutter\"] = getSpacing(gutter[breakpoint]);\n }\n return acc;\n },\n {}\n );\n const sortedBreakpoints = getSortedBreakpoints(keys(queries), _breakpoints).filter(\n (breakpoint) => keys(queries[breakpoint.value]).length > 0\n );\n const values = sortedBreakpoints.map((breakpoint) => ({\n query: type === \"container\" ? `mantine-grid (min-width: ${_breakpoints[breakpoint.value]})` : `(min-width: ${_breakpoints[breakpoint.value]})`,\n styles: queries[breakpoint.value]\n }));\n return /* @__PURE__ */ jsx(\n InlineStyles,\n {\n styles: baseStyles,\n media: type === \"container\" ? void 0 : values,\n container: type === \"container\" ? values : void 0,\n selector\n }\n );\n}\n\nexport { GridVariables };\n//# sourceMappingURL=GridVariables.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { useRandomClassName } from '../../core/Box/use-random-classname/use-random-classname.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { GridProvider } from './Grid.context.mjs';\nimport { GridCol } from './GridCol/GridCol.mjs';\nimport { GridVariables } from './GridVariables.mjs';\nimport classes from './Grid.module.css.mjs';\n\nconst defaultProps = {\n gutter: \"md\",\n grow: false,\n columns: 12\n};\nconst varsResolver = createVarsResolver((_, { justify, align, overflow }) => ({\n root: {\n \"--grid-justify\": justify,\n \"--grid-align\": align,\n \"--grid-overflow\": overflow\n }\n}));\nconst Grid = factory((_props, ref) => {\n const props = useProps(\"Grid\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n grow,\n gutter,\n columns,\n align,\n justify,\n children,\n breakpoints,\n type,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Grid\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const responsiveClassName = useRandomClassName();\n if (type === \"container\" && breakpoints) {\n return /* @__PURE__ */ jsxs(GridProvider, { value: { getStyles, grow, columns: columns || 12, breakpoints, type }, children: [\n /* @__PURE__ */ jsx(GridVariables, { selector: `.${responsiveClassName}`, ...props }),\n /* @__PURE__ */ jsx(\"div\", { ...getStyles(\"container\"), children: /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\", { className: responsiveClassName }), ...others, children: /* @__PURE__ */ jsx(\"div\", { ...getStyles(\"inner\"), children }) }) })\n ] });\n }\n return /* @__PURE__ */ jsxs(GridProvider, { value: { getStyles, grow, columns: columns || 12, breakpoints, type }, children: [\n /* @__PURE__ */ jsx(GridVariables, { selector: `.${responsiveClassName}`, ...props }),\n /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\", { className: responsiveClassName }), ...others, children: /* @__PURE__ */ jsx(\"div\", { ...getStyles(\"inner\"), children }) })\n ] });\n});\nGrid.classes = classes;\nGrid.displayName = \"@mantine/core/Grid\";\nGrid.Col = GridCol;\n\nexport { Grid };\n//# sourceMappingURL=Grid.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_9e117634\"};\n\nexport { classes as default };\n//# sourceMappingURL=Image.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useState, useEffect } from 'react';\nimport { getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../core/factory/polymorphic-factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './Image.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver((_, { radius, fit }) => ({\n root: {\n \"--image-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--image-object-fit\": fit\n }\n}));\nconst Image = polymorphicFactory((_props, ref) => {\n const props = useProps(\"Image\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n onError,\n src,\n radius,\n fit,\n fallbackSrc,\n mod,\n ...others\n } = props;\n const [error, setError] = useState(!src);\n useEffect(() => setError(!src), [src]);\n const getStyles = useStyles({\n name: \"Image\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n if (error && fallbackSrc) {\n return /* @__PURE__ */ jsx(\n Box,\n {\n component: \"img\",\n ref,\n src: fallbackSrc,\n ...getStyles(\"root\"),\n onError,\n mod: [\"fallback\", mod],\n ...others\n }\n );\n }\n return /* @__PURE__ */ jsx(\n Box,\n {\n component: \"img\",\n ref,\n ...getStyles(\"root\"),\n src,\n onError: (event) => {\n onError?.(event);\n setError(true);\n },\n mod,\n ...others\n }\n );\n});\nImage.classes = classes;\nImage.displayName = \"@mantine/core/Image\";\n\nexport { Image };\n//# sourceMappingURL=Image.mjs.map\n","import { useLayoutEffect } from 'react';\n\nvar index = useLayoutEffect ;\n\nexport { index as default };\n","import React from 'react';\nimport useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';\n\nvar useLatest = function useLatest(value) {\n var ref = React.useRef(value);\n useIsomorphicLayoutEffect(function () {\n ref.current = value;\n });\n return ref;\n};\n\nexport { useLatest as default };\n","import React from 'react';\n\n// basically Exclude[\"ref\"], string>\n\nvar updateRef = function updateRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n return;\n }\n ref.current = value;\n};\nvar useComposedRef = function useComposedRef(libRef, userRef) {\n var prevUserRef = React.useRef();\n return React.useCallback(function (instance) {\n libRef.current = instance;\n if (prevUserRef.current) {\n updateRef(prevUserRef.current, null);\n }\n prevUserRef.current = userRef;\n if (!userRef) {\n return;\n }\n updateRef(userRef, instance);\n }, [userRef]);\n};\n\nexport { useComposedRef as default };\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose';\nimport * as React from 'react';\nimport useLatest from 'use-latest';\nimport useComposedRef from 'use-composed-ref';\n\nvar HIDDEN_TEXTAREA_STYLE = {\n 'min-height': '0',\n 'max-height': 'none',\n height: '0',\n visibility: 'hidden',\n overflow: 'hidden',\n position: 'absolute',\n 'z-index': '-1000',\n top: '0',\n right: '0',\n display: 'block'\n};\nvar forceHiddenStyles = function forceHiddenStyles(node) {\n Object.keys(HIDDEN_TEXTAREA_STYLE).forEach(function (key) {\n node.style.setProperty(key, HIDDEN_TEXTAREA_STYLE[key], 'important');\n });\n};\nvar forceHiddenStyles$1 = forceHiddenStyles;\n\nvar hiddenTextarea = null;\nvar getHeight = function getHeight(node, sizingData) {\n var height = node.scrollHeight;\n if (sizingData.sizingStyle.boxSizing === 'border-box') {\n // border-box: add border, since height = content + padding + border\n return height + sizingData.borderSize;\n }\n\n // remove padding, since height = content\n return height - sizingData.paddingSize;\n};\nfunction calculateNodeHeight(sizingData, value, minRows, maxRows) {\n if (minRows === void 0) {\n minRows = 1;\n }\n if (maxRows === void 0) {\n maxRows = Infinity;\n }\n if (!hiddenTextarea) {\n hiddenTextarea = document.createElement('textarea');\n hiddenTextarea.setAttribute('tabindex', '-1');\n hiddenTextarea.setAttribute('aria-hidden', 'true');\n forceHiddenStyles$1(hiddenTextarea);\n }\n if (hiddenTextarea.parentNode === null) {\n document.body.appendChild(hiddenTextarea);\n }\n var paddingSize = sizingData.paddingSize,\n borderSize = sizingData.borderSize,\n sizingStyle = sizingData.sizingStyle;\n var boxSizing = sizingStyle.boxSizing;\n Object.keys(sizingStyle).forEach(function (_key) {\n var key = _key;\n hiddenTextarea.style[key] = sizingStyle[key];\n });\n forceHiddenStyles$1(hiddenTextarea);\n hiddenTextarea.value = value;\n var height = getHeight(hiddenTextarea, sizingData);\n // Double set and calc due to Firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1795904\n hiddenTextarea.value = value;\n height = getHeight(hiddenTextarea, sizingData);\n\n // measure height of a textarea with a single row\n hiddenTextarea.value = 'x';\n var rowHeight = hiddenTextarea.scrollHeight - paddingSize;\n var minHeight = rowHeight * minRows;\n if (boxSizing === 'border-box') {\n minHeight = minHeight + paddingSize + borderSize;\n }\n height = Math.max(minHeight, height);\n var maxHeight = rowHeight * maxRows;\n if (boxSizing === 'border-box') {\n maxHeight = maxHeight + paddingSize + borderSize;\n }\n height = Math.min(maxHeight, height);\n return [height, rowHeight];\n}\n\nvar noop = function noop() {};\nvar pick = function pick(props, obj) {\n return props.reduce(function (acc, prop) {\n acc[prop] = obj[prop];\n return acc;\n }, {});\n};\n\nvar SIZING_STYLE = ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth', 'boxSizing', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight', 'letterSpacing', 'lineHeight', 'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop',\n// non-standard\n'tabSize', 'textIndent',\n// non-standard\n'textRendering', 'textTransform', 'width', 'wordBreak', 'wordSpacing', 'scrollbarGutter'];\nvar isIE = !!document.documentElement.currentStyle ;\nvar getSizingData = function getSizingData(node) {\n var style = window.getComputedStyle(node);\n if (style === null) {\n return null;\n }\n var sizingStyle = pick(SIZING_STYLE, style);\n var boxSizing = sizingStyle.boxSizing;\n\n // probably node is detached from DOM, can't read computed dimensions\n if (boxSizing === '') {\n return null;\n }\n\n // IE (Edge has already correct behaviour) returns content width as computed width\n // so we need to add manually padding and border widths\n if (isIE && boxSizing === 'border-box') {\n sizingStyle.width = parseFloat(sizingStyle.width) + parseFloat(sizingStyle.borderRightWidth) + parseFloat(sizingStyle.borderLeftWidth) + parseFloat(sizingStyle.paddingRight) + parseFloat(sizingStyle.paddingLeft) + 'px';\n }\n var paddingSize = parseFloat(sizingStyle.paddingBottom) + parseFloat(sizingStyle.paddingTop);\n var borderSize = parseFloat(sizingStyle.borderBottomWidth) + parseFloat(sizingStyle.borderTopWidth);\n return {\n sizingStyle: sizingStyle,\n paddingSize: paddingSize,\n borderSize: borderSize\n };\n};\nvar getSizingData$1 = getSizingData;\n\nfunction useListener(target, type, listener) {\n var latestListener = useLatest(listener);\n React.useLayoutEffect(function () {\n var handler = function handler(ev) {\n return latestListener.current(ev);\n };\n\n // might happen if document.fonts is not defined, for instance\n if (!target) {\n return;\n }\n target.addEventListener(type, handler);\n return function () {\n return target.removeEventListener(type, handler);\n };\n }, []);\n}\nvar useWindowResizeListener = function useWindowResizeListener(listener) {\n useListener(window, 'resize', listener);\n};\nvar useFontsLoadedListener = function useFontsLoadedListener(listener) {\n useListener(document.fonts, 'loadingdone', listener);\n};\n\nvar _excluded = [\"cacheMeasurements\", \"maxRows\", \"minRows\", \"onChange\", \"onHeightChange\"];\nvar TextareaAutosize = function TextareaAutosize(_ref, userRef) {\n var cacheMeasurements = _ref.cacheMeasurements,\n maxRows = _ref.maxRows,\n minRows = _ref.minRows,\n _ref$onChange = _ref.onChange,\n onChange = _ref$onChange === void 0 ? noop : _ref$onChange,\n _ref$onHeightChange = _ref.onHeightChange,\n onHeightChange = _ref$onHeightChange === void 0 ? noop : _ref$onHeightChange,\n props = _objectWithoutPropertiesLoose(_ref, _excluded);\n var isControlled = props.value !== undefined;\n var libRef = React.useRef(null);\n var ref = useComposedRef(libRef, userRef);\n var heightRef = React.useRef(0);\n var measurementsCacheRef = React.useRef();\n var resizeTextarea = function resizeTextarea() {\n var node = libRef.current;\n var nodeSizingData = cacheMeasurements && measurementsCacheRef.current ? measurementsCacheRef.current : getSizingData$1(node);\n if (!nodeSizingData) {\n return;\n }\n measurementsCacheRef.current = nodeSizingData;\n var _calculateNodeHeight = calculateNodeHeight(nodeSizingData, node.value || node.placeholder || 'x', minRows, maxRows),\n height = _calculateNodeHeight[0],\n rowHeight = _calculateNodeHeight[1];\n if (heightRef.current !== height) {\n heightRef.current = height;\n node.style.setProperty('height', height + \"px\", 'important');\n onHeightChange(height, {\n rowHeight: rowHeight\n });\n }\n };\n var handleChange = function handleChange(event) {\n if (!isControlled) {\n resizeTextarea();\n }\n onChange(event);\n };\n {\n React.useLayoutEffect(resizeTextarea);\n useWindowResizeListener(resizeTextarea);\n useFontsLoadedListener(resizeTextarea);\n return /*#__PURE__*/React.createElement(\"textarea\", _extends({}, props, {\n onChange: handleChange,\n ref: ref\n }));\n }\n};\nvar index = /* #__PURE__ */React.forwardRef(TextareaAutosize);\n\nexport { index as default };\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport TextareaAutosize from 'react-textarea-autosize';\nimport 'react';\nimport '@mantine/hooks';\nimport { getEnv } from '../../core/utils/get-env/get-env.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { InputBase } from '../InputBase/InputBase.mjs';\n\nconst defaultProps = {};\nconst Textarea = factory((props, ref) => {\n const { autosize, maxRows, minRows, __staticSelector, resize, ...others } = useProps(\n \"Textarea\",\n defaultProps,\n props\n );\n const shouldAutosize = autosize && getEnv() !== \"test\";\n const autosizeProps = shouldAutosize ? { maxRows, minRows } : {};\n return /* @__PURE__ */ jsx(\n InputBase,\n {\n component: shouldAutosize ? TextareaAutosize : \"textarea\",\n ref,\n ...others,\n __staticSelector: __staticSelector || \"Textarea\",\n multiline: true,\n \"data-no-overflow\": autosize && maxRows === void 0 || void 0,\n __vars: { \"--input-resize\": resize },\n ...autosizeProps\n }\n );\n});\nTextarea.classes = InputBase.classes;\nTextarea.displayName = \"@mantine/core/Textarea\";\n\nexport { Textarea };\n//# sourceMappingURL=Textarea.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_6e45937b\",\"loader\":\"m_e8eb006c\",\"overlay\":\"m_df587f17\"};\n\nexport { classes as default };\n//# sourceMappingURL=LoadingOverlay.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport 'react';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Loader } from '../Loader/Loader.mjs';\nimport { Overlay } from '../Overlay/Overlay.mjs';\nimport { Transition } from '../Transition/Transition.mjs';\nimport classes from './LoadingOverlay.module.css.mjs';\n\nconst defaultProps = {\n transitionProps: { transition: \"fade\", duration: 0 },\n overlayProps: { backgroundOpacity: 0.75 },\n zIndex: getDefaultZIndex(\"overlay\")\n};\nconst varsResolver = createVarsResolver((_, { zIndex }) => ({\n root: {\n \"--lo-z-index\": zIndex?.toString()\n }\n}));\nconst LoadingOverlay = factory((_props, ref) => {\n const props = useProps(\"LoadingOverlay\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n transitionProps,\n loaderProps,\n overlayProps,\n visible,\n zIndex,\n ...others\n } = props;\n const theme = useMantineTheme();\n const getStyles = useStyles({\n name: \"LoadingOverlay\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const _overlayProps = { ...defaultProps.overlayProps, ...overlayProps };\n return /* @__PURE__ */ jsx(Transition, { transition: \"fade\", ...transitionProps, mounted: !!visible, children: (transitionStyles) => /* @__PURE__ */ jsxs(Box, { ...getStyles(\"root\", { style: transitionStyles }), ref, ...others, children: [\n /* @__PURE__ */ jsx(Loader, { ...getStyles(\"loader\"), unstyled, ...loaderProps }),\n /* @__PURE__ */ jsx(\n Overlay,\n {\n ..._overlayProps,\n ...getStyles(\"overlay\"),\n darkHidden: true,\n unstyled,\n color: overlayProps?.color || theme.white\n }\n ),\n /* @__PURE__ */ jsx(\n Overlay,\n {\n ..._overlayProps,\n ...getStyles(\"overlay\"),\n lightHidden: true,\n unstyled,\n color: overlayProps?.color || theme.colors.dark[5]\n }\n )\n ] }) });\n});\nLoadingOverlay.classes = classes;\nLoadingOverlay.displayName = \"@mantine/core/LoadingOverlay\";\n\nexport { LoadingOverlay };\n//# sourceMappingURL=LoadingOverlay.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [MenuContextProvider, useMenuContext] = createSafeContext(\n \"Menu component was not found in the tree\"\n);\n\nexport { MenuContextProvider, useMenuContext };\n//# sourceMappingURL=Menu.context.mjs.map\n","'use client';\nvar classes = {\"dropdown\":\"m_dc9b7c9f\",\"label\":\"m_9bfac126\",\"divider\":\"m_efdf90cb\",\"item\":\"m_99ac2aa1\",\"itemLabel\":\"m_5476e0d3\",\"itemSection\":\"m_8b75e504\"};\n\nexport { classes as default };\n//# sourceMappingURL=Menu.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useMenuContext } from '../Menu.context.mjs';\nimport classes from '../Menu.module.css.mjs';\n\nconst defaultProps = {};\nconst MenuDivider = factory((props, ref) => {\n const { classNames, className, style, styles, vars, ...others } = useProps(\n \"MenuDivider\",\n defaultProps,\n props\n );\n const ctx = useMenuContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n ...ctx.getStyles(\"divider\", { className, style, styles, classNames }),\n ...others\n }\n );\n});\nMenuDivider.classes = classes;\nMenuDivider.displayName = \"@mantine/core/MenuDivider\";\n\nexport { MenuDivider };\n//# sourceMappingURL=MenuDivider.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useRef } from 'react';\nimport { useMergedRef } from '@mantine/hooks';\nimport { createEventHandler } from '../../../core/utils/create-event-handler/create-event-handler.mjs';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Popover } from '../../Popover/Popover.mjs';\nimport '../../Popover/PopoverDropdown/PopoverDropdown.mjs';\nimport '../../Popover/PopoverTarget/PopoverTarget.mjs';\nimport { useMenuContext } from '../Menu.context.mjs';\nimport classes from '../Menu.module.css.mjs';\n\nconst defaultProps = {};\nconst MenuDropdown = factory((props, ref) => {\n const {\n classNames,\n className,\n style,\n styles,\n vars,\n onMouseEnter,\n onMouseLeave,\n onKeyDown,\n children,\n ...others\n } = useProps(\"MenuDropdown\", defaultProps, props);\n const wrapperRef = useRef(null);\n const ctx = useMenuContext();\n const handleKeyDown = createEventHandler(onKeyDown, (event) => {\n if (event.key === \"ArrowUp\" || event.key === \"ArrowDown\") {\n event.preventDefault();\n wrapperRef.current?.querySelectorAll(\"[data-menu-item]:not(:disabled)\")[0]?.focus();\n }\n });\n const handleMouseEnter = createEventHandler(\n onMouseEnter,\n () => (ctx.trigger === \"hover\" || ctx.trigger === \"click-hover\") && ctx.openDropdown()\n );\n const handleMouseLeave = createEventHandler(\n onMouseLeave,\n () => (ctx.trigger === \"hover\" || ctx.trigger === \"click-hover\") && ctx.closeDropdown()\n );\n return /* @__PURE__ */ jsxs(\n Popover.Dropdown,\n {\n ...others,\n onMouseEnter: handleMouseEnter,\n onMouseLeave: handleMouseLeave,\n role: \"menu\",\n \"aria-orientation\": \"vertical\",\n ref: useMergedRef(ref, wrapperRef),\n ...ctx.getStyles(\"dropdown\", {\n className,\n style,\n styles,\n classNames,\n withStaticClass: false\n }),\n tabIndex: -1,\n \"data-menu-dropdown\": true,\n onKeyDown: handleKeyDown,\n children: [\n ctx.withInitialFocusPlaceholder && /* @__PURE__ */ jsx(\"div\", { tabIndex: -1, \"data-autofocus\": true, \"data-mantine-stop-propagation\": true, style: { outline: 0 } }),\n children\n ]\n }\n );\n});\nMenuDropdown.classes = classes;\nMenuDropdown.displayName = \"@mantine/core/MenuDropdown\";\n\nexport { MenuDropdown };\n//# sourceMappingURL=MenuDropdown.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useRef } from 'react';\nimport { useMergedRef } from '@mantine/hooks';\nimport { createScopedKeydownHandler } from '../../../core/utils/create-scoped-keydown-handler/create-scoped-keydown-handler.mjs';\nimport { createEventHandler } from '../../../core/utils/create-event-handler/create-event-handler.mjs';\nimport 'clsx';\nimport { parseThemeColor } from '../../../core/MantineProvider/color-functions/parse-theme-color/parse-theme-color.mjs';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../../core/factory/polymorphic-factory.mjs';\nimport { useDirection } from '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { UnstyledButton } from '../../UnstyledButton/UnstyledButton.mjs';\nimport { useMenuContext } from '../Menu.context.mjs';\nimport classes from '../Menu.module.css.mjs';\n\nconst defaultProps = {};\nconst MenuItem = polymorphicFactory((props, ref) => {\n const {\n classNames,\n className,\n style,\n styles,\n vars,\n color,\n closeMenuOnClick,\n leftSection,\n rightSection,\n children,\n disabled,\n \"data-disabled\": dataDisabled,\n ...others\n } = useProps(\"MenuItem\", defaultProps, props);\n const ctx = useMenuContext();\n const theme = useMantineTheme();\n const { dir } = useDirection();\n const itemRef = useRef(null);\n const itemIndex = ctx.getItemIndex(itemRef.current);\n const _others = others;\n const handleMouseLeave = createEventHandler(_others.onMouseLeave, () => ctx.setHovered(-1));\n const handleMouseEnter = createEventHandler(\n _others.onMouseEnter,\n () => ctx.setHovered(ctx.getItemIndex(itemRef.current))\n );\n const handleClick = createEventHandler(_others.onClick, () => {\n if (dataDisabled) {\n return;\n }\n if (typeof closeMenuOnClick === \"boolean\") {\n closeMenuOnClick && ctx.closeDropdownImmediately();\n } else {\n ctx.closeOnItemClick && ctx.closeDropdownImmediately();\n }\n });\n const handleFocus = createEventHandler(\n _others.onFocus,\n () => ctx.setHovered(ctx.getItemIndex(itemRef.current))\n );\n const colors = color ? theme.variantColorResolver({ color, theme, variant: \"light\" }) : void 0;\n const parsedThemeColor = color ? parseThemeColor({ color, theme }) : null;\n return /* @__PURE__ */ jsxs(\n UnstyledButton,\n {\n ...others,\n unstyled: ctx.unstyled,\n tabIndex: ctx.menuItemTabIndex,\n onFocus: handleFocus,\n ...ctx.getStyles(\"item\", { className, style, styles, classNames }),\n ref: useMergedRef(itemRef, ref),\n role: \"menuitem\",\n disabled,\n \"data-menu-item\": true,\n \"data-disabled\": disabled || dataDisabled || void 0,\n \"data-hovered\": ctx.hovered === itemIndex ? true : void 0,\n \"data-mantine-stop-propagation\": true,\n onMouseEnter: handleMouseEnter,\n onMouseLeave: handleMouseLeave,\n onClick: handleClick,\n onKeyDown: createScopedKeydownHandler({\n siblingSelector: \"[data-menu-item]:not([data-disabled])\",\n parentSelector: \"[data-menu-dropdown]\",\n activateOnFocus: false,\n loop: ctx.loop,\n dir,\n orientation: \"vertical\",\n onKeyDown: _others.onKeyDown\n }),\n __vars: {\n \"--menu-item-color\": parsedThemeColor?.isThemeColor && parsedThemeColor?.shade === void 0 ? `var(--mantine-color-${parsedThemeColor.color}-6)` : colors?.color,\n \"--menu-item-hover\": colors?.hover\n },\n children: [\n leftSection && /* @__PURE__ */ jsx(\"div\", { ...ctx.getStyles(\"itemSection\", { styles, classNames }), \"data-position\": \"left\", children: leftSection }),\n children && /* @__PURE__ */ jsx(\"div\", { ...ctx.getStyles(\"itemLabel\", { styles, classNames }), children }),\n rightSection && /* @__PURE__ */ jsx(\"div\", { ...ctx.getStyles(\"itemSection\", { styles, classNames }), \"data-position\": \"right\", children: rightSection })\n ]\n }\n );\n});\nMenuItem.classes = classes;\nMenuItem.displayName = \"@mantine/core/MenuItem\";\n\nexport { MenuItem };\n//# sourceMappingURL=MenuItem.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useMenuContext } from '../Menu.context.mjs';\nimport classes from '../Menu.module.css.mjs';\n\nconst defaultProps = {};\nconst MenuLabel = factory((props, ref) => {\n const { classNames, className, style, styles, vars, ...others } = useProps(\n \"MenuLabel\",\n defaultProps,\n props\n );\n const ctx = useMenuContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n ...ctx.getStyles(\"label\", { className, style, styles, classNames }),\n ...others\n }\n );\n});\nMenuLabel.classes = classes;\nMenuLabel.displayName = \"@mantine/core/MenuLabel\";\n\nexport { MenuLabel };\n//# sourceMappingURL=MenuLabel.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef, cloneElement } from 'react';\nimport { isElement } from '../../../core/utils/is-element/is-element.mjs';\nimport { createEventHandler } from '../../../core/utils/create-event-handler/create-event-handler.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Popover } from '../../Popover/Popover.mjs';\nimport '../../Popover/PopoverDropdown/PopoverDropdown.mjs';\nimport '../../Popover/PopoverTarget/PopoverTarget.mjs';\nimport { useMenuContext } from '../Menu.context.mjs';\n\nconst defaultProps = {\n refProp: \"ref\"\n};\nconst MenuTarget = forwardRef((props, ref) => {\n const { children, refProp, ...others } = useProps(\"MenuTarget\", defaultProps, props);\n if (!isElement(children)) {\n throw new Error(\n \"Menu.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported\"\n );\n }\n const ctx = useMenuContext();\n const _childrenProps = children.props;\n const onClick = createEventHandler(_childrenProps.onClick, () => {\n if (ctx.trigger === \"click\") {\n ctx.toggleDropdown();\n } else if (ctx.trigger === \"click-hover\") {\n ctx.setOpenedViaClick(true);\n if (!ctx.opened) {\n ctx.openDropdown();\n }\n }\n });\n const onMouseEnter = createEventHandler(\n _childrenProps.onMouseEnter,\n () => (ctx.trigger === \"hover\" || ctx.trigger === \"click-hover\") && ctx.openDropdown()\n );\n const onMouseLeave = createEventHandler(_childrenProps.onMouseLeave, () => {\n if (ctx.trigger === \"hover\") {\n ctx.closeDropdown();\n } else if (ctx.trigger === \"click-hover\" && !ctx.openedViaClick) {\n ctx.closeDropdown();\n }\n });\n return /* @__PURE__ */ jsx(Popover.Target, { refProp, popupType: \"menu\", ref, ...others, children: cloneElement(children, {\n onClick,\n onMouseEnter,\n onMouseLeave,\n \"data-expanded\": ctx.opened ? true : void 0\n }) });\n});\nMenuTarget.displayName = \"@mantine/core/MenuTarget\";\n\nexport { MenuTarget };\n//# sourceMappingURL=MenuTarget.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useState } from 'react';\nimport { useUncontrolled, useDidUpdate } from '@mantine/hooks';\nimport { getContextItemIndex } from '../../core/utils/get-context-item-index/get-context-item-index.mjs';\nimport { useHovered } from '../../core/utils/use-hovered/use-hovered.mjs';\nimport 'clsx';\nimport { useResolvedStylesApi } from '../../core/styles-api/use-resolved-styles-api/use-resolved-styles-api.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useDelayedHover } from '../Floating/use-delayed-hover.mjs';\nimport '@floating-ui/react';\nimport '../Floating/FloatingArrow/FloatingArrow.mjs';\nimport { Popover } from '../Popover/Popover.mjs';\nimport '../Popover/PopoverDropdown/PopoverDropdown.mjs';\nimport '../Popover/PopoverTarget/PopoverTarget.mjs';\nimport { MenuContextProvider } from './Menu.context.mjs';\nimport { MenuDivider } from './MenuDivider/MenuDivider.mjs';\nimport { MenuDropdown } from './MenuDropdown/MenuDropdown.mjs';\nimport { MenuItem } from './MenuItem/MenuItem.mjs';\nimport { MenuLabel } from './MenuLabel/MenuLabel.mjs';\nimport { MenuTarget } from './MenuTarget/MenuTarget.mjs';\nimport classes from './Menu.module.css.mjs';\n\nconst defaultProps = {\n trapFocus: true,\n closeOnItemClick: true,\n withInitialFocusPlaceholder: true,\n clickOutsideEvents: [\"mousedown\", \"touchstart\", \"keydown\"],\n loop: true,\n trigger: \"click\",\n openDelay: 0,\n closeDelay: 100,\n menuItemTabIndex: -1\n};\nfunction Menu(_props) {\n const props = useProps(\"Menu\", defaultProps, _props);\n const {\n children,\n onOpen,\n onClose,\n opened,\n defaultOpened,\n trapFocus,\n onChange,\n closeOnItemClick,\n loop,\n closeOnEscape,\n trigger,\n openDelay,\n closeDelay,\n classNames,\n styles,\n unstyled,\n variant,\n vars,\n menuItemTabIndex,\n keepMounted,\n withInitialFocusPlaceholder,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Menu\",\n classes,\n props,\n classNames,\n styles,\n unstyled\n });\n const [hovered, { setHovered, resetHovered }] = useHovered();\n const [_opened, setOpened] = useUncontrolled({\n value: opened,\n defaultValue: defaultOpened,\n finalValue: false,\n onChange\n });\n const [openedViaClick, setOpenedViaClick] = useState(false);\n const close = () => {\n setOpened(false);\n setOpenedViaClick(false);\n _opened && onClose?.();\n };\n const open = () => {\n setOpened(true);\n !_opened && onOpen?.();\n };\n const toggleDropdown = () => {\n _opened ? close() : open();\n };\n const { openDropdown, closeDropdown } = useDelayedHover({ open, close, closeDelay, openDelay });\n const getItemIndex = (node) => getContextItemIndex(\"[data-menu-item]\", \"[data-menu-dropdown]\", node);\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n useDidUpdate(() => {\n resetHovered();\n }, [_opened]);\n return /* @__PURE__ */ jsx(\n MenuContextProvider,\n {\n value: {\n getStyles,\n opened: _opened,\n toggleDropdown,\n getItemIndex,\n hovered,\n setHovered,\n openedViaClick,\n setOpenedViaClick,\n closeOnItemClick,\n closeDropdown: trigger === \"click\" ? close : closeDropdown,\n openDropdown: trigger === \"click\" ? open : openDropdown,\n closeDropdownImmediately: close,\n loop,\n trigger,\n unstyled,\n menuItemTabIndex,\n withInitialFocusPlaceholder\n },\n children: /* @__PURE__ */ jsx(\n Popover,\n {\n ...others,\n opened: _opened,\n onChange: toggleDropdown,\n defaultOpened,\n trapFocus: keepMounted ? false : trapFocus,\n closeOnEscape,\n __staticSelector: \"Menu\",\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n variant,\n keepMounted,\n children\n }\n )\n }\n );\n}\nMenu.extend = (input) => input;\nMenu.classes = classes;\nMenu.displayName = \"@mantine/core/Menu\";\nMenu.Item = MenuItem;\nMenu.Label = MenuLabel;\nMenu.Dropdown = MenuDropdown;\nMenu.Target = MenuTarget;\nMenu.Divider = MenuDivider;\n\nexport { Menu };\n//# sourceMappingURL=Menu.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [ModalProvider, useModalContext] = createSafeContext(\n \"Modal component was not found in tree\"\n);\n\nexport { ModalProvider, useModalContext };\n//# sourceMappingURL=Modal.context.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_9df02822\",\"content\":\"m_54c44539\",\"inner\":\"m_1f958f16\",\"header\":\"m_d0e2b9cd\"};\n\nexport { classes as default };\n//# sourceMappingURL=Modal.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport { ModalBaseBody } from '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { useModalContext } from './Modal.context.mjs';\nimport classes from './Modal.module.css.mjs';\n\nconst defaultProps = {};\nconst ModalBody = factory((_props, ref) => {\n const props = useProps(\"ModalBody\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useModalContext();\n return /* @__PURE__ */ jsx(\n ModalBaseBody,\n {\n ref,\n ...ctx.getStyles(\"body\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nModalBody.classes = classes;\nModalBody.displayName = \"@mantine/core/ModalBody\";\n\nexport { ModalBody };\n//# sourceMappingURL=ModalBody.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport { ModalBaseCloseButton } from '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { useModalContext } from './Modal.context.mjs';\nimport classes from './Modal.module.css.mjs';\n\nconst defaultProps = {};\nconst ModalCloseButton = factory((_props, ref) => {\n const props = useProps(\"ModalCloseButton\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useModalContext();\n return /* @__PURE__ */ jsx(\n ModalBaseCloseButton,\n {\n ref,\n ...ctx.getStyles(\"close\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nModalCloseButton.classes = classes;\nModalCloseButton.displayName = \"@mantine/core/ModalCloseButton\";\n\nexport { ModalCloseButton };\n//# sourceMappingURL=ModalCloseButton.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport { ModalBaseContent } from '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { NativeScrollArea } from '../ModalBase/NativeScrollArea.mjs';\nimport { useModalContext } from './Modal.context.mjs';\nimport classes from './Modal.module.css.mjs';\n\nconst defaultProps = {};\nconst ModalContent = factory((_props, ref) => {\n const props = useProps(\"ModalContent\", defaultProps, _props);\n const { classNames, className, style, styles, vars, children, __hidden, ...others } = props;\n const ctx = useModalContext();\n const Scroll = ctx.scrollAreaComponent || NativeScrollArea;\n return /* @__PURE__ */ jsx(\n ModalBaseContent,\n {\n ...ctx.getStyles(\"content\", { className, style, styles, classNames }),\n innerProps: ctx.getStyles(\"inner\", { className, style, styles, classNames }),\n \"data-full-screen\": ctx.fullScreen || void 0,\n \"data-modal-content\": true,\n \"data-hidden\": __hidden || void 0,\n ref,\n ...others,\n children: /* @__PURE__ */ jsx(\n Scroll,\n {\n style: {\n maxHeight: ctx.fullScreen ? \"100dvh\" : `calc(100dvh - (${rem(ctx.yOffset)} * 2))`\n },\n children\n }\n )\n }\n );\n});\nModalContent.classes = classes;\nModalContent.displayName = \"@mantine/core/ModalContent\";\n\nexport { ModalContent };\n//# sourceMappingURL=ModalContent.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport { ModalBaseHeader } from '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { useModalContext } from './Modal.context.mjs';\nimport classes from './Modal.module.css.mjs';\n\nconst defaultProps = {};\nconst ModalHeader = factory((_props, ref) => {\n const props = useProps(\"ModalHeader\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useModalContext();\n return /* @__PURE__ */ jsx(\n ModalBaseHeader,\n {\n ref,\n ...ctx.getStyles(\"header\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nModalHeader.classes = classes;\nModalHeader.displayName = \"@mantine/core/ModalHeader\";\n\nexport { ModalHeader };\n//# sourceMappingURL=ModalHeader.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport { ModalBaseOverlay } from '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { useModalContext } from './Modal.context.mjs';\nimport classes from './Modal.module.css.mjs';\n\nconst defaultProps = {};\nconst ModalOverlay = factory((_props, ref) => {\n const props = useProps(\"ModalOverlay\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useModalContext();\n return /* @__PURE__ */ jsx(\n ModalBaseOverlay,\n {\n ref,\n ...ctx.getStyles(\"overlay\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nModalOverlay.classes = classes;\nModalOverlay.displayName = \"@mantine/core/ModalOverlay\";\n\nexport { ModalOverlay };\n//# sourceMappingURL=ModalOverlay.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport { getRadius, getSize } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ModalBase } from '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport '../ModalBase/ModalBaseTitle.mjs';\nimport { ModalProvider } from './Modal.context.mjs';\nimport classes from './Modal.module.css.mjs';\n\nconst defaultProps = {\n __staticSelector: \"Modal\",\n closeOnClickOutside: true,\n withinPortal: true,\n lockScroll: true,\n trapFocus: true,\n returnFocus: true,\n closeOnEscape: true,\n keepMounted: false,\n zIndex: getDefaultZIndex(\"modal\"),\n transitionProps: { duration: 200, transition: \"fade-down\" },\n yOffset: \"5dvh\"\n};\nconst varsResolver = createVarsResolver(\n (_, { radius, size, yOffset, xOffset }) => ({\n root: {\n \"--modal-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--modal-size\": getSize(size, \"modal-size\"),\n \"--modal-y-offset\": rem(yOffset),\n \"--modal-x-offset\": rem(xOffset)\n }\n })\n);\nconst ModalRoot = factory((_props, ref) => {\n const props = useProps(\"ModalRoot\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n yOffset,\n scrollAreaComponent,\n radius,\n fullScreen,\n centered,\n xOffset,\n __staticSelector,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector,\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(ModalProvider, { value: { yOffset, scrollAreaComponent, getStyles, fullScreen }, children: /* @__PURE__ */ jsx(\n ModalBase,\n {\n ref,\n ...getStyles(\"root\"),\n \"data-full-screen\": fullScreen || void 0,\n \"data-centered\": centered || void 0,\n unstyled,\n ...others\n }\n ) });\n});\nModalRoot.classes = classes;\nModalRoot.displayName = \"@mantine/core/ModalRoot\";\n\nexport { ModalRoot };\n//# sourceMappingURL=ModalRoot.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useState } from 'react';\nimport { createOptionalContext } from '../../core/utils/create-optional-context/create-optional-context.mjs';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [ModalStackProvider, useModalStackContext] = createOptionalContext();\nfunction ModalStack({ children }) {\n const [stack, setStack] = useState([]);\n const [maxZIndex, setMaxZIndex] = useState(getDefaultZIndex(\"modal\"));\n return /* @__PURE__ */ jsx(\n ModalStackProvider,\n {\n value: {\n stack,\n addModal: (id, zIndex) => {\n setStack((current) => [.../* @__PURE__ */ new Set([...current, id])]);\n setMaxZIndex(\n (current) => typeof zIndex === \"number\" && typeof current === \"number\" ? Math.max(current, zIndex) : current\n );\n },\n removeModal: (id) => setStack((current) => current.filter((currentId) => currentId !== id)),\n getZIndex: (id) => `calc(${maxZIndex} + ${stack.indexOf(id)} + 1)`,\n currentId: stack[stack.length - 1],\n maxZIndex\n },\n children\n }\n );\n}\nModalStack.displayName = \"@mantine/core/ModalStack\";\n\nexport { ModalStack, useModalStackContext };\n//# sourceMappingURL=ModalStack.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../ModalBase/ModalBase.mjs';\nimport '../ModalBase/ModalBaseBody.mjs';\nimport '../ModalBase/ModalBaseCloseButton.mjs';\nimport '../ModalBase/ModalBaseContent.mjs';\nimport '../ModalBase/ModalBaseHeader.mjs';\nimport '../ModalBase/ModalBaseOverlay.mjs';\nimport { ModalBaseTitle } from '../ModalBase/ModalBaseTitle.mjs';\nimport { useModalContext } from './Modal.context.mjs';\nimport classes from './Modal.module.css.mjs';\n\nconst defaultProps = {};\nconst ModalTitle = factory((_props, ref) => {\n const props = useProps(\"ModalTitle\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useModalContext();\n return /* @__PURE__ */ jsx(\n ModalBaseTitle,\n {\n ref,\n ...ctx.getStyles(\"title\", { classNames, style, styles, className }),\n ...others\n }\n );\n});\nModalTitle.classes = classes;\nModalTitle.displayName = \"@mantine/core/ModalTitle\";\n\nexport { ModalTitle };\n//# sourceMappingURL=ModalTitle.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useEffect } from 'react';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ModalBody } from './ModalBody.mjs';\nimport { ModalCloseButton } from './ModalCloseButton.mjs';\nimport { ModalContent } from './ModalContent.mjs';\nimport { ModalHeader } from './ModalHeader.mjs';\nimport { ModalOverlay } from './ModalOverlay.mjs';\nimport { ModalRoot } from './ModalRoot.mjs';\nimport { ModalStack, useModalStackContext } from './ModalStack.mjs';\nimport { ModalTitle } from './ModalTitle.mjs';\nimport classes from './Modal.module.css.mjs';\n\nconst defaultProps = {\n closeOnClickOutside: true,\n withinPortal: true,\n lockScroll: true,\n trapFocus: true,\n returnFocus: true,\n closeOnEscape: true,\n keepMounted: false,\n zIndex: getDefaultZIndex(\"modal\"),\n transitionProps: { duration: 200, transition: \"fade-down\" },\n withOverlay: true,\n withCloseButton: true\n};\nconst Modal = factory((_props, ref) => {\n const {\n title,\n withOverlay,\n overlayProps,\n withCloseButton,\n closeButtonProps,\n children,\n radius,\n opened,\n stackId,\n zIndex,\n ...others\n } = useProps(\"Modal\", defaultProps, _props);\n const ctx = useModalStackContext();\n const hasHeader = !!title || withCloseButton;\n const stackProps = ctx && stackId ? {\n closeOnEscape: ctx.currentId === stackId,\n trapFocus: ctx.currentId === stackId,\n zIndex: ctx.getZIndex(stackId)\n } : {};\n const overlayVisible = withOverlay === false ? false : stackId && ctx ? ctx.currentId === stackId : opened;\n useEffect(() => {\n if (ctx && stackId) {\n opened ? ctx.addModal(stackId, zIndex || getDefaultZIndex(\"modal\")) : ctx.removeModal(stackId);\n }\n }, [opened, stackId, zIndex]);\n return /* @__PURE__ */ jsxs(\n ModalRoot,\n {\n ref,\n radius,\n opened,\n zIndex: ctx && stackId ? ctx.getZIndex(stackId) : zIndex,\n ...others,\n ...stackProps,\n children: [\n withOverlay && /* @__PURE__ */ jsx(\n ModalOverlay,\n {\n visible: overlayVisible,\n transitionProps: ctx && stackId ? { duration: 0 } : void 0,\n ...overlayProps\n }\n ),\n /* @__PURE__ */ jsxs(\n ModalContent,\n {\n radius,\n __hidden: ctx && stackId && opened ? stackId !== ctx.currentId : false,\n children: [\n hasHeader && /* @__PURE__ */ jsxs(ModalHeader, { children: [\n title && /* @__PURE__ */ jsx(ModalTitle, { children: title }),\n withCloseButton && /* @__PURE__ */ jsx(ModalCloseButton, { ...closeButtonProps })\n ] }),\n /* @__PURE__ */ jsx(ModalBody, { children })\n ]\n }\n )\n ]\n }\n );\n});\nModal.classes = classes;\nModal.displayName = \"@mantine/core/Modal\";\nModal.Root = ModalRoot;\nModal.Overlay = ModalOverlay;\nModal.Content = ModalContent;\nModal.Body = ModalBody;\nModal.Header = ModalHeader;\nModal.Title = ModalTitle;\nModal.CloseButton = ModalCloseButton;\nModal.Stack = ModalStack;\n\nexport { Modal };\n//# sourceMappingURL=Modal.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_f0824112\",\"description\":\"m_57492dcc\",\"section\":\"m_690090b5\",\"label\":\"m_1f6ac4c4\",\"body\":\"m_f07af9d2\",\"children\":\"m_e17b862f\",\"chevron\":\"m_1fd8a00b\"};\n\nexport { classes as default };\n//# sourceMappingURL=NavLink.module.css.mjs.map\n","'use client';\nimport { jsxs, Fragment, jsx } from 'react/jsx-runtime';\nimport { useUncontrolled } from '@mantine/hooks';\nimport 'react';\nimport { getSpacing } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { polymorphicFactory } from '../../core/factory/polymorphic-factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../Accordion/Accordion.mjs';\nimport { AccordionChevron } from '../Accordion/AccordionChevron.mjs';\nimport '../Accordion/AccordionItem/AccordionItem.mjs';\nimport '../Accordion/AccordionPanel/AccordionPanel.mjs';\nimport '../Accordion/AccordionControl/AccordionControl.mjs';\nimport { Collapse } from '../Collapse/Collapse.mjs';\nimport { UnstyledButton } from '../UnstyledButton/UnstyledButton.mjs';\nimport classes from './NavLink.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver(\n (theme, { variant, color, childrenOffset, autoContrast }) => {\n const colors = theme.variantColorResolver({\n color: color || theme.primaryColor,\n theme,\n variant: variant || \"light\",\n autoContrast\n });\n return {\n root: {\n \"--nl-bg\": color || variant ? colors.background : void 0,\n \"--nl-hover\": color || variant ? colors.hover : void 0,\n \"--nl-color\": color || variant ? colors.color : void 0\n },\n children: {\n \"--nl-offset\": getSpacing(childrenOffset)\n }\n };\n }\n);\nconst NavLink = polymorphicFactory((_props, ref) => {\n const props = useProps(\"NavLink\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n opened,\n defaultOpened,\n onChange,\n children,\n onClick,\n active,\n disabled,\n leftSection,\n rightSection,\n label,\n description,\n disableRightSectionRotation,\n noWrap,\n childrenOffset,\n onKeyDown,\n autoContrast,\n mod,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"NavLink\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const [_opened, setOpened] = useUncontrolled({\n value: opened,\n defaultValue: defaultOpened,\n finalValue: false,\n onChange\n });\n const withChildren = !!children;\n const handleClick = (event) => {\n onClick?.(event);\n if (withChildren) {\n event.preventDefault();\n setOpened(!_opened);\n }\n };\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsxs(\n UnstyledButton,\n {\n ...getStyles(\"root\"),\n component: \"a\",\n ref,\n onClick: handleClick,\n onKeyDown: (event) => {\n onKeyDown?.(event);\n if (event.nativeEvent.code === \"Space\" && withChildren) {\n event.preventDefault();\n setOpened(!_opened);\n }\n },\n unstyled,\n mod: [{ disabled, active, expanded: _opened }, mod],\n ...others,\n children: [\n leftSection && /* @__PURE__ */ jsx(Box, { component: \"span\", ...getStyles(\"section\"), mod: { position: \"left\" }, children: leftSection }),\n /* @__PURE__ */ jsxs(Box, { ...getStyles(\"body\"), mod: { \"no-wrap\": noWrap }, children: [\n /* @__PURE__ */ jsx(Box, { component: \"span\", ...getStyles(\"label\"), children: label }),\n /* @__PURE__ */ jsx(Box, { component: \"span\", mod: { active }, ...getStyles(\"description\"), children: description })\n ] }),\n (withChildren || rightSection) && /* @__PURE__ */ jsx(\n Box,\n {\n ...getStyles(\"section\"),\n component: \"span\",\n mod: { rotate: _opened && !disableRightSectionRotation, position: \"right\" },\n children: withChildren ? rightSection || /* @__PURE__ */ jsx(AccordionChevron, { ...getStyles(\"chevron\") }) : rightSection\n }\n )\n ]\n }\n ),\n withChildren && /* @__PURE__ */ jsx(Collapse, { in: _opened, ...getStyles(\"collapse\"), children: /* @__PURE__ */ jsx(\"div\", { ...getStyles(\"children\"), children }) })\n ] });\n});\nNavLink.classes = classes;\nNavLink.displayName = \"@mantine/core/NavLink\";\n\nexport { NavLink };\n//# sourceMappingURL=NavLink.mjs.map\n","/**\n * react-number-format - 5.4.3\n * Author : Sudhanshu Yadav\n * Copyright (c) 2016, 2024 to Sudhanshu Yadav, released under the MIT license.\n * https://github.com/s-yadav/react-number-format\n */\n\nimport React, { useState, useMemo, useRef, useEffect, useLayoutEffect } from 'react';\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n { t[p] = s[p]; } }\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n { t[p[i]] = s[p[i]]; }\r\n } }\r\n return t;\r\n}\n\nvar SourceType;\n(function (SourceType) {\n SourceType[\"event\"] = \"event\";\n SourceType[\"props\"] = \"prop\";\n})(SourceType || (SourceType = {}));\n\n// basic noop function\nfunction noop() { }\nfunction memoizeOnce(cb) {\n var lastArgs;\n var lastValue = undefined;\n return function () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n if (lastArgs &&\n args.length === lastArgs.length &&\n args.every(function (value, index) { return value === lastArgs[index]; })) {\n return lastValue;\n }\n lastArgs = args;\n lastValue = cb.apply(void 0, args);\n return lastValue;\n };\n}\nfunction charIsNumber(char) {\n return !!(char || '').match(/\\d/);\n}\nfunction isNil(val) {\n return val === null || val === undefined;\n}\nfunction isNanValue(val) {\n return typeof val === 'number' && isNaN(val);\n}\nfunction isNotValidValue(val) {\n return isNil(val) || isNanValue(val) || (typeof val === 'number' && !isFinite(val));\n}\nfunction escapeRegExp(str) {\n return str.replace(/[-[\\]/{}()*+?.\\\\^$|]/g, '\\\\$&');\n}\nfunction getThousandsGroupRegex(thousandsGroupStyle) {\n switch (thousandsGroupStyle) {\n case 'lakh':\n return /(\\d+?)(?=(\\d\\d)+(\\d)(?!\\d))(\\.\\d+)?/g;\n case 'wan':\n return /(\\d)(?=(\\d{4})+(?!\\d))/g;\n case 'thousand':\n default:\n return /(\\d)(?=(\\d{3})+(?!\\d))/g;\n }\n}\nfunction applyThousandSeparator(str, thousandSeparator, thousandsGroupStyle) {\n var thousandsGroupRegex = getThousandsGroupRegex(thousandsGroupStyle);\n var index = str.search(/[1-9]/);\n index = index === -1 ? str.length : index;\n return (str.substring(0, index) +\n str.substring(index, str.length).replace(thousandsGroupRegex, '$1' + thousandSeparator));\n}\nfunction usePersistentCallback(cb) {\n var callbackRef = useRef(cb);\n // keep the callback ref upto date\n callbackRef.current = cb;\n /**\n * initialize a persistent callback which never changes\n * through out the component lifecycle\n */\n var persistentCbRef = useRef(function () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n return callbackRef.current.apply(callbackRef, args);\n });\n return persistentCbRef.current;\n}\n//spilt a float number into different parts beforeDecimal, afterDecimal, and negation\nfunction splitDecimal(numStr, allowNegative) {\n if ( allowNegative === void 0 ) allowNegative = true;\n\n var hasNegation = numStr[0] === '-';\n var addNegation = hasNegation && allowNegative;\n numStr = numStr.replace('-', '');\n var parts = numStr.split('.');\n var beforeDecimal = parts[0];\n var afterDecimal = parts[1] || '';\n return {\n beforeDecimal: beforeDecimal,\n afterDecimal: afterDecimal,\n hasNegation: hasNegation,\n addNegation: addNegation,\n };\n}\nfunction fixLeadingZero(numStr) {\n if (!numStr)\n { return numStr; }\n var isNegative = numStr[0] === '-';\n if (isNegative)\n { numStr = numStr.substring(1, numStr.length); }\n var parts = numStr.split('.');\n var beforeDecimal = parts[0].replace(/^0+/, '') || '0';\n var afterDecimal = parts[1] || '';\n return (\"\" + (isNegative ? '-' : '') + beforeDecimal + (afterDecimal ? (\".\" + afterDecimal) : ''));\n}\n/**\n * limit decimal numbers to given scale\n * Not used .fixedTo because that will break with big numbers\n */\nfunction limitToScale(numStr, scale, fixedDecimalScale) {\n var str = '';\n var filler = fixedDecimalScale ? '0' : '';\n for (var i = 0; i <= scale - 1; i++) {\n str += numStr[i] || filler;\n }\n return str;\n}\nfunction repeat(str, count) {\n return Array(count + 1).join(str);\n}\nfunction toNumericString(num) {\n var _num = num + ''; // typecast number to string\n // store the sign and remove it from the number.\n var sign = _num[0] === '-' ? '-' : '';\n if (sign)\n { _num = _num.substring(1); }\n // split the number into cofficient and exponent\n var ref = _num.split(/[eE]/g);\n var coefficient = ref[0];\n var exponent = ref[1];\n // covert exponent to number;\n exponent = Number(exponent);\n // if there is no exponent part or its 0, return the coffiecient with sign\n if (!exponent)\n { return sign + coefficient; }\n coefficient = coefficient.replace('.', '');\n /**\n * for scientific notation the current decimal index will be after first number (index 0)\n * So effective decimal index will always be 1 + exponent value\n */\n var decimalIndex = 1 + exponent;\n var coffiecientLn = coefficient.length;\n if (decimalIndex < 0) {\n // if decimal index is less then 0 add preceding 0s\n // add 1 as join will have\n coefficient = '0.' + repeat('0', Math.abs(decimalIndex)) + coefficient;\n }\n else if (decimalIndex >= coffiecientLn) {\n // if decimal index is less then 0 add leading 0s\n coefficient = coefficient + repeat('0', decimalIndex - coffiecientLn);\n }\n else {\n // else add decimal point at proper index\n coefficient =\n (coefficient.substring(0, decimalIndex) || '0') + '.' + coefficient.substring(decimalIndex);\n }\n return sign + coefficient;\n}\n/**\n * This method is required to round prop value to given scale.\n * Not used .round or .fixedTo because that will break with big numbers\n */\nfunction roundToPrecision(numStr, scale, fixedDecimalScale) {\n //if number is empty don't do anything return empty string\n if (['', '-'].indexOf(numStr) !== -1)\n { return numStr; }\n var shouldHaveDecimalSeparator = (numStr.indexOf('.') !== -1 || fixedDecimalScale) && scale;\n var ref = splitDecimal(numStr);\n var beforeDecimal = ref.beforeDecimal;\n var afterDecimal = ref.afterDecimal;\n var hasNegation = ref.hasNegation;\n var floatValue = parseFloat((\"0.\" + (afterDecimal || '0')));\n var floatValueStr = afterDecimal.length <= scale ? (\"0.\" + afterDecimal) : floatValue.toFixed(scale);\n var roundedDecimalParts = floatValueStr.split('.');\n var intPart = beforeDecimal;\n // if we have cary over from rounding decimal part, add that on before decimal\n if (beforeDecimal && Number(roundedDecimalParts[0])) {\n intPart = beforeDecimal\n .split('')\n .reverse()\n .reduce(function (roundedStr, current, idx) {\n if (roundedStr.length > idx) {\n return ((Number(roundedStr[0]) + Number(current)).toString() +\n roundedStr.substring(1, roundedStr.length));\n }\n return current + roundedStr;\n }, roundedDecimalParts[0]);\n }\n var decimalPart = limitToScale(roundedDecimalParts[1] || '', scale, fixedDecimalScale);\n var negation = hasNegation ? '-' : '';\n var decimalSeparator = shouldHaveDecimalSeparator ? '.' : '';\n return (\"\" + negation + intPart + decimalSeparator + decimalPart);\n}\n/** set the caret positon in an input field **/\nfunction setCaretPosition(el, caretPos) {\n el.value = el.value;\n // ^ this is used to not only get 'focus', but\n // to make sure we don't have it everything -selected-\n // (it causes an issue in chrome, and having it doesn't hurt any other browser)\n if (el !== null) {\n /* @ts-ignore */\n if (el.createTextRange) {\n /* @ts-ignore */\n var range = el.createTextRange();\n range.move('character', caretPos);\n range.select();\n return true;\n }\n // (el.selectionStart === 0 added for Firefox bug)\n if (el.selectionStart || el.selectionStart === 0) {\n el.focus();\n el.setSelectionRange(caretPos, caretPos);\n return true;\n }\n // fail city, fortunately this never happens (as far as I've tested) :)\n el.focus();\n return false;\n }\n}\n/**\n * TODO: remove dependency of findChangeRange, findChangedRangeFromCaretPositions is better way to find what is changed\n * currently this is mostly required by test and isCharacterSame util\n * Given previous value and newValue it returns the index\n * start - end to which values have changed.\n * This function makes assumption about only consecutive\n * characters are changed which is correct assumption for caret input.\n */\nvar findChangeRange = memoizeOnce(function (prevValue, newValue) {\n var i = 0, j = 0;\n var prevLength = prevValue.length;\n var newLength = newValue.length;\n while (prevValue[i] === newValue[i] && i < prevLength)\n { i++; }\n //check what has been changed from last\n while (prevValue[prevLength - 1 - j] === newValue[newLength - 1 - j] &&\n newLength - j > i &&\n prevLength - j > i) {\n j++;\n }\n return {\n from: { start: i, end: prevLength - j },\n to: { start: i, end: newLength - j },\n };\n});\nvar findChangedRangeFromCaretPositions = function (lastCaretPositions, currentCaretPosition) {\n var startPosition = Math.min(lastCaretPositions.selectionStart, currentCaretPosition);\n return {\n from: { start: startPosition, end: lastCaretPositions.selectionEnd },\n to: { start: startPosition, end: currentCaretPosition },\n };\n};\n/*\n Returns a number whose value is limited to the given range\n*/\nfunction clamp(num, min, max) {\n return Math.min(Math.max(num, min), max);\n}\nfunction geInputCaretPosition(el) {\n /*Max of selectionStart and selectionEnd is taken for the patch of pixel and other mobile device caret bug*/\n return Math.max(el.selectionStart, el.selectionEnd);\n}\nfunction addInputMode() {\n return (typeof navigator !== 'undefined' &&\n !(navigator.platform && /iPhone|iPod/.test(navigator.platform)));\n}\nfunction getDefaultChangeMeta(value) {\n return {\n from: {\n start: 0,\n end: 0,\n },\n to: {\n start: 0,\n end: value.length,\n },\n lastValue: '',\n };\n}\nfunction getMaskAtIndex(mask, index) {\n if ( mask === void 0 ) mask = ' ';\n\n if (typeof mask === 'string') {\n return mask;\n }\n return mask[index] || ' ';\n}\nfunction defaultIsCharacterSame(ref) {\n var currentValue = ref.currentValue;\n var formattedValue = ref.formattedValue;\n var currentValueIndex = ref.currentValueIndex;\n var formattedValueIndex = ref.formattedValueIndex;\n\n return currentValue[currentValueIndex] === formattedValue[formattedValueIndex];\n}\nfunction getCaretPosition(newFormattedValue, lastFormattedValue, curValue, curCaretPos, boundary, isValidInputCharacter, \n/**\n * format function can change the character, the caret engine relies on mapping old value and new value\n * In such case if character is changed, parent can tell which chars are equivalent\n * Some example, all allowedDecimalCharacters are updated to decimalCharacters, 2nd case if user is coverting\n * number to different numeric system.\n */\nisCharacterSame) {\n if ( isCharacterSame === void 0 ) isCharacterSame = defaultIsCharacterSame;\n\n /**\n * if something got inserted on empty value, add the formatted character before the current value,\n * This is to avoid the case where typed character is present on format characters\n */\n var firstAllowedPosition = boundary.findIndex(function (b) { return b; });\n var prefixFormat = newFormattedValue.slice(0, firstAllowedPosition);\n if (!lastFormattedValue && !curValue.startsWith(prefixFormat)) {\n lastFormattedValue = prefixFormat;\n curValue = prefixFormat + curValue;\n curCaretPos = curCaretPos + prefixFormat.length;\n }\n var curValLn = curValue.length;\n var formattedValueLn = newFormattedValue.length;\n // create index map\n var addedIndexMap = {};\n var indexMap = new Array(curValLn);\n for (var i = 0; i < curValLn; i++) {\n indexMap[i] = -1;\n for (var j = 0, jLn = formattedValueLn; j < jLn; j++) {\n var isCharSame = isCharacterSame({\n currentValue: curValue,\n lastValue: lastFormattedValue,\n formattedValue: newFormattedValue,\n currentValueIndex: i,\n formattedValueIndex: j,\n });\n if (isCharSame && addedIndexMap[j] !== true) {\n indexMap[i] = j;\n addedIndexMap[j] = true;\n break;\n }\n }\n }\n /**\n * For current caret position find closest characters (left and right side)\n * which are properly mapped to formatted value.\n * The idea is that the new caret position will exist always in the boundary of\n * that mapped index\n */\n var pos = curCaretPos;\n while (pos < curValLn && (indexMap[pos] === -1 || !isValidInputCharacter(curValue[pos]))) {\n pos++;\n }\n // if the caret position is on last keep the endIndex as last for formatted value\n var endIndex = pos === curValLn || indexMap[pos] === -1 ? formattedValueLn : indexMap[pos];\n pos = curCaretPos - 1;\n while (pos > 0 && indexMap[pos] === -1)\n { pos--; }\n var startIndex = pos === -1 || indexMap[pos] === -1 ? 0 : indexMap[pos] + 1;\n /**\n * case where a char is added on suffix and removed from middle, example 2sq345 becoming $2,345 sq\n * there is still a mapping but the order of start index and end index is changed\n */\n if (startIndex > endIndex)\n { return endIndex; }\n /**\n * given the current caret position if it closer to startIndex\n * keep the new caret position on start index or keep it closer to endIndex\n */\n return curCaretPos - startIndex < endIndex - curCaretPos ? startIndex : endIndex;\n}\n/* This keeps the caret within typing area so people can't type in between prefix or suffix or format characters */\nfunction getCaretPosInBoundary(value, caretPos, boundary, direction) {\n var valLn = value.length;\n // clamp caret position to [0, value.length]\n caretPos = clamp(caretPos, 0, valLn);\n if (direction === 'left') {\n while (caretPos >= 0 && !boundary[caretPos])\n { caretPos--; }\n // if we don't find any suitable caret position on left, set it on first allowed position\n if (caretPos === -1)\n { caretPos = boundary.indexOf(true); }\n }\n else {\n while (caretPos <= valLn && !boundary[caretPos])\n { caretPos++; }\n // if we don't find any suitable caret position on right, set it on last allowed position\n if (caretPos > valLn)\n { caretPos = boundary.lastIndexOf(true); }\n }\n // if we still don't find caret position, set it at the end of value\n if (caretPos === -1)\n { caretPos = valLn; }\n return caretPos;\n}\nfunction caretUnknownFormatBoundary(formattedValue) {\n var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n for (var i = 0, ln = boundaryAry.length; i < ln; i++) {\n // consider caret to be in boundary if it is before or after numeric value\n boundaryAry[i] = Boolean(charIsNumber(formattedValue[i]) || charIsNumber(formattedValue[i - 1]));\n }\n return boundaryAry;\n}\nfunction useInternalValues(value, defaultValue, valueIsNumericString, format, removeFormatting, onValueChange) {\n if ( onValueChange === void 0 ) onValueChange = noop;\n\n var getValues = usePersistentCallback(function (value, valueIsNumericString) {\n var formattedValue, numAsString;\n if (isNotValidValue(value)) {\n numAsString = '';\n formattedValue = '';\n }\n else if (typeof value === 'number' || valueIsNumericString) {\n numAsString = typeof value === 'number' ? toNumericString(value) : value;\n formattedValue = format(numAsString);\n }\n else {\n numAsString = removeFormatting(value, undefined);\n formattedValue = format(numAsString);\n }\n return { formattedValue: formattedValue, numAsString: numAsString };\n });\n var ref = useState(function () {\n return getValues(isNil(value) ? defaultValue : value, valueIsNumericString);\n });\n var values = ref[0];\n var setValues = ref[1];\n var _onValueChange = function (newValues, sourceInfo) {\n if (newValues.formattedValue !== values.formattedValue) {\n setValues({\n formattedValue: newValues.formattedValue,\n numAsString: newValues.value,\n });\n }\n // call parent on value change if only if formatted value is changed\n onValueChange(newValues, sourceInfo);\n };\n // if value is switch from controlled to uncontrolled, use the internal state's value to format with new props\n var _value = value;\n var _valueIsNumericString = valueIsNumericString;\n if (isNil(value)) {\n _value = values.numAsString;\n _valueIsNumericString = true;\n }\n var newValues = getValues(_value, _valueIsNumericString);\n useMemo(function () {\n setValues(newValues);\n }, [newValues.formattedValue]);\n return [values, _onValueChange];\n}\n\nfunction defaultRemoveFormatting(value) {\n return value.replace(/[^0-9]/g, '');\n}\nfunction defaultFormat(value) {\n return value;\n}\nfunction NumberFormatBase(props) {\n var type = props.type; if ( type === void 0 ) type = 'text';\n var displayType = props.displayType; if ( displayType === void 0 ) displayType = 'input';\n var customInput = props.customInput;\n var renderText = props.renderText;\n var getInputRef = props.getInputRef;\n var format = props.format; if ( format === void 0 ) format = defaultFormat;\n var removeFormatting = props.removeFormatting; if ( removeFormatting === void 0 ) removeFormatting = defaultRemoveFormatting;\n var defaultValue = props.defaultValue;\n var valueIsNumericString = props.valueIsNumericString;\n var onValueChange = props.onValueChange;\n var isAllowed = props.isAllowed;\n var onChange = props.onChange; if ( onChange === void 0 ) onChange = noop;\n var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n var onMouseUp = props.onMouseUp; if ( onMouseUp === void 0 ) onMouseUp = noop;\n var onFocus = props.onFocus; if ( onFocus === void 0 ) onFocus = noop;\n var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;\n var propValue = props.value;\n var getCaretBoundary = props.getCaretBoundary; if ( getCaretBoundary === void 0 ) getCaretBoundary = caretUnknownFormatBoundary;\n var isValidInputCharacter = props.isValidInputCharacter; if ( isValidInputCharacter === void 0 ) isValidInputCharacter = charIsNumber;\n var isCharacterSame = props.isCharacterSame;\n var otherProps = __rest(props, [\"type\", \"displayType\", \"customInput\", \"renderText\", \"getInputRef\", \"format\", \"removeFormatting\", \"defaultValue\", \"valueIsNumericString\", \"onValueChange\", \"isAllowed\", \"onChange\", \"onKeyDown\", \"onMouseUp\", \"onFocus\", \"onBlur\", \"value\", \"getCaretBoundary\", \"isValidInputCharacter\", \"isCharacterSame\"]);\n var ref = useInternalValues(propValue, defaultValue, Boolean(valueIsNumericString), format, removeFormatting, onValueChange);\n var ref_0 = ref[0];\n var formattedValue = ref_0.formattedValue;\n var numAsString = ref_0.numAsString;\n var onFormattedValueChange = ref[1];\n var caretPositionBeforeChange = useRef();\n var lastUpdatedValue = useRef({ formattedValue: formattedValue, numAsString: numAsString });\n var _onValueChange = function (values, source) {\n lastUpdatedValue.current = { formattedValue: values.formattedValue, numAsString: values.value };\n onFormattedValueChange(values, source);\n };\n var ref$1 = useState(false);\n var mounted = ref$1[0];\n var setMounted = ref$1[1];\n var focusedElm = useRef(null);\n var timeout = useRef({\n setCaretTimeout: null,\n focusTimeout: null,\n });\n useEffect(function () {\n setMounted(true);\n return function () {\n clearTimeout(timeout.current.setCaretTimeout);\n clearTimeout(timeout.current.focusTimeout);\n };\n }, []);\n var _format = format;\n var getValueObject = function (formattedValue, numAsString) {\n var floatValue = parseFloat(numAsString);\n return {\n formattedValue: formattedValue,\n value: numAsString,\n floatValue: isNaN(floatValue) ? undefined : floatValue,\n };\n };\n var setPatchedCaretPosition = function (el, caretPos, currentValue) {\n // don't reset the caret position when the whole input content is selected\n if (el.selectionStart === 0 && el.selectionEnd === el.value.length)\n { return; }\n /* setting caret position within timeout of 0ms is required for mobile chrome,\n otherwise browser resets the caret position after we set it\n We are also setting it without timeout so that in normal browser we don't see the flickering */\n setCaretPosition(el, caretPos);\n timeout.current.setCaretTimeout = setTimeout(function () {\n if (el.value === currentValue && el.selectionStart !== caretPos) {\n setCaretPosition(el, caretPos);\n }\n }, 0);\n };\n /* This keeps the caret within typing area so people can't type in between prefix or suffix */\n var correctCaretPosition = function (value, caretPos, direction) {\n return getCaretPosInBoundary(value, caretPos, getCaretBoundary(value), direction);\n };\n var getNewCaretPosition = function (inputValue, newFormattedValue, caretPos) {\n var caretBoundary = getCaretBoundary(newFormattedValue);\n var updatedCaretPos = getCaretPosition(newFormattedValue, formattedValue, inputValue, caretPos, caretBoundary, isValidInputCharacter, isCharacterSame);\n //correct caret position if its outside of editable area\n updatedCaretPos = getCaretPosInBoundary(newFormattedValue, updatedCaretPos, caretBoundary);\n return updatedCaretPos;\n };\n var updateValueAndCaretPosition = function (params) {\n var newFormattedValue = params.formattedValue; if ( newFormattedValue === void 0 ) newFormattedValue = '';\n var input = params.input;\n var source = params.source;\n var event = params.event;\n var numAsString = params.numAsString;\n var caretPos;\n if (input) {\n var inputValue = params.inputValue || input.value;\n var currentCaretPosition = geInputCaretPosition(input);\n /**\n * set the value imperatively, this is required for IE fix\n * This is also required as if new caret position is beyond the previous value.\n * Caret position will not be set correctly\n */\n input.value = newFormattedValue;\n //get the caret position\n caretPos = getNewCaretPosition(inputValue, newFormattedValue, currentCaretPosition);\n //set caret position imperatively\n if (caretPos !== undefined) {\n setPatchedCaretPosition(input, caretPos, newFormattedValue);\n }\n }\n if (newFormattedValue !== formattedValue) {\n // trigger onValueChange synchronously, so parent is updated along with the number format. Fix for #277, #287\n _onValueChange(getValueObject(newFormattedValue, numAsString), { event: event, source: source });\n }\n };\n /**\n * if the formatted value is not synced to parent, or if the formatted value is different from last synced value sync it\n * if the formatting props is removed, in which case last formatted value will be different from the numeric string value\n * in such case we need to inform the parent.\n */\n useEffect(function () {\n var ref = lastUpdatedValue.current;\n var lastFormattedValue = ref.formattedValue;\n var lastNumAsString = ref.numAsString;\n if (formattedValue !== lastFormattedValue || numAsString !== lastNumAsString) {\n _onValueChange(getValueObject(formattedValue, numAsString), {\n event: undefined,\n source: SourceType.props,\n });\n }\n }, [formattedValue, numAsString]);\n // also if formatted value is changed from the props, we need to update the caret position\n // keep the last caret position if element is focused\n var currentCaretPosition = focusedElm.current\n ? geInputCaretPosition(focusedElm.current)\n : undefined;\n // needed to prevent warning with useLayoutEffect on server\n var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n useIsomorphicLayoutEffect(function () {\n var input = focusedElm.current;\n if (formattedValue !== lastUpdatedValue.current.formattedValue && input) {\n var caretPos = getNewCaretPosition(lastUpdatedValue.current.formattedValue, formattedValue, currentCaretPosition);\n /**\n * set the value imperatively, as we set the caret position as well imperatively.\n * This is to keep value and caret position in sync\n */\n input.value = formattedValue;\n setPatchedCaretPosition(input, caretPos, formattedValue);\n }\n }, [formattedValue]);\n var formatInputValue = function (inputValue, event, source) {\n var input = event.target;\n var changeRange = caretPositionBeforeChange.current\n ? findChangedRangeFromCaretPositions(caretPositionBeforeChange.current, input.selectionEnd)\n : findChangeRange(formattedValue, inputValue);\n var changeMeta = Object.assign(Object.assign({}, changeRange), { lastValue: formattedValue });\n var _numAsString = removeFormatting(inputValue, changeMeta);\n var _formattedValue = _format(_numAsString);\n // formatting can remove some of the number chars, so we need to fine number string again\n _numAsString = removeFormatting(_formattedValue, undefined);\n if (isAllowed && !isAllowed(getValueObject(_formattedValue, _numAsString))) {\n //reset the caret position\n var input$1 = event.target;\n var currentCaretPosition = geInputCaretPosition(input$1);\n var caretPos = getNewCaretPosition(inputValue, formattedValue, currentCaretPosition);\n input$1.value = formattedValue;\n setPatchedCaretPosition(input$1, caretPos, formattedValue);\n return false;\n }\n updateValueAndCaretPosition({\n formattedValue: _formattedValue,\n numAsString: _numAsString,\n inputValue: inputValue,\n event: event,\n source: source,\n input: event.target,\n });\n return true;\n };\n var setCaretPositionInfoBeforeChange = function (el, endOffset) {\n if ( endOffset === void 0 ) endOffset = 0;\n\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n caretPositionBeforeChange.current = { selectionStart: selectionStart, selectionEnd: selectionEnd + endOffset };\n };\n var _onChange = function (e) {\n var el = e.target;\n var inputValue = el.value;\n var changed = formatInputValue(inputValue, e, SourceType.event);\n if (changed)\n { onChange(e); }\n // reset the position, as we have already handled the caret position\n caretPositionBeforeChange.current = undefined;\n };\n var _onKeyDown = function (e) {\n var el = e.target;\n var key = e.key;\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n var expectedCaretPosition;\n //Handle backspace and delete against non numerical/decimal characters or arrow keys\n if (key === 'ArrowLeft' || key === 'Backspace') {\n expectedCaretPosition = Math.max(selectionStart - 1, 0);\n }\n else if (key === 'ArrowRight') {\n expectedCaretPosition = Math.min(selectionStart + 1, value.length);\n }\n else if (key === 'Delete') {\n expectedCaretPosition = selectionStart;\n }\n // if key is delete and text is not selected keep the end offset to 1, as it deletes one character\n // this is required as selection is not changed on delete case, which changes the change range calculation\n var endOffset = 0;\n if (key === 'Delete' && selectionStart === selectionEnd) {\n endOffset = 1;\n }\n var isArrowKey = key === 'ArrowLeft' || key === 'ArrowRight';\n //if expectedCaretPosition is not set it means we don't want to Handle keyDown\n // also if multiple characters are selected don't handle\n if (expectedCaretPosition === undefined || (selectionStart !== selectionEnd && !isArrowKey)) {\n onKeyDown(e);\n // keep information of what was the caret position before keyDown\n // set it after onKeyDown, in case parent updates the position manually\n setCaretPositionInfoBeforeChange(el, endOffset);\n return;\n }\n var newCaretPosition = expectedCaretPosition;\n if (isArrowKey) {\n var direction = key === 'ArrowLeft' ? 'left' : 'right';\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, direction);\n // arrow left or right only moves the caret, so no need to handle the event, if we are handling it manually\n if (newCaretPosition !== expectedCaretPosition) {\n e.preventDefault();\n }\n }\n else if (key === 'Delete' && !isValidInputCharacter(value[expectedCaretPosition])) {\n // in case of delete go to closest caret boundary on the right side\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'right');\n }\n else if (key === 'Backspace' && !isValidInputCharacter(value[expectedCaretPosition])) {\n // in case of backspace go to closest caret boundary on the left side\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'left');\n }\n if (newCaretPosition !== expectedCaretPosition) {\n setPatchedCaretPosition(el, newCaretPosition, value);\n }\n onKeyDown(e);\n setCaretPositionInfoBeforeChange(el, endOffset);\n };\n /** required to handle the caret position when click anywhere within the input **/\n var _onMouseUp = function (e) {\n var el = e.target;\n /**\n * NOTE: we have to give default value for value as in case when custom input is provided\n * value can come as undefined when nothing is provided on value prop.\n */\n var correctCaretPositionIfRequired = function () {\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n if (selectionStart === selectionEnd) {\n var caretPosition = correctCaretPosition(value, selectionStart);\n if (caretPosition !== selectionStart) {\n setPatchedCaretPosition(el, caretPosition, value);\n }\n }\n };\n correctCaretPositionIfRequired();\n // try to correct after selection has updated by browser\n // this case is required when user clicks on some position while a text is selected on input\n requestAnimationFrame(function () {\n correctCaretPositionIfRequired();\n });\n onMouseUp(e);\n setCaretPositionInfoBeforeChange(el);\n };\n var _onFocus = function (e) {\n // Workaround Chrome and Safari bug https://bugs.chromium.org/p/chromium/issues/detail?id=779328\n // (onFocus event target selectionStart is always 0 before setTimeout)\n if (e.persist)\n { e.persist(); }\n var el = e.target;\n var currentTarget = e.currentTarget;\n focusedElm.current = el;\n timeout.current.focusTimeout = setTimeout(function () {\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n var caretPosition = correctCaretPosition(value, selectionStart);\n //setPatchedCaretPosition only when everything is not selected on focus (while tabbing into the field)\n if (caretPosition !== selectionStart &&\n !(selectionStart === 0 && selectionEnd === value.length)) {\n setPatchedCaretPosition(el, caretPosition, value);\n }\n onFocus(Object.assign(Object.assign({}, e), { currentTarget: currentTarget }));\n }, 0);\n };\n var _onBlur = function (e) {\n focusedElm.current = null;\n clearTimeout(timeout.current.focusTimeout);\n clearTimeout(timeout.current.setCaretTimeout);\n onBlur(e);\n };\n // add input mode on element based on format prop and device once the component is mounted\n var inputMode = mounted && addInputMode() ? 'numeric' : undefined;\n var inputProps = Object.assign({ inputMode: inputMode }, otherProps, {\n type: type,\n value: formattedValue,\n onChange: _onChange,\n onKeyDown: _onKeyDown,\n onMouseUp: _onMouseUp,\n onFocus: _onFocus,\n onBlur: _onBlur,\n });\n if (displayType === 'text') {\n return renderText ? (React.createElement(React.Fragment, null, renderText(formattedValue, otherProps) || null)) : (React.createElement(\"span\", Object.assign({}, otherProps, { ref: getInputRef }), formattedValue));\n }\n else if (customInput) {\n var CustomInput = customInput;\n /* @ts-ignore */\n return React.createElement(CustomInput, Object.assign({}, inputProps, { ref: getInputRef }));\n }\n return React.createElement(\"input\", Object.assign({}, inputProps, { ref: getInputRef }));\n}\n\nfunction format(numStr, props) {\n var decimalScale = props.decimalScale;\n var fixedDecimalScale = props.fixedDecimalScale;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var allowNegative = props.allowNegative;\n var thousandsGroupStyle = props.thousandsGroupStyle; if ( thousandsGroupStyle === void 0 ) thousandsGroupStyle = 'thousand';\n // don't apply formatting on empty string or '-'\n if (numStr === '' || numStr === '-') {\n return numStr;\n }\n var ref = getSeparators(props);\n var thousandSeparator = ref.thousandSeparator;\n var decimalSeparator = ref.decimalSeparator;\n /**\n * Keep the decimal separator\n * when decimalScale is not defined or non zero and the numStr has decimal in it\n * Or if decimalScale is > 0 and fixeDecimalScale is true (even if numStr has no decimal)\n */\n var hasDecimalSeparator = (decimalScale !== 0 && numStr.indexOf('.') !== -1) || (decimalScale && fixedDecimalScale);\n var ref$1 = splitDecimal(numStr, allowNegative);\n var beforeDecimal = ref$1.beforeDecimal;\n var afterDecimal = ref$1.afterDecimal;\n var addNegation = ref$1.addNegation; // eslint-disable-line prefer-const\n //apply decimal precision if its defined\n if (decimalScale !== undefined) {\n afterDecimal = limitToScale(afterDecimal, decimalScale, !!fixedDecimalScale);\n }\n if (thousandSeparator) {\n beforeDecimal = applyThousandSeparator(beforeDecimal, thousandSeparator, thousandsGroupStyle);\n }\n //add prefix and suffix when there is a number present\n if (prefix)\n { beforeDecimal = prefix + beforeDecimal; }\n if (suffix)\n { afterDecimal = afterDecimal + suffix; }\n //restore negation sign\n if (addNegation)\n { beforeDecimal = '-' + beforeDecimal; }\n numStr = beforeDecimal + ((hasDecimalSeparator && decimalSeparator) || '') + afterDecimal;\n return numStr;\n}\nfunction getSeparators(props) {\n var decimalSeparator = props.decimalSeparator; if ( decimalSeparator === void 0 ) decimalSeparator = '.';\n var thousandSeparator = props.thousandSeparator;\n var allowedDecimalSeparators = props.allowedDecimalSeparators;\n if (thousandSeparator === true) {\n thousandSeparator = ',';\n }\n if (!allowedDecimalSeparators) {\n allowedDecimalSeparators = [decimalSeparator, '.'];\n }\n return {\n decimalSeparator: decimalSeparator,\n thousandSeparator: thousandSeparator,\n allowedDecimalSeparators: allowedDecimalSeparators,\n };\n}\nfunction handleNegation(value, allowNegative) {\n if ( value === void 0 ) value = '';\n\n var negationRegex = new RegExp('(-)');\n var doubleNegationRegex = new RegExp('(-)(.)*(-)');\n // Check number has '-' value\n var hasNegation = negationRegex.test(value);\n // Check number has 2 or more '-' values\n var removeNegation = doubleNegationRegex.test(value);\n //remove negation\n value = value.replace(/-/g, '');\n if (hasNegation && !removeNegation && allowNegative) {\n value = '-' + value;\n }\n return value;\n}\nfunction getNumberRegex(decimalSeparator, global) {\n return new RegExp((\"(^-)|[0-9]|\" + (escapeRegExp(decimalSeparator))), global ? 'g' : undefined);\n}\nfunction isNumericString(val, prefix, suffix) {\n // for empty value we can always treat it as numeric string\n if (val === '')\n { return true; }\n return (!(prefix === null || prefix === void 0 ? void 0 : prefix.match(/\\d/)) && !(suffix === null || suffix === void 0 ? void 0 : suffix.match(/\\d/)) && typeof val === 'string' && !isNaN(Number(val)));\n}\nfunction removeFormatting(value, changeMeta, props) {\n var assign;\n\n if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);\n var allowNegative = props.allowNegative;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var decimalScale = props.decimalScale;\n var from = changeMeta.from;\n var to = changeMeta.to;\n var start = to.start;\n var end = to.end;\n var ref = getSeparators(props);\n var allowedDecimalSeparators = ref.allowedDecimalSeparators;\n var decimalSeparator = ref.decimalSeparator;\n var isBeforeDecimalSeparator = value[end] === decimalSeparator;\n /**\n * If only a number is added on empty input which matches with the prefix or suffix,\n * then don't remove it, just return the same\n */\n if (charIsNumber(value) &&\n (value === prefix || value === suffix) &&\n changeMeta.lastValue === '') {\n return value;\n }\n /** Check for any allowed decimal separator is added in the numeric format and replace it with decimal separator */\n if (end - start === 1 && allowedDecimalSeparators.indexOf(value[start]) !== -1) {\n var separator = decimalScale === 0 ? '' : decimalSeparator;\n value = value.substring(0, start) + separator + value.substring(start + 1, value.length);\n }\n var stripNegation = function (value, start, end) {\n /**\n * if prefix starts with - we don't allow negative number to avoid confusion\n * if suffix starts with - and the value length is same as suffix length, then the - sign is from the suffix\n * In other cases, if the value starts with - then it is a negation\n */\n var hasNegation = false;\n var hasDoubleNegation = false;\n if (prefix.startsWith('-')) {\n hasNegation = false;\n }\n else if (value.startsWith('--')) {\n hasNegation = false;\n hasDoubleNegation = true;\n }\n else if (suffix.startsWith('-') && value.length === suffix.length) {\n hasNegation = false;\n }\n else if (value[0] === '-') {\n hasNegation = true;\n }\n var charsToRemove = hasNegation ? 1 : 0;\n if (hasDoubleNegation)\n { charsToRemove = 2; }\n // remove negation/double negation from start to simplify prefix logic as negation comes before prefix\n if (charsToRemove) {\n value = value.substring(charsToRemove);\n // account for the removal of the negation for start and end index\n start -= charsToRemove;\n end -= charsToRemove;\n }\n return { value: value, start: start, end: end, hasNegation: hasNegation };\n };\n var toMetadata = stripNegation(value, start, end);\n var hasNegation = toMetadata.hasNegation;\n ((assign = toMetadata, value = assign.value, start = assign.start, end = assign.end));\n var ref$1 = stripNegation(changeMeta.lastValue, from.start, from.end);\n var fromStart = ref$1.start;\n var fromEnd = ref$1.end;\n var lastValue = ref$1.value;\n // if only prefix and suffix part is updated reset the value to last value\n // if the changed range is from suffix in the updated value, and the the suffix starts with the same characters, allow the change\n var updatedSuffixPart = value.substring(start, end);\n if (value.length &&\n lastValue.length &&\n (fromStart > lastValue.length - suffix.length || fromEnd < prefix.length) &&\n !(updatedSuffixPart && suffix.startsWith(updatedSuffixPart))) {\n value = lastValue;\n }\n /**\n * remove prefix\n * Remove whole prefix part if its present on the value\n * If the prefix is partially deleted (in which case change start index will be less the prefix length)\n * Remove only partial part of prefix.\n */\n var startIndex = 0;\n if (value.startsWith(prefix))\n { startIndex += prefix.length; }\n else if (start < prefix.length)\n { startIndex = start; }\n value = value.substring(startIndex);\n // account for deleted prefix for end\n end -= startIndex;\n /**\n * Remove suffix\n * Remove whole suffix part if its present on the value\n * If the suffix is partially deleted (in which case change end index will be greater than the suffixStartIndex)\n * remove the partial part of suffix\n */\n var endIndex = value.length;\n var suffixStartIndex = value.length - suffix.length;\n if (value.endsWith(suffix))\n { endIndex = suffixStartIndex; }\n // if the suffix is removed from the end\n else if (end > suffixStartIndex)\n { endIndex = end; }\n // if the suffix is removed from start\n else if (end > value.length - suffix.length)\n { endIndex = end; }\n value = value.substring(0, endIndex);\n // add the negation back and handle for double negation\n value = handleNegation(hasNegation ? (\"-\" + value) : value, allowNegative);\n // remove non numeric characters\n value = (value.match(getNumberRegex(decimalSeparator, true)) || []).join('');\n // replace the decimalSeparator with ., and only keep the first separator, ignore following ones\n var firstIndex = value.indexOf(decimalSeparator);\n value = value.replace(new RegExp(escapeRegExp(decimalSeparator), 'g'), function (match, index) {\n return index === firstIndex ? '.' : '';\n });\n //check if beforeDecimal got deleted and there is nothing after decimal,\n //clear all numbers in such case while keeping the - sign\n var ref$2 = splitDecimal(value, allowNegative);\n var beforeDecimal = ref$2.beforeDecimal;\n var afterDecimal = ref$2.afterDecimal;\n var addNegation = ref$2.addNegation; // eslint-disable-line prefer-const\n //clear only if something got deleted before decimal (cursor is before decimal)\n if (to.end - to.start < from.end - from.start &&\n beforeDecimal === '' &&\n isBeforeDecimalSeparator &&\n !parseFloat(afterDecimal)) {\n value = addNegation ? '-' : '';\n }\n return value;\n}\nfunction getCaretBoundary(formattedValue, props) {\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n var hasNegation = formattedValue[0] === '-';\n // fill for prefix and negation\n boundaryAry.fill(false, 0, prefix.length + (hasNegation ? 1 : 0));\n // fill for suffix\n var valLn = formattedValue.length;\n boundaryAry.fill(false, valLn - suffix.length + 1, valLn + 1);\n return boundaryAry;\n}\nfunction validateAndUpdateProps(props) {\n var ref = getSeparators(props);\n var thousandSeparator = ref.thousandSeparator;\n var decimalSeparator = ref.decimalSeparator;\n // eslint-disable-next-line prefer-const\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var allowNegative = props.allowNegative; if ( allowNegative === void 0 ) allowNegative = true;\n if (thousandSeparator === decimalSeparator) {\n throw new Error((\"\\n Decimal separator can't be same as thousand separator.\\n thousandSeparator: \" + thousandSeparator + \" (thousandSeparator = {true} is same as thousandSeparator = \\\",\\\")\\n decimalSeparator: \" + decimalSeparator + \" (default value for decimalSeparator is .)\\n \"));\n }\n if (prefix.startsWith('-') && allowNegative) {\n // TODO: throw error in next major version\n console.error((\"\\n Prefix can't start with '-' when allowNegative is true.\\n prefix: \" + prefix + \"\\n allowNegative: \" + allowNegative + \"\\n \"));\n allowNegative = false;\n }\n return Object.assign(Object.assign({}, props), { allowNegative: allowNegative });\n}\nfunction useNumericFormat(props) {\n // validate props\n props = validateAndUpdateProps(props);\n var _decimalSeparator = props.decimalSeparator;\n var _allowedDecimalSeparators = props.allowedDecimalSeparators;\n var thousandsGroupStyle = props.thousandsGroupStyle;\n var suffix = props.suffix;\n var allowNegative = props.allowNegative;\n var allowLeadingZeros = props.allowLeadingZeros;\n var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;\n var thousandSeparator = props.thousandSeparator;\n var decimalScale = props.decimalScale;\n var fixedDecimalScale = props.fixedDecimalScale;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var defaultValue = props.defaultValue;\n var value = props.value;\n var valueIsNumericString = props.valueIsNumericString;\n var onValueChange = props.onValueChange;\n var restProps = __rest(props, [\"decimalSeparator\", \"allowedDecimalSeparators\", \"thousandsGroupStyle\", \"suffix\", \"allowNegative\", \"allowLeadingZeros\", \"onKeyDown\", \"onBlur\", \"thousandSeparator\", \"decimalScale\", \"fixedDecimalScale\", \"prefix\", \"defaultValue\", \"value\", \"valueIsNumericString\", \"onValueChange\"]);\n // get derived decimalSeparator and allowedDecimalSeparators\n var ref = getSeparators(props);\n var decimalSeparator = ref.decimalSeparator;\n var allowedDecimalSeparators = ref.allowedDecimalSeparators;\n var _format = function (numStr) { return format(numStr, props); };\n var _removeFormatting = function (inputValue, changeMeta) { return removeFormatting(inputValue, changeMeta, props); };\n var _value = isNil(value) ? defaultValue : value;\n // try to figure out isValueNumericString based on format prop and value\n var _valueIsNumericString = valueIsNumericString !== null && valueIsNumericString !== void 0 ? valueIsNumericString : isNumericString(_value, prefix, suffix);\n if (!isNil(value)) {\n _valueIsNumericString = _valueIsNumericString || typeof value === 'number';\n }\n else if (!isNil(defaultValue)) {\n _valueIsNumericString = _valueIsNumericString || typeof defaultValue === 'number';\n }\n var roundIncomingValueToPrecision = function (value) {\n if (isNotValidValue(value))\n { return value; }\n if (typeof value === 'number') {\n value = toNumericString(value);\n }\n /**\n * only round numeric or float string values coming through props,\n * we don't need to do it for onChange events, as we want to prevent typing there\n */\n if (_valueIsNumericString && typeof decimalScale === 'number') {\n return roundToPrecision(value, decimalScale, Boolean(fixedDecimalScale));\n }\n return value;\n };\n var ref$1 = useInternalValues(roundIncomingValueToPrecision(value), roundIncomingValueToPrecision(defaultValue), Boolean(_valueIsNumericString), _format, _removeFormatting, onValueChange);\n var ref$1_0 = ref$1[0];\n var numAsString = ref$1_0.numAsString;\n var formattedValue = ref$1_0.formattedValue;\n var _onValueChange = ref$1[1];\n var _onKeyDown = function (e) {\n var el = e.target;\n var key = e.key;\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n // if user tries to delete partial prefix then ignore it\n if ((key === 'Backspace' || key === 'Delete') && selectionEnd < prefix.length) {\n e.preventDefault();\n return;\n }\n // if multiple characters are selected and user hits backspace, no need to handle anything manually\n if (selectionStart !== selectionEnd) {\n onKeyDown(e);\n return;\n }\n // if user hits backspace, while the cursor is before prefix, and the input has negation, remove the negation\n if (key === 'Backspace' &&\n value[0] === '-' &&\n selectionStart === prefix.length + 1 &&\n allowNegative) {\n // bring the cursor to after negation\n setCaretPosition(el, 1);\n }\n // don't allow user to delete decimal separator when decimalScale and fixedDecimalScale is set\n if (decimalScale && fixedDecimalScale) {\n if (key === 'Backspace' && value[selectionStart - 1] === decimalSeparator) {\n setCaretPosition(el, selectionStart - 1);\n e.preventDefault();\n }\n else if (key === 'Delete' && value[selectionStart] === decimalSeparator) {\n e.preventDefault();\n }\n }\n // if user presses the allowed decimal separator before the separator, move the cursor after the separator\n if ((allowedDecimalSeparators === null || allowedDecimalSeparators === void 0 ? void 0 : allowedDecimalSeparators.includes(key)) && value[selectionStart] === decimalSeparator) {\n setCaretPosition(el, selectionStart + 1);\n }\n var _thousandSeparator = thousandSeparator === true ? ',' : thousandSeparator;\n // move cursor when delete or backspace is pressed before/after thousand separator\n if (key === 'Backspace' && value[selectionStart - 1] === _thousandSeparator) {\n setCaretPosition(el, selectionStart - 1);\n }\n if (key === 'Delete' && value[selectionStart] === _thousandSeparator) {\n setCaretPosition(el, selectionStart + 1);\n }\n onKeyDown(e);\n };\n var _onBlur = function (e) {\n var _value = numAsString;\n // if there no no numeric value, clear the input\n if (!_value.match(/\\d/g)) {\n _value = '';\n }\n // clear leading 0s\n if (!allowLeadingZeros) {\n _value = fixLeadingZero(_value);\n }\n // apply fixedDecimalScale on blur event\n if (fixedDecimalScale && decimalScale) {\n _value = roundToPrecision(_value, decimalScale, fixedDecimalScale);\n }\n if (_value !== numAsString) {\n var formattedValue = format(_value, props);\n _onValueChange({\n formattedValue: formattedValue,\n value: _value,\n floatValue: parseFloat(_value),\n }, {\n event: e,\n source: SourceType.event,\n });\n }\n onBlur(e);\n };\n var isValidInputCharacter = function (inputChar) {\n if (inputChar === decimalSeparator)\n { return true; }\n return charIsNumber(inputChar);\n };\n var isCharacterSame = function (ref) {\n var currentValue = ref.currentValue;\n var lastValue = ref.lastValue;\n var formattedValue = ref.formattedValue;\n var currentValueIndex = ref.currentValueIndex;\n var formattedValueIndex = ref.formattedValueIndex;\n\n var curChar = currentValue[currentValueIndex];\n var newChar = formattedValue[formattedValueIndex];\n /**\n * NOTE: as thousand separator and allowedDecimalSeparators can be same, we need to check on\n * typed range if we have typed any character from allowedDecimalSeparators, in that case we\n * consider different characters like , and . same within the range of updated value.\n */\n var typedRange = findChangeRange(lastValue, currentValue);\n var to = typedRange.to;\n // handle corner case where if we user types a decimal separator with fixedDecimalScale\n // and pass back float value the cursor jumps. #851\n var getDecimalSeparatorIndex = function (value) {\n return _removeFormatting(value).indexOf('.') + prefix.length;\n };\n if (value === 0 &&\n fixedDecimalScale &&\n decimalScale &&\n currentValue[to.start] === decimalSeparator &&\n getDecimalSeparatorIndex(currentValue) < currentValueIndex &&\n getDecimalSeparatorIndex(formattedValue) > formattedValueIndex) {\n return false;\n }\n if (currentValueIndex >= to.start &&\n currentValueIndex < to.end &&\n allowedDecimalSeparators &&\n allowedDecimalSeparators.includes(curChar) &&\n newChar === decimalSeparator) {\n return true;\n }\n return curChar === newChar;\n };\n return Object.assign(Object.assign({}, restProps), { value: formattedValue, valueIsNumericString: false, isValidInputCharacter: isValidInputCharacter,\n isCharacterSame: isCharacterSame, onValueChange: _onValueChange, format: _format, removeFormatting: _removeFormatting, getCaretBoundary: function (formattedValue) { return getCaretBoundary(formattedValue, props); }, onKeyDown: _onKeyDown, onBlur: _onBlur });\n}\nfunction NumericFormat(props) {\n var numericFormatProps = useNumericFormat(props);\n return React.createElement(NumberFormatBase, Object.assign({}, numericFormatProps));\n}\n\nfunction format$1(numStr, props) {\n var format = props.format;\n var allowEmptyFormatting = props.allowEmptyFormatting;\n var mask = props.mask;\n var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n if (numStr === '' && !allowEmptyFormatting)\n { return ''; }\n var hashCount = 0;\n var formattedNumberAry = format.split('');\n for (var i = 0, ln = format.length; i < ln; i++) {\n if (format[i] === patternChar) {\n formattedNumberAry[i] = numStr[hashCount] || getMaskAtIndex(mask, hashCount);\n hashCount += 1;\n }\n }\n return formattedNumberAry.join('');\n}\nfunction removeFormatting$1(value, changeMeta, props) {\n if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);\n\n var format = props.format;\n var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n var from = changeMeta.from;\n var to = changeMeta.to;\n var lastValue = changeMeta.lastValue; if ( lastValue === void 0 ) lastValue = '';\n var isNumericSlot = function (caretPos) { return format[caretPos] === patternChar; };\n var removeFormatChar = function (string, startIndex) {\n var str = '';\n for (var i = 0; i < string.length; i++) {\n if (isNumericSlot(startIndex + i) && charIsNumber(string[i])) {\n str += string[i];\n }\n }\n return str;\n };\n var extractNumbers = function (str) { return str.replace(/[^0-9]/g, ''); };\n // if format doesn't have any number, remove all the non numeric characters\n if (!format.match(/\\d/)) {\n return extractNumbers(value);\n }\n /**\n * if user paste the whole formatted text in an empty input or doing select all and paste, check if matches to the pattern\n * and remove the format characters, if there is a mismatch on the pattern, do plane number extract\n */\n if ((lastValue === '' || from.end - from.start === lastValue.length) &&\n value.length === format.length) {\n var str = '';\n for (var i = 0; i < value.length; i++) {\n if (isNumericSlot(i)) {\n if (charIsNumber(value[i])) {\n str += value[i];\n }\n }\n else if (value[i] !== format[i]) {\n // if there is a mismatch on the pattern, do plane number extract\n return extractNumbers(value);\n }\n }\n return str;\n }\n /**\n * For partial change,\n * where ever there is a change on the input, we can break the number in three parts\n * 1st: left part which is unchanged\n * 2nd: middle part which is changed\n * 3rd: right part which is unchanged\n *\n * The first and third section will be same as last value, only the middle part will change\n * We can consider on the change part all the new characters are non format characters.\n * And on the first and last section it can have partial format characters.\n *\n * We pick first and last section from the lastValue (as that has 1-1 mapping with format)\n * and middle one from the update value.\n */\n var firstSection = lastValue.substring(0, from.start);\n var middleSection = value.substring(to.start, to.end);\n var lastSection = lastValue.substring(from.end);\n return (\"\" + (removeFormatChar(firstSection, 0)) + (extractNumbers(middleSection)) + (removeFormatChar(lastSection, from.end)));\n}\nfunction getCaretBoundary$1(formattedValue, props) {\n var format = props.format;\n var mask = props.mask;\n var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n var hashCount = 0;\n var firstEmptySlot = -1;\n var maskAndIndexMap = {};\n format.split('').forEach(function (char, index) {\n var maskAtIndex = undefined;\n if (char === patternChar) {\n hashCount++;\n maskAtIndex = getMaskAtIndex(mask, hashCount - 1);\n if (firstEmptySlot === -1 && formattedValue[index] === maskAtIndex) {\n firstEmptySlot = index;\n }\n }\n maskAndIndexMap[index] = maskAtIndex;\n });\n var isPosAllowed = function (pos) {\n // the position is allowed if the position is not masked and valid number area\n return format[pos] === patternChar && formattedValue[pos] !== maskAndIndexMap[pos];\n };\n for (var i = 0, ln = boundaryAry.length; i < ln; i++) {\n // consider caret to be in boundary if it is before or after numeric value\n // Note: on pattern based format its denoted by patternCharacter\n // we should also allow user to put cursor on first empty slot\n boundaryAry[i] = i === firstEmptySlot || isPosAllowed(i) || isPosAllowed(i - 1);\n }\n // the first patternChar position is always allowed\n boundaryAry[format.indexOf(patternChar)] = true;\n return boundaryAry;\n}\nfunction validateProps(props) {\n var mask = props.mask;\n if (mask) {\n var maskAsStr = mask === 'string' ? mask : mask.toString();\n if (maskAsStr.match(/\\d/g)) {\n throw new Error((\"Mask \" + mask + \" should not contain numeric character;\"));\n }\n }\n}\nfunction isNumericString$1(val, format) {\n //we can treat empty string as numeric string\n if (val === '')\n { return true; }\n return !(format === null || format === void 0 ? void 0 : format.match(/\\d/)) && typeof val === 'string' && (!!val.match(/^\\d+$/) || val === '');\n}\nfunction usePatternFormat(props) {\n var mask = props.mask;\n var allowEmptyFormatting = props.allowEmptyFormatting;\n var formatProp = props.format;\n var inputMode = props.inputMode; if ( inputMode === void 0 ) inputMode = 'numeric';\n var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n var value = props.value;\n var defaultValue = props.defaultValue;\n var valueIsNumericString = props.valueIsNumericString;\n var restProps = __rest(props, [\"mask\", \"allowEmptyFormatting\", \"format\", \"inputMode\", \"onKeyDown\", \"patternChar\", \"value\", \"defaultValue\", \"valueIsNumericString\"]);\n // validate props\n validateProps(props);\n var _getCaretBoundary = function (formattedValue) {\n return getCaretBoundary$1(formattedValue, props);\n };\n var _onKeyDown = function (e) {\n var key = e.key;\n var el = e.target;\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value;\n // if multiple characters are selected and user hits backspace, no need to handle anything manually\n if (selectionStart !== selectionEnd) {\n onKeyDown(e);\n return;\n }\n // bring the cursor to closest numeric section\n var caretPos = selectionStart;\n // if backspace is pressed after the format characters, bring it to numeric section\n // if delete is pressed before the format characters, bring it to numeric section\n if (key === 'Backspace' || key === 'Delete') {\n var direction = 'right';\n if (key === 'Backspace') {\n while (caretPos > 0 && formatProp[caretPos - 1] !== patternChar) {\n caretPos--;\n }\n direction = 'left';\n }\n else {\n var formatLn = formatProp.length;\n while (caretPos < formatLn && formatProp[caretPos] !== patternChar) {\n caretPos++;\n }\n direction = 'right';\n }\n caretPos = getCaretPosInBoundary(value, caretPos, _getCaretBoundary(value), direction);\n }\n else if (formatProp[caretPos] !== patternChar &&\n key !== 'ArrowLeft' &&\n key !== 'ArrowRight') {\n // if user is typing on format character position, bring user to next allowed caret position\n caretPos = getCaretPosInBoundary(value, caretPos + 1, _getCaretBoundary(value), 'right');\n }\n // if we changing caret position, set the caret position\n if (caretPos !== selectionStart) {\n setCaretPosition(el, caretPos);\n }\n onKeyDown(e);\n };\n // try to figure out isValueNumericString based on format prop and value\n var _value = isNil(value) ? defaultValue : value;\n var isValueNumericString = valueIsNumericString !== null && valueIsNumericString !== void 0 ? valueIsNumericString : isNumericString$1(_value, formatProp);\n var _props = Object.assign(Object.assign({}, props), { valueIsNumericString: isValueNumericString });\n return Object.assign(Object.assign({}, restProps), { value: value,\n defaultValue: defaultValue, valueIsNumericString: isValueNumericString, inputMode: inputMode, format: function (numStr) { return format$1(numStr, _props); }, removeFormatting: function (inputValue, changeMeta) { return removeFormatting$1(inputValue, changeMeta, _props); }, getCaretBoundary: _getCaretBoundary, onKeyDown: _onKeyDown });\n}\nfunction PatternFormat(props) {\n var patternFormatProps = usePatternFormat(props);\n return React.createElement(NumberFormatBase, Object.assign({}, patternFormatProps));\n}\n\nexport { NumberFormatBase, NumericFormat, PatternFormat, getCaretBoundary as getNumericCaretBoundary, getCaretBoundary$1 as getPatternCaretBoundary, format as numericFormatter, format$1 as patternFormatter, removeFormatting as removeNumericFormat, removeFormatting$1 as removePatternFormat, useNumericFormat, usePatternFormat };\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\n\nfunction NumberInputChevron({ direction, style, ...others }) {\n return /* @__PURE__ */ jsx(\n \"svg\",\n {\n style: {\n width: \"var(--ni-chevron-size)\",\n height: \"var(--ni-chevron-size)\",\n transform: direction === \"up\" ? \"rotate(180deg)\" : void 0,\n ...style\n },\n viewBox: \"0 0 15 15\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\",\n ...others,\n children: /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z\",\n fill: \"currentColor\",\n fillRule: \"evenodd\",\n clipRule: \"evenodd\"\n }\n )\n }\n );\n}\n\nexport { NumberInputChevron };\n//# sourceMappingURL=NumberInputChevron.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_e2f5cd4e\",\"controls\":\"m_95e17d22\",\"control\":\"m_80b4b171\"};\n\nexport { classes as default };\n//# sourceMappingURL=NumberInput.module.css.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useRef } from 'react';\nimport cx from 'clsx';\nimport { NumericFormat } from 'react-number-format';\nimport { useUncontrolled, clamp, assignRef, useMergedRef } from '@mantine/hooks';\nimport { noop } from '../../core/utils/noop/noop.mjs';\nimport { getSize } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport { useResolvedStylesApi } from '../../core/styles-api/use-resolved-styles-api/use-resolved-styles-api.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { InputBase } from '../InputBase/InputBase.mjs';\nimport { UnstyledButton } from '../UnstyledButton/UnstyledButton.mjs';\nimport { NumberInputChevron } from './NumberInputChevron.mjs';\nimport classes from './NumberInput.module.css.mjs';\n\nconst leadingDecimalZeroPattern = /^(0\\.0*|-0(\\.0*)?)$/;\nconst leadingZerosPattern = /^-?0\\d+(\\.\\d+)?\\.?$/;\nfunction isNumberString(value) {\n return typeof value === \"string\" && value !== \"\" && !Number.isNaN(Number(value));\n}\nfunction canIncrement(value) {\n if (typeof value === \"number\") {\n return value < Number.MAX_SAFE_INTEGER;\n }\n return value === \"\" || isNumberString(value) && Number(value) < Number.MAX_SAFE_INTEGER;\n}\nfunction getDecimalPlaces(inputValue) {\n return inputValue.toString().replace(\".\", \"\").length;\n}\nfunction isValidNumber(floatValue, value) {\n return (typeof floatValue === \"number\" ? floatValue < Number.MAX_SAFE_INTEGER : !Number.isNaN(Number(floatValue))) && !Number.isNaN(floatValue) && getDecimalPlaces(value) < 14 && value !== \"\";\n}\nfunction isInRange(value, min, max) {\n if (value === void 0) {\n return true;\n }\n const minValid = min === void 0 || value >= min;\n const maxValid = max === void 0 || value <= max;\n return minValid && maxValid;\n}\nconst defaultProps = {\n step: 1,\n clampBehavior: \"blur\",\n allowDecimal: true,\n allowNegative: true,\n withKeyboardEvents: true,\n allowLeadingZeros: true,\n trimLeadingZeroesOnBlur: true,\n startValue: 0\n};\nconst varsResolver = createVarsResolver((_, { size }) => ({\n controls: {\n \"--ni-chevron-size\": getSize(size, \"ni-chevron-size\")\n }\n}));\nconst NumberInput = factory((_props, ref) => {\n const props = useProps(\"NumberInput\", defaultProps, _props);\n const {\n className,\n classNames,\n styles,\n unstyled,\n vars,\n onChange,\n onValueChange,\n value,\n defaultValue,\n max,\n min,\n step,\n hideControls,\n rightSection,\n isAllowed,\n clampBehavior,\n onBlur,\n allowDecimal,\n decimalScale,\n onKeyDown,\n onKeyDownCapture,\n handlersRef,\n startValue,\n disabled,\n rightSectionPointerEvents,\n allowNegative,\n readOnly,\n size,\n rightSectionWidth,\n stepHoldInterval,\n stepHoldDelay,\n allowLeadingZeros,\n withKeyboardEvents,\n trimLeadingZeroesOnBlur,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"NumberInput\",\n classes,\n props,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n const [_value, setValue] = useUncontrolled({\n value,\n defaultValue,\n finalValue: \"\",\n onChange\n });\n const shouldUseStepInterval = stepHoldDelay !== void 0 && stepHoldInterval !== void 0;\n const inputRef = useRef(null);\n const onStepTimeoutRef = useRef(null);\n const stepCountRef = useRef(0);\n const handleValueChange = (payload, event) => {\n if (event.source === \"event\") {\n setValue(\n isValidNumber(payload.floatValue, payload.value) && !leadingDecimalZeroPattern.test(payload.value) && !(allowLeadingZeros ? leadingZerosPattern.test(payload.value) : false) ? payload.floatValue : payload.value\n );\n }\n onValueChange?.(payload, event);\n };\n const getDecimalPlaces2 = (inputValue) => {\n const match = String(inputValue).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);\n if (!match) {\n return 0;\n }\n return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));\n };\n const adjustCursor = (position) => {\n if (inputRef.current && typeof position !== \"undefined\") {\n inputRef.current.setSelectionRange(position, position);\n }\n };\n const incrementRef = useRef(noop);\n incrementRef.current = () => {\n if (!canIncrement(_value)) {\n return;\n }\n let val;\n const currentValuePrecision = getDecimalPlaces2(_value);\n const stepPrecision = getDecimalPlaces2(step);\n const maxPrecision = Math.max(currentValuePrecision, stepPrecision);\n const factor = 10 ** maxPrecision;\n if (!isNumberString(_value) && (typeof _value !== \"number\" || Number.isNaN(_value))) {\n val = clamp(startValue, min, max);\n } else if (max !== void 0) {\n const incrementedValue = (Math.round(Number(_value) * factor) + Math.round(step * factor)) / factor;\n val = incrementedValue <= max ? incrementedValue : max;\n } else {\n val = (Math.round(Number(_value) * factor) + Math.round(step * factor)) / factor;\n }\n const formattedValue = val.toFixed(maxPrecision);\n setValue(parseFloat(formattedValue));\n onValueChange?.(\n { floatValue: parseFloat(formattedValue), formattedValue, value: formattedValue },\n { source: \"increment\" }\n );\n setTimeout(() => adjustCursor(inputRef.current?.value.length), 0);\n };\n const decrementRef = useRef(noop);\n decrementRef.current = () => {\n if (!canIncrement(_value)) {\n return;\n }\n let val;\n const minValue = min !== void 0 ? min : !allowNegative ? 0 : Number.MIN_SAFE_INTEGER;\n const currentValuePrecision = getDecimalPlaces2(_value);\n const stepPrecision = getDecimalPlaces2(step);\n const maxPrecision = Math.max(currentValuePrecision, stepPrecision);\n const factor = 10 ** maxPrecision;\n if (!isNumberString(_value) && typeof _value !== \"number\" || Number.isNaN(_value)) {\n val = clamp(startValue, minValue, max);\n } else {\n const decrementedValue = (Math.round(Number(_value) * factor) - Math.round(step * factor)) / factor;\n val = minValue !== void 0 && decrementedValue < minValue ? minValue : decrementedValue;\n }\n const formattedValue = val.toFixed(maxPrecision);\n setValue(parseFloat(formattedValue));\n onValueChange?.(\n { floatValue: parseFloat(formattedValue), formattedValue, value: formattedValue },\n { source: \"decrement\" }\n );\n setTimeout(() => adjustCursor(inputRef.current?.value.length), 0);\n };\n const handleKeyDown = (event) => {\n onKeyDown?.(event);\n if (readOnly || !withKeyboardEvents) {\n return;\n }\n if (event.key === \"ArrowUp\") {\n event.preventDefault();\n incrementRef.current();\n }\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n decrementRef.current();\n }\n };\n const handleKeyDownCapture = (event) => {\n onKeyDownCapture?.(event);\n if (event.key === \"Backspace\") {\n const input = inputRef.current;\n if (input.selectionStart === 0 && input.selectionStart === input.selectionEnd) {\n event.preventDefault();\n window.setTimeout(() => adjustCursor(0), 0);\n }\n }\n };\n const handleBlur = (event) => {\n let sanitizedValue = _value;\n if (clampBehavior === \"blur\" && typeof sanitizedValue === \"number\") {\n const clampedValue = clamp(sanitizedValue, min, max);\n sanitizedValue = clampedValue;\n }\n if (trimLeadingZeroesOnBlur && typeof sanitizedValue === \"string\" && getDecimalPlaces2(sanitizedValue) < 15) {\n const replaced = sanitizedValue.toString().replace(/^0+/, \"\");\n const parsedValue = parseFloat(replaced);\n sanitizedValue = Number.isNaN(parsedValue) || parsedValue > Number.MAX_SAFE_INTEGER ? replaced : clamp(parsedValue, min, max);\n }\n if (_value !== sanitizedValue) {\n setValue(sanitizedValue);\n }\n onBlur?.(event);\n };\n assignRef(handlersRef, { increment: incrementRef.current, decrement: decrementRef.current });\n const onStepHandleChange = (isIncrement) => {\n if (isIncrement) {\n incrementRef.current();\n } else {\n decrementRef.current();\n }\n stepCountRef.current += 1;\n };\n const onStepLoop = (isIncrement) => {\n onStepHandleChange(isIncrement);\n if (shouldUseStepInterval) {\n const interval = typeof stepHoldInterval === \"number\" ? stepHoldInterval : stepHoldInterval(stepCountRef.current);\n onStepTimeoutRef.current = window.setTimeout(() => onStepLoop(isIncrement), interval);\n }\n };\n const onStep = (event, isIncrement) => {\n event.preventDefault();\n inputRef.current?.focus();\n onStepHandleChange(isIncrement);\n if (shouldUseStepInterval) {\n onStepTimeoutRef.current = window.setTimeout(() => onStepLoop(isIncrement), stepHoldDelay);\n }\n };\n const onStepDone = () => {\n if (onStepTimeoutRef.current) {\n window.clearTimeout(onStepTimeoutRef.current);\n }\n onStepTimeoutRef.current = null;\n stepCountRef.current = 0;\n };\n const controls = /* @__PURE__ */ jsxs(\"div\", { ...getStyles(\"controls\"), children: [\n /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ...getStyles(\"control\"),\n tabIndex: -1,\n \"aria-hidden\": true,\n disabled: disabled || typeof _value === \"number\" && max !== void 0 && _value >= max,\n mod: { direction: \"up\" },\n onMouseDown: (event) => event.preventDefault(),\n onPointerDown: (event) => {\n onStep(event, true);\n },\n onPointerUp: onStepDone,\n onPointerLeave: onStepDone,\n children: /* @__PURE__ */ jsx(NumberInputChevron, { direction: \"up\" })\n }\n ),\n /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ...getStyles(\"control\"),\n tabIndex: -1,\n \"aria-hidden\": true,\n disabled: disabled || typeof _value === \"number\" && min !== void 0 && _value <= min,\n mod: { direction: \"down\" },\n onMouseDown: (event) => event.preventDefault(),\n onPointerDown: (event) => {\n onStep(event, false);\n },\n onPointerUp: onStepDone,\n onPointerLeave: onStepDone,\n children: /* @__PURE__ */ jsx(NumberInputChevron, { direction: \"down\" })\n }\n )\n ] });\n return /* @__PURE__ */ jsx(\n InputBase,\n {\n component: NumericFormat,\n allowNegative,\n className: cx(classes.root, className),\n size,\n ...others,\n readOnly,\n disabled,\n value: _value,\n getInputRef: useMergedRef(ref, inputRef),\n onValueChange: handleValueChange,\n rightSection: hideControls || readOnly || !canIncrement(_value) ? rightSection : rightSection || controls,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n __staticSelector: \"NumberInput\",\n decimalScale: allowDecimal ? decimalScale : 0,\n onKeyDown: handleKeyDown,\n onKeyDownCapture: handleKeyDownCapture,\n rightSectionPointerEvents: rightSectionPointerEvents ?? (disabled ? \"none\" : void 0),\n rightSectionWidth: rightSectionWidth ?? `var(--ni-right-section-width-${size || \"sm\"})`,\n allowLeadingZeros,\n onBlur: handleBlur,\n isAllowed: (val) => {\n if (clampBehavior === \"strict\") {\n if (isAllowed) {\n return isAllowed(val) && isInRange(val.floatValue, min, max);\n }\n return isInRange(val.floatValue, min, max);\n }\n return isAllowed ? isAllowed(val) : true;\n }\n }\n );\n});\nNumberInput.classes = { ...InputBase.classes, ...classes };\nNumberInput.displayName = \"@mantine/core/NumberInput\";\n\nexport { NumberInput };\n//# sourceMappingURL=NumberInput.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [PaginationProvider, usePaginationContext] = createSafeContext(\n \"Pagination.Root component was not found in tree\"\n);\n\nexport { PaginationProvider, usePaginationContext };\n//# sourceMappingURL=Pagination.context.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_4addd315\",\"control\":\"m_326d024a\",\"dots\":\"m_4ad7767d\"};\n\nexport { classes as default };\n//# sourceMappingURL=Pagination.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { UnstyledButton } from '../../UnstyledButton/UnstyledButton.mjs';\nimport { usePaginationContext } from '../Pagination.context.mjs';\nimport classes from '../Pagination.module.css.mjs';\n\nconst defaultProps = {\n withPadding: true\n};\nconst PaginationControl = factory((_props, ref) => {\n const props = useProps(\"PaginationControl\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n vars,\n active,\n disabled,\n withPadding,\n mod,\n ...others\n } = props;\n const ctx = usePaginationContext();\n const _disabled = disabled || ctx.disabled;\n return /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ref,\n disabled: _disabled,\n mod: [{ active, disabled: _disabled, \"with-padding\": withPadding }, mod],\n ...ctx.getStyles(\"control\", { className, style, classNames, styles, active: !_disabled }),\n ...others\n }\n );\n});\nPaginationControl.classes = classes;\nPaginationControl.displayName = \"@mantine/core/PaginationControl\";\n\nexport { PaginationControl };\n//# sourceMappingURL=PaginationControl.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\n\nfunction PaginationIcon({ style, children, path, ...others }) {\n return /* @__PURE__ */ jsx(\n \"svg\",\n {\n viewBox: \"0 0 16 16\",\n xmlns: \"http://www.w3.org/2000/svg\",\n style: {\n width: \"calc(var(--pagination-control-size) / 1.8)\",\n height: \"calc(var(--pagination-control-size) / 1.8)\",\n ...style\n },\n ...others,\n children: /* @__PURE__ */ jsx(\"path\", { d: path, fill: \"currentColor\" })\n }\n );\n}\nconst PaginationNextIcon = (props) => /* @__PURE__ */ jsx(\n PaginationIcon,\n {\n ...props,\n path: \"M8.781 8l-3.3-3.3.943-.943L10.667 8l-4.243 4.243-.943-.943 3.3-3.3z\"\n }\n);\nconst PaginationPreviousIcon = (props) => /* @__PURE__ */ jsx(\n PaginationIcon,\n {\n ...props,\n path: \"M7.219 8l3.3 3.3-.943.943L5.333 8l4.243-4.243.943.943-3.3 3.3z\"\n }\n);\nconst PaginationFirstIcon = (props) => /* @__PURE__ */ jsx(\n PaginationIcon,\n {\n ...props,\n path: \"M6.85355 3.85355C7.04882 3.65829 7.04882 3.34171 6.85355 3.14645C6.65829 2.95118 6.34171 2.95118 6.14645 3.14645L2.14645 7.14645C1.95118 7.34171 1.95118 7.65829 2.14645 7.85355L6.14645 11.8536C6.34171 12.0488 6.65829 12.0488 6.85355 11.8536C7.04882 11.6583 7.04882 11.3417 6.85355 11.1464L3.20711 7.5L6.85355 3.85355ZM12.8536 3.85355C13.0488 3.65829 13.0488 3.34171 12.8536 3.14645C12.6583 2.95118 12.3417 2.95118 12.1464 3.14645L8.14645 7.14645C7.95118 7.34171 7.95118 7.65829 8.14645 7.85355L12.1464 11.8536C12.3417 12.0488 12.6583 12.0488 12.8536 11.8536C13.0488 11.6583 13.0488 11.3417 12.8536 11.1464L9.20711 7.5L12.8536 3.85355Z\"\n }\n);\nconst PaginationLastIcon = (props) => /* @__PURE__ */ jsx(\n PaginationIcon,\n {\n ...props,\n path: \"M2.14645 11.1464C1.95118 11.3417 1.95118 11.6583 2.14645 11.8536C2.34171 12.0488 2.65829 12.0488 2.85355 11.8536L6.85355 7.85355C7.04882 7.65829 7.04882 7.34171 6.85355 7.14645L2.85355 3.14645C2.65829 2.95118 2.34171 2.95118 2.14645 3.14645C1.95118 3.34171 1.95118 3.65829 2.14645 3.85355L5.79289 7.5L2.14645 11.1464ZM8.14645 11.1464C7.95118 11.3417 7.95118 11.6583 8.14645 11.8536C8.34171 12.0488 8.65829 12.0488 8.85355 11.8536L12.8536 7.85355C13.0488 7.65829 13.0488 7.34171 12.8536 7.14645L8.85355 3.14645C8.65829 2.95118 8.34171 2.95118 8.14645 3.14645C7.95118 3.34171 7.95118 3.65829 8.14645 3.85355L11.7929 7.5L8.14645 11.1464Z\"\n }\n);\nconst PaginationDotsIcon = (props) => /* @__PURE__ */ jsx(\n PaginationIcon,\n {\n ...props,\n path: \"M2 8c0-.733.6-1.333 1.333-1.333.734 0 1.334.6 1.334 1.333s-.6 1.333-1.334 1.333C2.6 9.333 2 8.733 2 8zm9.333 0c0-.733.6-1.333 1.334-1.333C13.4 6.667 14 7.267 14 8s-.6 1.333-1.333 1.333c-.734 0-1.334-.6-1.334-1.333zM6.667 8c0-.733.6-1.333 1.333-1.333s1.333.6 1.333 1.333S8.733 9.333 8 9.333 6.667 8.733 6.667 8z\"\n }\n);\n\nexport { PaginationDotsIcon, PaginationFirstIcon, PaginationLastIcon, PaginationNextIcon, PaginationPreviousIcon };\n//# sourceMappingURL=Pagination.icons.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { usePaginationContext } from '../Pagination.context.mjs';\nimport { PaginationDotsIcon } from '../Pagination.icons.mjs';\nimport classes from '../Pagination.module.css.mjs';\n\nconst defaultProps = {\n icon: PaginationDotsIcon\n};\nconst PaginationDots = factory((_props, ref) => {\n const props = useProps(\"PaginationDots\", defaultProps, _props);\n const { classNames, className, style, styles, vars, icon, ...others } = props;\n const ctx = usePaginationContext();\n const Icon = icon;\n return /* @__PURE__ */ jsx(Box, { ref, ...ctx.getStyles(\"dots\", { className, style, styles, classNames }), ...others, children: /* @__PURE__ */ jsx(\n Icon,\n {\n style: {\n width: \"calc(var(--pagination-control-size) / 1.8)\",\n height: \"calc(var(--pagination-control-size) / 1.8)\"\n }\n }\n ) });\n});\nPaginationDots.classes = classes;\nPaginationDots.displayName = \"@mantine/core/PaginationDots\";\n\nexport { PaginationDots };\n//# sourceMappingURL=PaginationDots.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { createPolymorphicComponent } from '../../../core/factory/create-polymorphic-component.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { usePaginationContext } from '../Pagination.context.mjs';\nimport { PaginationNextIcon, PaginationPreviousIcon, PaginationFirstIcon, PaginationLastIcon } from '../Pagination.icons.mjs';\nimport { PaginationControl } from '../PaginationControl/PaginationControl.mjs';\n\nfunction createEdgeComponent({ icon, name, action, type }) {\n const defaultProps = { icon };\n const Component = forwardRef((props, ref) => {\n const { icon: _icon, ...others } = useProps(name, defaultProps, props);\n const Icon = _icon;\n const ctx = usePaginationContext();\n const disabled = type === \"next\" ? ctx.active === ctx.total : ctx.active === 1;\n return /* @__PURE__ */ jsx(\n PaginationControl,\n {\n disabled: ctx.disabled || disabled,\n ref,\n onClick: ctx[action],\n withPadding: false,\n ...others,\n children: /* @__PURE__ */ jsx(\n Icon,\n {\n className: \"mantine-rotate-rtl\",\n style: {\n width: \"calc(var(--pagination-control-size) / 1.8)\",\n height: \"calc(var(--pagination-control-size) / 1.8)\"\n }\n }\n )\n }\n );\n });\n Component.displayName = `@mantine/core/${name}`;\n return createPolymorphicComponent(Component);\n}\nconst PaginationNext = createEdgeComponent({\n icon: PaginationNextIcon,\n name: \"PaginationNext\",\n action: \"onNext\",\n type: \"next\"\n});\nconst PaginationPrevious = createEdgeComponent({\n icon: PaginationPreviousIcon,\n name: \"PaginationPrevious\",\n action: \"onPrevious\",\n type: \"previous\"\n});\nconst PaginationFirst = createEdgeComponent({\n icon: PaginationFirstIcon,\n name: \"PaginationFirst\",\n action: \"onFirst\",\n type: \"previous\"\n});\nconst PaginationLast = createEdgeComponent({\n icon: PaginationLastIcon,\n name: \"PaginationLast\",\n action: \"onLast\",\n type: \"next\"\n});\n\nexport { PaginationFirst, PaginationLast, PaginationNext, PaginationPrevious, createEdgeComponent };\n//# sourceMappingURL=PaginationEdges.mjs.map\n","'use client';\nimport { jsx, Fragment } from 'react/jsx-runtime';\nimport { usePaginationContext } from '../Pagination.context.mjs';\nimport { PaginationControl } from '../PaginationControl/PaginationControl.mjs';\nimport { PaginationDots } from '../PaginationDots/PaginationDots.mjs';\n\nfunction PaginationItems({ dotsIcon }) {\n const ctx = usePaginationContext();\n const items = ctx.range.map((page, index) => {\n if (page === \"dots\") {\n return /* @__PURE__ */ jsx(PaginationDots, { icon: dotsIcon }, index);\n }\n return /* @__PURE__ */ jsx(\n PaginationControl,\n {\n active: page === ctx.active,\n \"aria-current\": page === ctx.active ? \"page\" : void 0,\n onClick: () => ctx.onChange(page),\n disabled: ctx.disabled,\n ...ctx.getItemProps?.(page),\n children: ctx.getItemProps?.(page)?.children ?? page\n },\n index\n );\n });\n return /* @__PURE__ */ jsx(Fragment, { children: items });\n}\nPaginationItems.displayName = \"@mantine/core/PaginationItems\";\n\nexport { PaginationItems };\n//# sourceMappingURL=PaginationItems.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { usePagination } from '@mantine/hooks';\nimport 'react';\nimport { getRadius, getSize, getFontSize } from '../../../core/utils/get-size/get-size.mjs';\nimport { createEventHandler } from '../../../core/utils/create-event-handler/create-event-handler.mjs';\nimport { createVarsResolver } from '../../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { getThemeColor } from '../../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport { getContrastColor } from '../../../core/MantineProvider/color-functions/get-contrast-color/get-contrast-color.mjs';\nimport { getAutoContrastValue } from '../../../core/MantineProvider/color-functions/get-auto-contrast-value/get-auto-contrast-value.mjs';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { PaginationProvider } from '../Pagination.context.mjs';\nimport classes from '../Pagination.module.css.mjs';\n\nconst defaultProps = {\n siblings: 1,\n boundaries: 1\n};\nconst varsResolver = createVarsResolver(\n (theme, { size, radius, color, autoContrast }) => ({\n root: {\n \"--pagination-control-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--pagination-control-size\": getSize(size, \"pagination-control-size\"),\n \"--pagination-control-fz\": getFontSize(size),\n \"--pagination-active-bg\": color ? getThemeColor(color, theme) : void 0,\n \"--pagination-active-color\": getAutoContrastValue(autoContrast, theme) ? getContrastColor({ color, theme, autoContrast }) : void 0\n }\n })\n);\nconst PaginationRoot = factory((_props, ref) => {\n const props = useProps(\"PaginationRoot\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n total,\n value,\n defaultValue,\n onChange,\n disabled,\n siblings,\n boundaries,\n color,\n radius,\n onNextPage,\n onPreviousPage,\n onFirstPage,\n onLastPage,\n getItemProps,\n autoContrast,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Pagination\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const { range, setPage, next, previous, active, first, last } = usePagination({\n page: value,\n initialPage: defaultValue,\n onChange,\n total,\n siblings,\n boundaries\n });\n const handleNextPage = createEventHandler(onNextPage, next);\n const handlePreviousPage = createEventHandler(onPreviousPage, previous);\n const handleFirstPage = createEventHandler(onFirstPage, first);\n const handleLastPage = createEventHandler(onLastPage, last);\n return /* @__PURE__ */ jsx(\n PaginationProvider,\n {\n value: {\n total,\n range,\n active,\n disabled,\n getItemProps,\n onChange: setPage,\n onNext: handleNextPage,\n onPrevious: handlePreviousPage,\n onFirst: handleFirstPage,\n onLast: handleLastPage,\n getStyles\n },\n children: /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\"), ...others })\n }\n );\n});\nPaginationRoot.classes = classes;\nPaginationRoot.displayName = \"@mantine/core/PaginationRoot\";\n\nexport { PaginationRoot };\n//# sourceMappingURL=PaginationRoot.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Group } from '../Group/Group.mjs';\nimport { PaginationControl } from './PaginationControl/PaginationControl.mjs';\nimport { PaginationDots } from './PaginationDots/PaginationDots.mjs';\nimport { PaginationFirst, PaginationLast, PaginationNext, PaginationPrevious } from './PaginationEdges/PaginationEdges.mjs';\nimport { PaginationItems } from './PaginationItems/PaginationItems.mjs';\nimport { PaginationRoot } from './PaginationRoot/PaginationRoot.mjs';\nimport classes from './Pagination.module.css.mjs';\n\nconst defaultProps = {\n withControls: true,\n withPages: true,\n siblings: 1,\n boundaries: 1,\n gap: 8\n};\nconst Pagination = factory((_props, ref) => {\n const props = useProps(\"Pagination\", defaultProps, _props);\n const {\n withEdges,\n withControls,\n getControlProps,\n nextIcon,\n previousIcon,\n lastIcon,\n firstIcon,\n dotsIcon,\n total,\n gap,\n hideWithOnePage,\n withPages,\n ...others\n } = props;\n if (total <= 0 || hideWithOnePage && total === 1) {\n return null;\n }\n return /* @__PURE__ */ jsx(PaginationRoot, { ref, total, ...others, children: /* @__PURE__ */ jsxs(Group, { gap, children: [\n withEdges && /* @__PURE__ */ jsx(PaginationFirst, { icon: firstIcon, ...getControlProps?.(\"first\") }),\n withControls && /* @__PURE__ */ jsx(PaginationPrevious, { icon: previousIcon, ...getControlProps?.(\"previous\") }),\n withPages && /* @__PURE__ */ jsx(PaginationItems, { dotsIcon }),\n withControls && /* @__PURE__ */ jsx(PaginationNext, { icon: nextIcon, ...getControlProps?.(\"next\") }),\n withEdges && /* @__PURE__ */ jsx(PaginationLast, { icon: lastIcon, ...getControlProps?.(\"last\") })\n ] }) });\n});\nPagination.classes = classes;\nPagination.displayName = \"@mantine/core/Pagination\";\nPagination.Root = PaginationRoot;\nPagination.Control = PaginationControl;\nPagination.Dots = PaginationDots;\nPagination.First = PaginationFirst;\nPagination.Last = PaginationLast;\nPagination.Next = PaginationNext;\nPagination.Previous = PaginationPrevious;\nPagination.Items = PaginationItems;\n\nexport { Pagination };\n//# sourceMappingURL=Pagination.mjs.map\n","'use client';\nimport 'react';\nimport 'react/jsx-runtime';\nimport { createOptionalContext } from '../../core/utils/create-optional-context/create-optional-context.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [RadioGroupProvider, useRadioGroupContext] = createOptionalContext();\n\nexport { RadioGroupProvider, useRadioGroupContext };\n//# sourceMappingURL=RadioGroup.context.mjs.map\n","'use client';\nimport 'react';\nimport 'react/jsx-runtime';\nimport { createOptionalContext } from '../../../core/utils/create-optional-context/create-optional-context.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [RadioCardProvider, useRadioCardContext] = createOptionalContext();\n\nexport { RadioCardProvider, useRadioCardContext };\n//# sourceMappingURL=RadioCard.context.mjs.map\n","'use client';\nvar classes = {\"card\":\"m_9dc8ae12\"};\n\nexport { classes as default };\n//# sourceMappingURL=RadioCard.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport { getRadius } from '../../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../../core/styles-api/use-styles/use-styles.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport { useDirection } from '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { UnstyledButton } from '../../UnstyledButton/UnstyledButton.mjs';\nimport { useRadioGroupContext } from '../RadioGroup.context.mjs';\nimport { RadioCardProvider } from './RadioCard.context.mjs';\nimport classes from './RadioCard.module.css.mjs';\n\nconst defaultProps = {\n withBorder: true\n};\nconst varsResolver = createVarsResolver((_, { radius }) => ({\n card: {\n \"--card-radius\": getRadius(radius)\n }\n}));\nconst RadioCard = factory((_props, ref) => {\n const props = useProps(\"RadioCard\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n checked,\n mod,\n withBorder,\n value,\n onClick,\n name,\n onKeyDown,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"RadioCard\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver,\n rootSelector: \"card\"\n });\n const { dir } = useDirection();\n const ctx = useRadioGroupContext();\n const _checked = typeof checked === \"boolean\" ? checked : ctx?.value === value || false;\n const _name = name || ctx?.name;\n const handleKeyDown = (event) => {\n onKeyDown?.(event);\n if ([\"ArrowDown\", \"ArrowUp\", \"ArrowLeft\", \"ArrowRight\"].includes(event.nativeEvent.code)) {\n event.preventDefault();\n const siblings = Array.from(\n document.querySelectorAll(\n `[role=\"radio\"][name=\"${_name || \"__mantine\"}\"]`\n )\n );\n const currentIndex = siblings.findIndex((element) => element === event.target);\n const nextIndex = currentIndex + 1 >= siblings.length ? 0 : currentIndex + 1;\n const prevIndex = currentIndex - 1 < 0 ? siblings.length - 1 : currentIndex - 1;\n if (event.nativeEvent.code === \"ArrowDown\") {\n siblings[nextIndex].focus();\n siblings[nextIndex].click();\n }\n if (event.nativeEvent.code === \"ArrowUp\") {\n siblings[prevIndex].focus();\n siblings[prevIndex].click();\n }\n if (event.nativeEvent.code === \"ArrowLeft\") {\n siblings[dir === \"ltr\" ? prevIndex : nextIndex].focus();\n siblings[dir === \"ltr\" ? prevIndex : nextIndex].click();\n }\n if (event.nativeEvent.code === \"ArrowRight\") {\n siblings[dir === \"ltr\" ? nextIndex : prevIndex].focus();\n siblings[dir === \"ltr\" ? nextIndex : prevIndex].click();\n }\n }\n };\n return /* @__PURE__ */ jsx(RadioCardProvider, { value: { checked: _checked }, children: /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ref,\n mod: [{ \"with-border\": withBorder, checked: _checked }, mod],\n ...getStyles(\"card\"),\n ...others,\n role: \"radio\",\n \"aria-checked\": _checked,\n name: _name,\n onClick: (event) => {\n onClick?.(event);\n ctx?.onChange(value || \"\");\n },\n onKeyDown: handleKeyDown\n }\n ) });\n});\nRadioCard.displayName = \"@mantine/core/RadioCard\";\nRadioCard.classes = classes;\n\nexport { RadioCard };\n//# sourceMappingURL=RadioCard.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useId, useUncontrolled } from '@mantine/hooks';\nimport 'react';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Input } from '../../Input/Input.mjs';\nimport '../../Input/InputWrapper/InputWrapper.mjs';\nimport '../../Input/InputDescription/InputDescription.mjs';\nimport '../../Input/InputError/InputError.mjs';\nimport '../../Input/InputLabel/InputLabel.mjs';\nimport '../../Input/InputPlaceholder/InputPlaceholder.mjs';\nimport '../../Input/InputClearButton/InputClearButton.mjs';\nimport '../../Input/InputWrapper.context.mjs';\nimport { InputsGroupFieldset } from '../../InputsGroupFieldset/InputsGroupFieldset.mjs';\nimport { RadioGroupProvider } from '../RadioGroup.context.mjs';\n\nconst defaultProps = {};\nconst RadioGroup = factory((props, ref) => {\n const { value, defaultValue, onChange, size, wrapperProps, children, name, readOnly, ...others } = useProps(\"RadioGroup\", defaultProps, props);\n const _name = useId(name);\n const [_value, setValue] = useUncontrolled({\n value,\n defaultValue,\n finalValue: \"\",\n onChange\n });\n const handleChange = (event) => !readOnly && setValue(typeof event === \"string\" ? event : event.currentTarget.value);\n return /* @__PURE__ */ jsx(RadioGroupProvider, { value: { value: _value, onChange: handleChange, size, name: _name }, children: /* @__PURE__ */ jsx(\n Input.Wrapper,\n {\n size,\n ref,\n ...wrapperProps,\n ...others,\n labelElement: \"div\",\n __staticSelector: \"RadioGroup\",\n children: /* @__PURE__ */ jsx(InputsGroupFieldset, { role: \"radiogroup\", children })\n }\n ) });\n});\nRadioGroup.classes = Input.Wrapper.classes;\nRadioGroup.displayName = \"@mantine/core/RadioGroup\";\n\nexport { RadioGroup };\n//# sourceMappingURL=RadioGroup.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nfunction RadioIcon({ size, style, ...others }) {\n return /* @__PURE__ */ jsx(\n \"svg\",\n {\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 5 5\",\n style: { width: rem(size), height: rem(size), ...style },\n \"aria-hidden\": true,\n ...others,\n children: /* @__PURE__ */ jsx(\"circle\", { cx: \"2.5\", cy: \"2.5\", r: \"2.5\", fill: \"currentColor\" })\n }\n );\n}\n\nexport { RadioIcon };\n//# sourceMappingURL=RadioIcon.mjs.map\n","'use client';\nvar classes = {\"indicator\":\"m_717d7ff6\",\"icon\":\"m_3e4da632\",\"indicator--outline\":\"m_2980836c\"};\n\nexport { classes as default };\n//# sourceMappingURL=RadioIndicator.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport { getSize, getRadius } from '../../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { parseThemeColor } from '../../../core/MantineProvider/color-functions/parse-theme-color/parse-theme-color.mjs';\nimport { getThemeColor } from '../../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport { getContrastColor } from '../../../core/MantineProvider/color-functions/get-contrast-color/get-contrast-color.mjs';\nimport { getAutoContrastValue } from '../../../core/MantineProvider/color-functions/get-auto-contrast-value/get-auto-contrast-value.mjs';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useRadioCardContext } from '../RadioCard/RadioCard.context.mjs';\nimport { RadioIcon } from '../RadioIcon.mjs';\nimport classes from './RadioIndicator.module.css.mjs';\n\nconst defaultProps = {\n icon: RadioIcon\n};\nconst varsResolver = createVarsResolver(\n (theme, { radius, color, size, iconColor, variant, autoContrast }) => {\n const parsedColor = parseThemeColor({ color: color || theme.primaryColor, theme });\n const outlineColor = parsedColor.isThemeColor && parsedColor.shade === void 0 ? `var(--mantine-color-${parsedColor.color}-outline)` : parsedColor.color;\n return {\n indicator: {\n \"--radio-size\": getSize(size, \"radio-size\"),\n \"--radio-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--radio-color\": variant === \"outline\" ? outlineColor : getThemeColor(color, theme),\n \"--radio-icon-size\": getSize(size, \"radio-icon-size\"),\n \"--radio-icon-color\": iconColor ? getThemeColor(iconColor, theme) : getAutoContrastValue(autoContrast, theme) ? getContrastColor({ color, theme, autoContrast }) : void 0\n }\n };\n }\n);\nconst RadioIndicator = factory((_props, ref) => {\n const props = useProps(\"RadioIndicator\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n icon,\n radius,\n color,\n iconColor,\n autoContrast,\n checked,\n mod,\n variant,\n disabled,\n ...others\n } = props;\n const Icon = icon;\n const getStyles = useStyles({\n name: \"RadioIndicator\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver,\n rootSelector: \"indicator\"\n });\n const ctx = useRadioCardContext();\n const _checked = typeof checked === \"boolean\" ? checked : ctx?.checked || false;\n return /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n ...getStyles(\"indicator\", { variant }),\n variant,\n mod: [{ checked: _checked, disabled }, mod],\n ...others,\n children: /* @__PURE__ */ jsx(Icon, { ...getStyles(\"icon\") })\n }\n );\n});\nRadioIndicator.displayName = \"@mantine/core/RadioIndicator\";\nRadioIndicator.classes = classes;\n\nexport { RadioIndicator };\n//# sourceMappingURL=RadioIndicator.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_f3f1af94\",\"inner\":\"m_89c4f5e4\",\"icon\":\"m_f3ed6b2b\",\"radio\":\"m_8a3dbb89\",\"radio--outline\":\"m_1bfe9d39\"};\n\nexport { classes as default };\n//# sourceMappingURL=Radio.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { useId } from '@mantine/hooks';\nimport 'react';\nimport { getSize, getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { parseThemeColor } from '../../core/MantineProvider/color-functions/parse-theme-color/parse-theme-color.mjs';\nimport { getThemeColor } from '../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport { getContrastColor } from '../../core/MantineProvider/color-functions/get-contrast-color/get-contrast-color.mjs';\nimport { getAutoContrastValue } from '../../core/MantineProvider/color-functions/get-auto-contrast-value/get-auto-contrast-value.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { extractStyleProps } from '../../core/Box/style-props/extract-style-props/extract-style-props.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { InlineInput } from '../InlineInput/InlineInput.mjs';\nimport { RadioCard } from './RadioCard/RadioCard.mjs';\nimport { useRadioGroupContext } from './RadioGroup.context.mjs';\nimport { RadioGroup } from './RadioGroup/RadioGroup.mjs';\nimport { RadioIcon } from './RadioIcon.mjs';\nimport { RadioIndicator } from './RadioIndicator/RadioIndicator.mjs';\nimport classes from './Radio.module.css.mjs';\n\nconst defaultProps = {\n labelPosition: \"right\"\n};\nconst varsResolver = createVarsResolver(\n (theme, { size, radius, color, iconColor, variant, autoContrast }) => {\n const parsedColor = parseThemeColor({ color: color || theme.primaryColor, theme });\n const outlineColor = parsedColor.isThemeColor && parsedColor.shade === void 0 ? `var(--mantine-color-${parsedColor.color}-outline)` : parsedColor.color;\n return {\n root: {\n \"--radio-size\": getSize(size, \"radio-size\"),\n \"--radio-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--radio-color\": variant === \"outline\" ? outlineColor : getThemeColor(color, theme),\n \"--radio-icon-color\": iconColor ? getThemeColor(iconColor, theme) : getAutoContrastValue(autoContrast, theme) ? getContrastColor({ color, theme, autoContrast }) : void 0,\n \"--radio-icon-size\": getSize(size, \"radio-icon-size\")\n }\n };\n }\n);\nconst Radio = factory((_props, ref) => {\n const props = useProps(\"Radio\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n id,\n size,\n label,\n labelPosition,\n description,\n error,\n radius,\n color,\n variant,\n disabled,\n wrapperProps,\n icon: Icon = RadioIcon,\n rootRef,\n iconColor,\n onChange,\n mod,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Radio\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const ctx = useRadioGroupContext();\n const contextSize = ctx?.size ?? size;\n const componentSize = props.size ? size : contextSize;\n const { styleProps, rest } = extractStyleProps(others);\n const uuid = useId(id);\n const contextProps = ctx ? {\n checked: ctx.value === rest.value,\n name: rest.name ?? ctx.name,\n onChange: (event) => {\n ctx.onChange(event);\n onChange?.(event);\n }\n } : {};\n return /* @__PURE__ */ jsx(\n InlineInput,\n {\n ...getStyles(\"root\"),\n __staticSelector: \"Radio\",\n __stylesApiProps: props,\n id: uuid,\n size: componentSize,\n labelPosition,\n label,\n description,\n error,\n disabled,\n classNames,\n styles,\n unstyled,\n \"data-checked\": contextProps.checked || void 0,\n variant,\n ref: rootRef,\n mod,\n ...styleProps,\n ...wrapperProps,\n children: /* @__PURE__ */ jsxs(Box, { ...getStyles(\"inner\"), mod: { \"label-position\": labelPosition }, children: [\n /* @__PURE__ */ jsx(\n Box,\n {\n ...getStyles(\"radio\", { focusable: true, variant }),\n onChange,\n ...rest,\n ...contextProps,\n component: \"input\",\n mod: { error: !!error },\n ref,\n id: uuid,\n disabled,\n type: \"radio\"\n }\n ),\n /* @__PURE__ */ jsx(Icon, { ...getStyles(\"icon\"), \"aria-hidden\": true })\n ] })\n }\n );\n});\nRadio.classes = classes;\nRadio.displayName = \"@mantine/core/Radio\";\nRadio.Group = RadioGroup;\nRadio.Card = RadioCard;\nRadio.Indicator = RadioIndicator;\n\nexport { Radio };\n//# sourceMappingURL=Radio.mjs.map\n","'use client';\nconst defaultTransition = {\n duration: 100,\n transition: \"fade\"\n};\nfunction getTransitionProps(transitionProps, componentTransition) {\n return { ...defaultTransition, ...componentTransition, ...transitionProps };\n}\n\nexport { getTransitionProps };\n//# sourceMappingURL=get-transition-props.mjs.map\n","'use client';\nimport { useState, useRef, useCallback, useEffect } from 'react';\nimport { useFloating, shift, getOverflowAncestors } from '@floating-ui/react';\n\nfunction useFloatingTooltip({\n offset,\n position,\n defaultOpened\n}) {\n const [opened, setOpened] = useState(defaultOpened);\n const boundaryRef = useRef(null);\n const { x, y, elements, refs, update, placement } = useFloating({\n placement: position,\n middleware: [\n shift({\n crossAxis: true,\n padding: 5,\n rootBoundary: \"document\"\n })\n ]\n });\n const horizontalOffset = placement.includes(\"right\") ? offset : position.includes(\"left\") ? offset * -1 : 0;\n const verticalOffset = placement.includes(\"bottom\") ? offset : position.includes(\"top\") ? offset * -1 : 0;\n const handleMouseMove = useCallback(\n ({ clientX, clientY }) => {\n refs.setPositionReference({\n getBoundingClientRect() {\n return {\n width: 0,\n height: 0,\n x: clientX,\n y: clientY,\n left: clientX + horizontalOffset,\n top: clientY + verticalOffset,\n right: clientX,\n bottom: clientY\n };\n }\n });\n },\n [elements.reference]\n );\n useEffect(() => {\n if (refs.floating.current) {\n const boundary = boundaryRef.current;\n boundary.addEventListener(\"mousemove\", handleMouseMove);\n const parents = getOverflowAncestors(refs.floating.current);\n parents.forEach((parent) => {\n parent.addEventListener(\"scroll\", update);\n });\n return () => {\n boundary.removeEventListener(\"mousemove\", handleMouseMove);\n parents.forEach((parent) => {\n parent.removeEventListener(\"scroll\", update);\n });\n };\n }\n return void 0;\n }, [elements.reference, refs.floating.current, update, handleMouseMove, opened]);\n return { handleMouseMove, x, y, opened, setOpened, boundaryRef, floating: refs.setFloating };\n}\n\nexport { useFloatingTooltip };\n//# sourceMappingURL=use-floating-tooltip.mjs.map\n","'use client';\nvar classes = {\"tooltip\":\"m_1b3c8819\",\"arrow\":\"m_f898399f\"};\n\nexport { classes as default };\n//# sourceMappingURL=Tooltip.module.css.mjs.map\n","'use client';\nimport { jsxs, Fragment, jsx } from 'react/jsx-runtime';\nimport { cloneElement } from 'react';\nimport { useMergedRef } from '@mantine/hooks';\nimport { isElement } from '../../../core/utils/is-element/is-element.mjs';\nimport { getDefaultZIndex } from '../../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport { getRadius } from '../../../core/utils/get-size/get-size.mjs';\nimport { getRefProp } from '../../../core/utils/get-ref-prop/get-ref-prop.mjs';\nimport { createVarsResolver } from '../../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { getThemeColor } from '../../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../../core/styles-api/use-styles/use-styles.mjs';\nimport { getStyleObject } from '../../../core/Box/get-style-object/get-style-object.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport '../../Portal/Portal.mjs';\nimport { OptionalPortal } from '../../Portal/OptionalPortal.mjs';\nimport { useFloatingTooltip } from './use-floating-tooltip.mjs';\nimport classes from '../Tooltip.module.css.mjs';\n\nconst defaultProps = {\n refProp: \"ref\",\n withinPortal: true,\n offset: 10,\n defaultOpened: false,\n position: \"right\",\n zIndex: getDefaultZIndex(\"popover\")\n};\nconst varsResolver = createVarsResolver((theme, { radius, color }) => ({\n tooltip: {\n \"--tooltip-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--tooltip-bg\": color ? getThemeColor(color, theme) : void 0,\n \"--tooltip-color\": color ? \"var(--mantine-color-white)\" : void 0\n }\n}));\nconst TooltipFloating = factory((_props, ref) => {\n const props = useProps(\"TooltipFloating\", defaultProps, _props);\n const {\n children,\n refProp,\n withinPortal,\n style,\n className,\n classNames,\n styles,\n unstyled,\n radius,\n color,\n label,\n offset,\n position,\n multiline,\n zIndex,\n disabled,\n defaultOpened,\n variant,\n vars,\n portalProps,\n ...others\n } = props;\n const theme = useMantineTheme();\n const getStyles = useStyles({\n name: \"TooltipFloating\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n rootSelector: \"tooltip\",\n vars,\n varsResolver\n });\n const { handleMouseMove, x, y, opened, boundaryRef, floating, setOpened } = useFloatingTooltip({\n offset,\n position,\n defaultOpened\n });\n if (!isElement(children)) {\n throw new Error(\n \"[@mantine/core] Tooltip.Floating component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported\"\n );\n }\n const targetRef = useMergedRef(boundaryRef, getRefProp(children), ref);\n const _childrenProps = children.props;\n const onMouseEnter = (event) => {\n _childrenProps.onMouseEnter?.(event);\n handleMouseMove(event);\n setOpened(true);\n };\n const onMouseLeave = (event) => {\n _childrenProps.onMouseLeave?.(event);\n setOpened(false);\n };\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsx(OptionalPortal, { ...portalProps, withinPortal, children: /* @__PURE__ */ jsx(\n Box,\n {\n ...others,\n ...getStyles(\"tooltip\", {\n style: {\n ...getStyleObject(style, theme),\n zIndex,\n display: !disabled && opened ? \"block\" : \"none\",\n top: (y && Math.round(y)) ?? \"\",\n left: (x && Math.round(x)) ?? \"\"\n }\n }),\n variant,\n ref: floating,\n mod: { multiline },\n children: label\n }\n ) }),\n cloneElement(children, {\n ..._childrenProps,\n [refProp]: targetRef,\n onMouseEnter,\n onMouseLeave\n })\n ] });\n});\nTooltipFloating.classes = classes;\nTooltipFloating.displayName = \"@mantine/core/TooltipFloating\";\n\nexport { TooltipFloating };\n//# sourceMappingURL=TooltipFloating.mjs.map\n","'use client';\nimport { createContext, useContext } from 'react';\n\nconst TooltipGroupContext = createContext(false);\nconst TooltipGroupProvider = TooltipGroupContext.Provider;\nconst useTooltipGroupContext = () => useContext(TooltipGroupContext);\n\nexport { TooltipGroupProvider, useTooltipGroupContext };\n//# sourceMappingURL=TooltipGroup.context.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { FloatingDelayGroup } from '@floating-ui/react';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { TooltipGroupProvider } from './TooltipGroup.context.mjs';\n\nconst defaultProps = {\n openDelay: 0,\n closeDelay: 0\n};\nfunction TooltipGroup(props) {\n const { openDelay, closeDelay, children } = useProps(\"TooltipGroup\", defaultProps, props);\n return /* @__PURE__ */ jsx(TooltipGroupProvider, { value: true, children: /* @__PURE__ */ jsx(FloatingDelayGroup, { delay: { open: openDelay, close: closeDelay }, children }) });\n}\nTooltipGroup.displayName = \"@mantine/core/TooltipGroup\";\nTooltipGroup.extend = (c) => c;\n\nexport { TooltipGroup };\n//# sourceMappingURL=TooltipGroup.mjs.map\n","'use client';\nimport { useState, useCallback } from 'react';\nimport { useFloating, useDelayGroup, useInteractions, useHover, useFocus, useRole, useDismiss, offset, shift, flip, arrow, inline } from '@floating-ui/react';\nimport { useId, useDidUpdate } from '@mantine/hooks';\nimport { useFloatingAutoUpdate } from '../Floating/use-floating-auto-update.mjs';\nimport '../Floating/FloatingArrow/FloatingArrow.mjs';\nimport { useTooltipGroupContext } from './TooltipGroup/TooltipGroup.context.mjs';\n\nfunction getDefaultMiddlewares(middlewares) {\n if (middlewares === void 0) {\n return { shift: true, flip: true };\n }\n const result = { ...middlewares };\n if (middlewares.shift === void 0) {\n result.shift = true;\n }\n if (middlewares.flip === void 0) {\n result.flip = true;\n }\n return result;\n}\nfunction getTooltipMiddlewares(settings) {\n const middlewaresOptions = getDefaultMiddlewares(settings.middlewares);\n const middlewares = [offset(settings.offset)];\n if (middlewaresOptions.shift) {\n middlewares.push(\n shift(\n typeof middlewaresOptions.shift === \"boolean\" ? { padding: 8 } : { padding: 8, ...middlewaresOptions.shift }\n )\n );\n }\n if (middlewaresOptions.flip) {\n middlewares.push(\n typeof middlewaresOptions.flip === \"boolean\" ? flip() : flip(middlewaresOptions.flip)\n );\n }\n middlewares.push(arrow({ element: settings.arrowRef, padding: settings.arrowOffset }));\n if (middlewaresOptions.inline) {\n middlewares.push(\n typeof middlewaresOptions.inline === \"boolean\" ? inline() : inline(middlewaresOptions.inline)\n );\n } else if (settings.inline) {\n middlewares.push(inline());\n }\n return middlewares;\n}\nfunction useTooltip(settings) {\n const [uncontrolledOpened, setUncontrolledOpened] = useState(settings.defaultOpened);\n const controlled = typeof settings.opened === \"boolean\";\n const opened = controlled ? settings.opened : uncontrolledOpened;\n const withinGroup = useTooltipGroupContext();\n const uid = useId();\n const onChange = useCallback(\n (_opened) => {\n setUncontrolledOpened(_opened);\n if (_opened) {\n setCurrentId(uid);\n }\n },\n [uid]\n );\n const {\n x,\n y,\n context,\n refs,\n update,\n placement,\n middlewareData: { arrow: { x: arrowX, y: arrowY } = {} }\n } = useFloating({\n strategy: settings.strategy,\n placement: settings.position,\n open: opened,\n onOpenChange: onChange,\n middleware: getTooltipMiddlewares(settings)\n });\n const { delay: groupDelay, currentId, setCurrentId } = useDelayGroup(context, { id: uid });\n const { getReferenceProps, getFloatingProps } = useInteractions([\n useHover(context, {\n enabled: settings.events?.hover,\n delay: withinGroup ? groupDelay : { open: settings.openDelay, close: settings.closeDelay },\n mouseOnly: !settings.events?.touch\n }),\n useFocus(context, { enabled: settings.events?.focus, visibleOnly: true }),\n useRole(context, { role: \"tooltip\" }),\n // Cannot be used with controlled tooltip, page jumps\n useDismiss(context, { enabled: typeof settings.opened === \"undefined\" })\n ]);\n useFloatingAutoUpdate({\n opened,\n position: settings.position,\n positionDependencies: settings.positionDependencies,\n floating: { refs, update }\n });\n useDidUpdate(() => {\n settings.onPositionChange?.(placement);\n }, [placement]);\n const isGroupPhase = opened && currentId && currentId !== uid;\n return {\n x,\n y,\n arrowX,\n arrowY,\n reference: refs.setReference,\n floating: refs.setFloating,\n getFloatingProps,\n getReferenceProps,\n isGroupPhase,\n opened,\n placement\n };\n}\n\nexport { useTooltip };\n//# sourceMappingURL=use-tooltip.mjs.map\n","'use client';\nimport { jsxs, Fragment, jsx } from 'react/jsx-runtime';\nimport { useRef, cloneElement } from 'react';\nimport cx from 'clsx';\nimport { useMergedRef } from '@mantine/hooks';\nimport { isElement } from '../../core/utils/is-element/is-element.mjs';\nimport { getDefaultZIndex } from '../../core/utils/get-default-z-index/get-default-z-index.mjs';\nimport { getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport { getRefProp } from '../../core/utils/get-ref-prop/get-ref-prop.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport { getThemeColor } from '../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport { useDirection } from '../../core/DirectionProvider/DirectionProvider.mjs';\nimport '@floating-ui/react';\nimport { getFloatingPosition } from '../Floating/get-floating-position/get-floating-position.mjs';\nimport { FloatingArrow } from '../Floating/FloatingArrow/FloatingArrow.mjs';\nimport '../Portal/Portal.mjs';\nimport { OptionalPortal } from '../Portal/OptionalPortal.mjs';\nimport { Transition } from '../Transition/Transition.mjs';\nimport { getTransitionProps } from '../Transition/get-transition-props/get-transition-props.mjs';\nimport { TooltipFloating } from './TooltipFloating/TooltipFloating.mjs';\nimport { TooltipGroup } from './TooltipGroup/TooltipGroup.mjs';\nimport { useTooltip } from './use-tooltip.mjs';\nimport classes from './Tooltip.module.css.mjs';\n\nconst defaultProps = {\n position: \"top\",\n refProp: \"ref\",\n withinPortal: true,\n inline: false,\n defaultOpened: false,\n arrowSize: 4,\n arrowOffset: 5,\n arrowRadius: 0,\n arrowPosition: \"side\",\n offset: 5,\n transitionProps: { duration: 100, transition: \"fade\" },\n events: { hover: true, focus: false, touch: false },\n zIndex: getDefaultZIndex(\"popover\"),\n positionDependencies: [],\n middlewares: { flip: true, shift: true, inline: false }\n};\nconst varsResolver = createVarsResolver((theme, { radius, color }) => ({\n tooltip: {\n \"--tooltip-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--tooltip-bg\": color ? getThemeColor(color, theme) : void 0,\n \"--tooltip-color\": color ? \"var(--mantine-color-white)\" : void 0\n }\n}));\nconst Tooltip = factory((_props, ref) => {\n const props = useProps(\"Tooltip\", defaultProps, _props);\n const {\n children,\n position,\n refProp,\n label,\n openDelay,\n closeDelay,\n onPositionChange,\n opened,\n defaultOpened,\n withinPortal,\n radius,\n color,\n classNames,\n styles,\n unstyled,\n style,\n className,\n withArrow,\n arrowSize,\n arrowOffset,\n arrowRadius,\n arrowPosition,\n offset,\n transitionProps,\n multiline,\n events,\n zIndex,\n disabled,\n positionDependencies,\n onClick,\n onMouseEnter,\n onMouseLeave,\n inline,\n variant,\n keepMounted,\n vars,\n portalProps,\n mod,\n floatingStrategy,\n middlewares,\n ...others\n } = useProps(\"Tooltip\", defaultProps, props);\n const { dir } = useDirection();\n const arrowRef = useRef(null);\n const tooltip = useTooltip({\n position: getFloatingPosition(dir, position),\n closeDelay,\n openDelay,\n onPositionChange,\n opened,\n defaultOpened,\n events,\n arrowRef,\n arrowOffset,\n offset: typeof offset === \"number\" ? offset + (withArrow ? arrowSize / 2 : 0) : offset,\n positionDependencies: [...positionDependencies, children],\n inline,\n strategy: floatingStrategy,\n middlewares\n });\n const getStyles = useStyles({\n name: \"Tooltip\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n rootSelector: \"tooltip\",\n vars,\n varsResolver\n });\n if (!isElement(children)) {\n throw new Error(\n \"[@mantine/core] Tooltip component children should be an element or a component that accepts ref, fragments, strings, numbers and other primitive values are not supported\"\n );\n }\n const targetRef = useMergedRef(tooltip.reference, getRefProp(children), ref);\n const transition = getTransitionProps(transitionProps, { duration: 100, transition: \"fade\" });\n const _childrenProps = children.props;\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsx(OptionalPortal, { ...portalProps, withinPortal, children: /* @__PURE__ */ jsx(\n Transition,\n {\n ...transition,\n keepMounted,\n mounted: !disabled && !!tooltip.opened,\n duration: tooltip.isGroupPhase ? 10 : transition.duration,\n children: (transitionStyles) => /* @__PURE__ */ jsxs(\n Box,\n {\n ...others,\n \"data-fixed\": floatingStrategy === \"fixed\" || void 0,\n variant,\n mod: [{ multiline }, mod],\n ...tooltip.getFloatingProps({\n ref: tooltip.floating,\n className: getStyles(\"tooltip\").className,\n style: {\n ...getStyles(\"tooltip\").style,\n ...transitionStyles,\n zIndex,\n top: tooltip.y ?? 0,\n left: tooltip.x ?? 0\n }\n }),\n children: [\n label,\n /* @__PURE__ */ jsx(\n FloatingArrow,\n {\n ref: arrowRef,\n arrowX: tooltip.arrowX,\n arrowY: tooltip.arrowY,\n visible: withArrow,\n position: tooltip.placement,\n arrowSize,\n arrowOffset,\n arrowRadius,\n arrowPosition,\n ...getStyles(\"arrow\")\n }\n )\n ]\n }\n )\n }\n ) }),\n cloneElement(\n children,\n tooltip.getReferenceProps({\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove: props.onMouseMove,\n onPointerDown: props.onPointerDown,\n onPointerEnter: props.onPointerEnter,\n [refProp]: targetRef,\n className: cx(className, _childrenProps.className),\n ..._childrenProps\n })\n )\n ] });\n});\nTooltip.classes = classes;\nTooltip.displayName = \"@mantine/core/Tooltip\";\nTooltip.Floating = TooltipFloating;\nTooltip.Group = TooltipGroup;\n\nexport { Tooltip };\n//# sourceMappingURL=Tooltip.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_cf365364\",\"indicator\":\"m_9e182ccd\",\"label\":\"m_1738fcb2\",\"input\":\"m_1714d588\",\"control\":\"m_69686b9b\",\"innerLabel\":\"m_78882f40\"};\n\nexport { classes as default };\n//# sourceMappingURL=SegmentedControl.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { useState, createElement } from 'react';\nimport { useMounted, useUncontrolled, useId, useMergedRef } from '@mantine/hooks';\nimport { getRadius, getSize, getFontSize } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { getThemeColor } from '../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport { getContrastColor } from '../../core/MantineProvider/color-functions/get-contrast-color/get-contrast-color.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { FloatingIndicator } from '../FloatingIndicator/FloatingIndicator.mjs';\nimport classes from './SegmentedControl.module.css.mjs';\n\nconst defaultProps = {\n withItemsBorders: true\n};\nconst varsResolver = createVarsResolver(\n (theme, { radius, color, transitionDuration, size, transitionTimingFunction }) => ({\n root: {\n \"--sc-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--sc-color\": color ? getThemeColor(color, theme) : void 0,\n \"--sc-shadow\": color ? void 0 : \"var(--mantine-shadow-xs)\",\n \"--sc-transition-duration\": transitionDuration === void 0 ? void 0 : `${transitionDuration}ms`,\n \"--sc-transition-timing-function\": transitionTimingFunction,\n \"--sc-padding\": getSize(size, \"sc-padding\"),\n \"--sc-font-size\": getFontSize(size)\n }\n })\n);\nconst SegmentedControl = factory((_props, ref) => {\n const props = useProps(\"SegmentedControl\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n data,\n value,\n defaultValue,\n onChange,\n size,\n name,\n disabled,\n readOnly,\n fullWidth,\n orientation,\n radius,\n color,\n transitionDuration,\n transitionTimingFunction,\n variant,\n autoContrast,\n withItemsBorders,\n mod,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"SegmentedControl\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const theme = useMantineTheme();\n const _data = data.map(\n (item) => typeof item === \"string\" ? { label: item, value: item } : item\n );\n const initialized = useMounted();\n const [parent, setParent] = useState(null);\n const [refs, setRefs] = useState({});\n const setElementRef = (element, val) => {\n refs[val] = element;\n setRefs(refs);\n };\n const [_value, handleValueChange] = useUncontrolled({\n value,\n defaultValue,\n finalValue: Array.isArray(data) ? _data.find((item) => !item.disabled)?.value ?? data[0]?.value ?? null : null,\n onChange\n });\n const uuid = useId(name);\n const controls = _data.map((item) => /* @__PURE__ */ createElement(\n Box,\n {\n ...getStyles(\"control\"),\n mod: { active: _value === item.value, orientation },\n key: item.value\n },\n /* @__PURE__ */ createElement(\n \"input\",\n {\n ...getStyles(\"input\"),\n disabled: disabled || item.disabled,\n type: \"radio\",\n name: uuid,\n value: item.value,\n id: `${uuid}-${item.value}`,\n checked: _value === item.value,\n onChange: () => !readOnly && handleValueChange(item.value),\n \"data-focus-ring\": theme.focusRing,\n key: `${item.value}-input`\n }\n ),\n /* @__PURE__ */ createElement(\n Box,\n {\n component: \"label\",\n ...getStyles(\"label\"),\n mod: {\n active: _value === item.value && !(disabled || item.disabled),\n disabled: disabled || item.disabled,\n \"read-only\": readOnly\n },\n htmlFor: `${uuid}-${item.value}`,\n ref: (node) => setElementRef(node, item.value),\n __vars: {\n \"--sc-label-color\": color !== void 0 ? getContrastColor({ color, theme, autoContrast }) : void 0\n },\n key: `${item.value}-label`\n },\n /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"innerLabel\"), children: item.label })\n )\n ));\n const mergedRef = useMergedRef(ref, (node) => setParent(node));\n if (data.length === 0) {\n return null;\n }\n return /* @__PURE__ */ jsxs(\n Box,\n {\n ...getStyles(\"root\"),\n variant,\n size,\n ref: mergedRef,\n mod: [\n {\n \"full-width\": fullWidth,\n orientation,\n initialized,\n \"with-items-borders\": withItemsBorders\n },\n mod\n ],\n ...others,\n role: \"radiogroup\",\n \"data-disabled\": disabled,\n children: [\n typeof _value === \"string\" && /* @__PURE__ */ jsx(\n FloatingIndicator,\n {\n target: refs[_value],\n parent,\n component: \"span\",\n transitionDuration: \"var(--sc-transition-duration)\",\n ...getStyles(\"indicator\")\n }\n ),\n controls\n ]\n }\n );\n});\nSegmentedControl.classes = classes;\nSegmentedControl.displayName = \"@mantine/core/SegmentedControl\";\n\nexport { SegmentedControl };\n//# sourceMappingURL=SegmentedControl.mjs.map\n","'use client';\nimport { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { useMemo, useEffect } from 'react';\nimport { useId, useUncontrolled, usePrevious } from '@mantine/hooks';\nimport 'clsx';\nimport { useResolvedStylesApi } from '../../core/styles-api/use-resolved-styles-api/use-resolved-styles-api.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { getParsedComboboxData } from '../Combobox/get-parsed-combobox-data/get-parsed-combobox-data.mjs';\nimport { getOptionsLockup } from '../Combobox/get-options-lockup/get-options-lockup.mjs';\nimport '../Combobox/ComboboxChevron/ComboboxChevron.mjs';\nimport { Combobox } from '../Combobox/Combobox.mjs';\nimport '../Combobox/ComboboxDropdown/ComboboxDropdown.mjs';\nimport '../Combobox/ComboboxOptions/ComboboxOptions.mjs';\nimport '../Combobox/ComboboxOption/ComboboxOption.mjs';\nimport '../Combobox/ComboboxTarget/ComboboxTarget.mjs';\nimport '../Combobox/ComboboxSearch/ComboboxSearch.mjs';\nimport '../Combobox/ComboboxEmpty/ComboboxEmpty.mjs';\nimport '../Combobox/ComboboxFooter/ComboboxFooter.mjs';\nimport '../Combobox/ComboboxHeader/ComboboxHeader.mjs';\nimport '../Combobox/ComboboxEventsTarget/ComboboxEventsTarget.mjs';\nimport '../Combobox/ComboboxDropdownTarget/ComboboxDropdownTarget.mjs';\nimport '../Combobox/ComboboxGroup/ComboboxGroup.mjs';\nimport '../Combobox/ComboboxClearButton/ComboboxClearButton.mjs';\nimport '../Combobox/ComboboxHiddenInput/ComboboxHiddenInput.mjs';\nimport { OptionsDropdown } from '../Combobox/OptionsDropdown/OptionsDropdown.mjs';\nimport { useCombobox } from '../Combobox/use-combobox/use-combobox.mjs';\nimport '../Combobox/Combobox.context.mjs';\nimport { InputBase } from '../InputBase/InputBase.mjs';\n\nconst defaultProps = {\n searchable: false,\n withCheckIcon: true,\n allowDeselect: true,\n checkIconPosition: \"left\"\n};\nconst Select = factory((_props, ref) => {\n const props = useProps(\"Select\", defaultProps, _props);\n const {\n classNames,\n styles,\n unstyled,\n vars,\n dropdownOpened,\n defaultDropdownOpened,\n onDropdownClose,\n onDropdownOpen,\n onFocus,\n onBlur,\n onClick,\n onChange,\n data,\n value,\n defaultValue,\n selectFirstOptionOnChange,\n onOptionSubmit,\n comboboxProps,\n readOnly,\n disabled,\n filter,\n limit,\n withScrollArea,\n maxDropdownHeight,\n size,\n searchable,\n rightSection,\n checkIconPosition,\n withCheckIcon,\n nothingFoundMessage,\n name,\n form,\n searchValue,\n defaultSearchValue,\n onSearchChange,\n allowDeselect,\n error,\n rightSectionPointerEvents,\n id,\n clearable,\n clearButtonProps,\n hiddenInputProps,\n renderOption,\n onClear,\n autoComplete,\n scrollAreaProps,\n __defaultRightSection,\n __clearSection,\n __clearable,\n chevronColor,\n ...others\n } = props;\n const parsedData = useMemo(() => getParsedComboboxData(data), [data]);\n const optionsLockup = useMemo(() => getOptionsLockup(parsedData), [parsedData]);\n const _id = useId(id);\n const [_value, setValue, controlled] = useUncontrolled({\n value,\n defaultValue,\n finalValue: null,\n onChange\n });\n const selectedOption = typeof _value === \"string\" ? optionsLockup[_value] : void 0;\n const previousSelectedOption = usePrevious(selectedOption);\n const [search, setSearch] = useUncontrolled({\n value: searchValue,\n defaultValue: defaultSearchValue,\n finalValue: selectedOption ? selectedOption.label : \"\",\n onChange: onSearchChange\n });\n const combobox = useCombobox({\n opened: dropdownOpened,\n defaultOpened: defaultDropdownOpened,\n onDropdownOpen: () => {\n onDropdownOpen?.();\n combobox.updateSelectedOptionIndex(\"active\", { scrollIntoView: true });\n },\n onDropdownClose: () => {\n onDropdownClose?.();\n combobox.resetSelectedOption();\n }\n });\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n props,\n styles,\n classNames\n });\n useEffect(() => {\n if (selectFirstOptionOnChange) {\n combobox.selectFirstOption();\n }\n }, [selectFirstOptionOnChange, _value]);\n useEffect(() => {\n if (value === null) {\n setSearch(\"\");\n }\n if (typeof value === \"string\" && selectedOption && (previousSelectedOption?.value !== selectedOption.value || previousSelectedOption?.label !== selectedOption.label)) {\n setSearch(selectedOption.label);\n }\n }, [value, selectedOption]);\n const clearButton = /* @__PURE__ */ jsx(\n Combobox.ClearButton,\n {\n ...clearButtonProps,\n onClear: () => {\n setValue(null, null);\n setSearch(\"\");\n onClear?.();\n }\n }\n );\n const _clearable = clearable && !!_value && !disabled && !readOnly;\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsxs(\n Combobox,\n {\n store: combobox,\n __staticSelector: \"Select\",\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n readOnly,\n onOptionSubmit: (val) => {\n onOptionSubmit?.(val);\n const optionLockup = allowDeselect ? optionsLockup[val].value === _value ? null : optionsLockup[val] : optionsLockup[val];\n const nextValue = optionLockup ? optionLockup.value : null;\n nextValue !== _value && setValue(nextValue, optionLockup);\n !controlled && setSearch(typeof nextValue === \"string\" ? optionLockup?.label || \"\" : \"\");\n combobox.closeDropdown();\n },\n size,\n ...comboboxProps,\n children: [\n /* @__PURE__ */ jsx(Combobox.Target, { targetType: searchable ? \"input\" : \"button\", autoComplete, children: /* @__PURE__ */ jsx(\n InputBase,\n {\n id: _id,\n ref,\n __defaultRightSection: /* @__PURE__ */ jsx(\n Combobox.Chevron,\n {\n size,\n error,\n unstyled,\n color: chevronColor\n }\n ),\n __clearSection: clearButton,\n __clearable: _clearable,\n rightSection,\n rightSectionPointerEvents: rightSectionPointerEvents || (_clearable ? \"all\" : \"none\"),\n ...others,\n size,\n __staticSelector: \"Select\",\n disabled,\n readOnly: readOnly || !searchable,\n value: search,\n onChange: (event) => {\n setSearch(event.currentTarget.value);\n combobox.openDropdown();\n selectFirstOptionOnChange && combobox.selectFirstOption();\n },\n onFocus: (event) => {\n searchable && combobox.openDropdown();\n onFocus?.(event);\n },\n onBlur: (event) => {\n searchable && combobox.closeDropdown();\n setSearch(_value != null ? optionsLockup[_value]?.label || \"\" : \"\");\n onBlur?.(event);\n },\n onClick: (event) => {\n searchable ? combobox.openDropdown() : combobox.toggleDropdown();\n onClick?.(event);\n },\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n pointer: !searchable,\n error\n }\n ) }),\n /* @__PURE__ */ jsx(\n OptionsDropdown,\n {\n data: parsedData,\n hidden: readOnly || disabled,\n filter,\n search,\n limit,\n hiddenWhenEmpty: !nothingFoundMessage,\n withScrollArea,\n maxDropdownHeight,\n filterOptions: searchable && selectedOption?.label !== search,\n value: _value,\n checkIconPosition,\n withCheckIcon,\n nothingFoundMessage,\n unstyled,\n labelId: others.label ? `${_id}-label` : void 0,\n \"aria-label\": others.label ? void 0 : others[\"aria-label\"],\n renderOption,\n scrollAreaProps\n }\n )\n ]\n }\n ),\n /* @__PURE__ */ jsx(\n Combobox.HiddenInput,\n {\n value: _value,\n name,\n form,\n disabled,\n ...hiddenInputProps\n }\n )\n ] });\n});\nSelect.classes = { ...InputBase.classes, ...Combobox.classes };\nSelect.displayName = \"@mantine/core/Select\";\n\nexport { Select };\n//# sourceMappingURL=Select.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { keys } from '../../core/utils/keys/keys.mjs';\nimport { px } from '../../core/utils/units-converters/px.mjs';\nimport { filterProps } from '../../core/utils/filter-props/filter-props.mjs';\nimport 'react';\nimport { getSpacing } from '../../core/utils/get-size/get-size.mjs';\nimport { getSortedBreakpoints } from '../../core/utils/get-sorted-breakpoints/get-sorted-breakpoints.mjs';\nimport { getBaseValue } from '../../core/utils/get-base-value/get-base-value.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { InlineStyles } from '../../core/InlineStyles/InlineStyles.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nfunction SimpleGridMediaVariables({\n spacing,\n verticalSpacing,\n cols,\n selector\n}) {\n const theme = useMantineTheme();\n const _verticalSpacing = verticalSpacing === void 0 ? spacing : verticalSpacing;\n const baseStyles = filterProps({\n \"--sg-spacing-x\": getSpacing(getBaseValue(spacing)),\n \"--sg-spacing-y\": getSpacing(getBaseValue(_verticalSpacing)),\n \"--sg-cols\": getBaseValue(cols)?.toString()\n });\n const queries = keys(theme.breakpoints).reduce(\n (acc, breakpoint) => {\n if (!acc[breakpoint]) {\n acc[breakpoint] = {};\n }\n if (typeof spacing === \"object\" && spacing[breakpoint] !== void 0) {\n acc[breakpoint][\"--sg-spacing-x\"] = getSpacing(spacing[breakpoint]);\n }\n if (typeof _verticalSpacing === \"object\" && _verticalSpacing[breakpoint] !== void 0) {\n acc[breakpoint][\"--sg-spacing-y\"] = getSpacing(_verticalSpacing[breakpoint]);\n }\n if (typeof cols === \"object\" && cols[breakpoint] !== void 0) {\n acc[breakpoint][\"--sg-cols\"] = cols[breakpoint];\n }\n return acc;\n },\n {}\n );\n const sortedBreakpoints = getSortedBreakpoints(keys(queries), theme.breakpoints).filter(\n (breakpoint) => keys(queries[breakpoint.value]).length > 0\n );\n const media = sortedBreakpoints.map((breakpoint) => ({\n query: `(min-width: ${theme.breakpoints[breakpoint.value]})`,\n styles: queries[breakpoint.value]\n }));\n return /* @__PURE__ */ jsx(InlineStyles, { styles: baseStyles, media, selector });\n}\nfunction getBreakpoints(values) {\n if (typeof values === \"object\" && values !== null) {\n return keys(values);\n }\n return [];\n}\nfunction sortBreakpoints(breakpoints) {\n return breakpoints.sort((a, b) => px(a) - px(b));\n}\nfunction getUniqueBreakpoints({\n spacing,\n verticalSpacing,\n cols\n}) {\n const breakpoints = Array.from(\n /* @__PURE__ */ new Set([\n ...getBreakpoints(spacing),\n ...getBreakpoints(verticalSpacing),\n ...getBreakpoints(cols)\n ])\n );\n return sortBreakpoints(breakpoints);\n}\nfunction SimpleGridContainerVariables({\n spacing,\n verticalSpacing,\n cols,\n selector\n}) {\n const _verticalSpacing = verticalSpacing === void 0 ? spacing : verticalSpacing;\n const baseStyles = filterProps({\n \"--sg-spacing-x\": getSpacing(getBaseValue(spacing)),\n \"--sg-spacing-y\": getSpacing(getBaseValue(_verticalSpacing)),\n \"--sg-cols\": getBaseValue(cols)?.toString()\n });\n const uniqueBreakpoints = getUniqueBreakpoints({ spacing, verticalSpacing, cols });\n const queries = uniqueBreakpoints.reduce(\n (acc, breakpoint) => {\n if (!acc[breakpoint]) {\n acc[breakpoint] = {};\n }\n if (typeof spacing === \"object\" && spacing[breakpoint] !== void 0) {\n acc[breakpoint][\"--sg-spacing-x\"] = getSpacing(spacing[breakpoint]);\n }\n if (typeof _verticalSpacing === \"object\" && _verticalSpacing[breakpoint] !== void 0) {\n acc[breakpoint][\"--sg-spacing-y\"] = getSpacing(_verticalSpacing[breakpoint]);\n }\n if (typeof cols === \"object\" && cols[breakpoint] !== void 0) {\n acc[breakpoint][\"--sg-cols\"] = cols[breakpoint];\n }\n return acc;\n },\n {}\n );\n const media = uniqueBreakpoints.map((breakpoint) => ({\n query: `simple-grid (min-width: ${breakpoint})`,\n styles: queries[breakpoint]\n }));\n return /* @__PURE__ */ jsx(InlineStyles, { styles: baseStyles, container: media, selector });\n}\n\nexport { SimpleGridContainerVariables, SimpleGridMediaVariables };\n//# sourceMappingURL=SimpleGridVariables.mjs.map\n","'use client';\nvar classes = {\"container\":\"m_925c2d2c\",\"root\":\"m_2415a157\"};\n\nexport { classes as default };\n//# sourceMappingURL=SimpleGrid.module.css.mjs.map\n","'use client';\nimport { jsxs, Fragment, jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { useRandomClassName } from '../../core/Box/use-random-classname/use-random-classname.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { SimpleGridContainerVariables, SimpleGridMediaVariables } from './SimpleGridVariables.mjs';\nimport classes from './SimpleGrid.module.css.mjs';\n\nconst defaultProps = {\n cols: 1,\n spacing: \"md\",\n type: \"media\"\n};\nconst SimpleGrid = factory((_props, ref) => {\n const props = useProps(\"SimpleGrid\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n cols,\n verticalSpacing,\n spacing,\n type,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"SimpleGrid\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars\n });\n const responsiveClassName = useRandomClassName();\n if (type === \"container\") {\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsx(SimpleGridContainerVariables, { ...props, selector: `.${responsiveClassName}` }),\n /* @__PURE__ */ jsx(\"div\", { ...getStyles(\"container\"), children: /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\", { className: responsiveClassName }), ...others }) })\n ] });\n }\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n /* @__PURE__ */ jsx(SimpleGridMediaVariables, { ...props, selector: `.${responsiveClassName}` }),\n /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\", { className: responsiveClassName }), ...others })\n ] });\n});\nSimpleGrid.classes = classes;\nSimpleGrid.displayName = \"@mantine/core/SimpleGrid\";\n\nexport { SimpleGrid };\n//# sourceMappingURL=SimpleGrid.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_18320242\",\"skeleton-fade\":\"m_299c329c\"};\n\nexport { classes as default };\n//# sourceMappingURL=Skeleton.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport { getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './Skeleton.module.css.mjs';\n\nconst defaultProps = {\n visible: true,\n animate: true\n};\nconst varsResolver = createVarsResolver(\n (_, { width, height, radius, circle }) => ({\n root: {\n \"--skeleton-height\": rem(height),\n \"--skeleton-width\": circle ? rem(height) : rem(width),\n \"--skeleton-radius\": circle ? \"1000px\" : radius === void 0 ? void 0 : getRadius(radius)\n }\n })\n);\nconst Skeleton = factory((_props, ref) => {\n const props = useProps(\"Skeleton\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n width,\n height,\n circle,\n visible,\n radius,\n animate,\n mod,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Skeleton\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\"), mod: [{ visible, animate }, mod], ...others });\n});\nSkeleton.classes = classes;\nSkeleton.displayName = \"@mantine/core/Skeleton\";\n\nexport { Skeleton };\n//# sourceMappingURL=Skeleton.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_559cce2d\",\"content\":\"m_b912df4e\",\"control\":\"m_b9131032\"};\n\nexport { classes as default };\n//# sourceMappingURL=Spoiler.module.css.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useId, useUncontrolled, useElementSize } from '@mantine/hooks';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Anchor } from '../Anchor/Anchor.mjs';\nimport classes from './Spoiler.module.css.mjs';\n\nconst defaultProps = {\n maxHeight: 100,\n initialState: false\n};\nconst varsResolver = createVarsResolver((_, { transitionDuration }) => ({\n root: {\n \"--spoiler-transition-duration\": transitionDuration !== void 0 ? `${transitionDuration}ms` : void 0\n }\n}));\nconst Spoiler = factory((_props, ref) => {\n const props = useProps(\"Spoiler\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n initialState,\n maxHeight,\n hideLabel,\n showLabel,\n children,\n controlRef,\n transitionDuration,\n id,\n expanded,\n onExpandedChange,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Spoiler\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const _id = useId(id);\n const regionId = `${_id}-region`;\n const [show, setShowState] = useUncontrolled({\n value: expanded,\n defaultValue: initialState,\n finalValue: false,\n onChange: onExpandedChange\n });\n const { ref: contentRef, height } = useElementSize();\n const spoilerMoreContent = show ? hideLabel : showLabel;\n const spoiler = spoilerMoreContent !== null && maxHeight < height;\n return /* @__PURE__ */ jsxs(\n Box,\n {\n ...getStyles(\"root\"),\n id: _id,\n ref,\n \"data-has-spoiler\": spoiler || void 0,\n ...others,\n children: [\n spoiler && /* @__PURE__ */ jsx(\n Anchor,\n {\n component: \"button\",\n type: \"button\",\n ref: controlRef,\n onClick: () => setShowState(!show),\n \"aria-expanded\": show,\n \"aria-controls\": regionId,\n ...getStyles(\"control\"),\n children: spoilerMoreContent\n }\n ),\n /* @__PURE__ */ jsx(\n \"div\",\n {\n ...getStyles(\"content\", {\n style: { maxHeight: !show ? rem(maxHeight) : height ? rem(height) : void 0 }\n }),\n \"data-reduce-motion\": true,\n role: \"region\",\n id: regionId,\n children: /* @__PURE__ */ jsx(\"div\", { ref: contentRef, children })\n }\n )\n ]\n }\n );\n});\nSpoiler.classes = classes;\nSpoiler.displayName = \"@mantine/core/Spoiler\";\n\nexport { Spoiler };\n//# sourceMappingURL=Spoiler.mjs.map\n","'use client';\nimport { createContext, useContext } from 'react';\n\nconst SwitchGroupContext = createContext(null);\nconst SwitchGroupProvider = SwitchGroupContext.Provider;\nconst useSwitchGroupContext = () => useContext(SwitchGroupContext);\n\nexport { SwitchGroupProvider, useSwitchGroupContext };\n//# sourceMappingURL=SwitchGroup.context.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useUncontrolled } from '@mantine/hooks';\nimport 'react';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { Input } from '../../Input/Input.mjs';\nimport '../../Input/InputWrapper/InputWrapper.mjs';\nimport '../../Input/InputDescription/InputDescription.mjs';\nimport '../../Input/InputError/InputError.mjs';\nimport '../../Input/InputLabel/InputLabel.mjs';\nimport '../../Input/InputPlaceholder/InputPlaceholder.mjs';\nimport '../../Input/InputClearButton/InputClearButton.mjs';\nimport '../../Input/InputWrapper.context.mjs';\nimport { InputsGroupFieldset } from '../../InputsGroupFieldset/InputsGroupFieldset.mjs';\nimport { SwitchGroupProvider } from '../SwitchGroup.context.mjs';\n\nconst defaultProps = {};\nconst SwitchGroup = factory((props, ref) => {\n const { value, defaultValue, onChange, size, wrapperProps, children, readOnly, ...others } = useProps(\"SwitchGroup\", defaultProps, props);\n const [_value, setValue] = useUncontrolled({\n value,\n defaultValue,\n finalValue: [],\n onChange\n });\n const handleChange = (event) => {\n const itemValue = event.currentTarget.value;\n !readOnly && setValue(\n _value.includes(itemValue) ? _value.filter((item) => item !== itemValue) : [..._value, itemValue]\n );\n };\n return /* @__PURE__ */ jsx(SwitchGroupProvider, { value: { value: _value, onChange: handleChange, size }, children: /* @__PURE__ */ jsx(\n Input.Wrapper,\n {\n size,\n ref,\n ...wrapperProps,\n ...others,\n labelElement: \"div\",\n __staticSelector: \"SwitchGroup\",\n children: /* @__PURE__ */ jsx(InputsGroupFieldset, { role: \"group\", children })\n }\n ) });\n});\nSwitchGroup.classes = Input.Wrapper.classes;\nSwitchGroup.displayName = \"@mantine/core/SwitchGroup\";\n\nexport { SwitchGroup };\n//# sourceMappingURL=SwitchGroup.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_5f93f3bb\",\"input\":\"m_926b4011\",\"track\":\"m_9307d992\",\"thumb\":\"m_93039a1d\",\"trackLabel\":\"m_8277e082\"};\n\nexport { classes as default };\n//# sourceMappingURL=Switch.module.css.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useId, useUncontrolled } from '@mantine/hooks';\nimport 'react';\nimport { getRadius, getSize } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { getThemeColor } from '../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { extractStyleProps } from '../../core/Box/style-props/extract-style-props/extract-style-props.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { InlineInputClasses, InlineInput } from '../InlineInput/InlineInput.mjs';\nimport { useSwitchGroupContext } from './SwitchGroup.context.mjs';\nimport { SwitchGroup } from './SwitchGroup/SwitchGroup.mjs';\nimport classes from './Switch.module.css.mjs';\n\nconst defaultProps = {\n labelPosition: \"right\"\n};\nconst varsResolver = createVarsResolver((theme, { radius, color, size }) => ({\n root: {\n \"--switch-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--switch-height\": getSize(size, \"switch-height\"),\n \"--switch-width\": getSize(size, \"switch-width\"),\n \"--switch-thumb-size\": getSize(size, \"switch-thumb-size\"),\n \"--switch-label-font-size\": getSize(size, \"switch-label-font-size\"),\n \"--switch-track-label-padding\": getSize(size, \"switch-track-label-padding\"),\n \"--switch-color\": color ? getThemeColor(color, theme) : void 0\n }\n}));\nconst Switch = factory((_props, ref) => {\n const props = useProps(\"Switch\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n color,\n label,\n offLabel,\n onLabel,\n id,\n size,\n radius,\n wrapperProps,\n thumbIcon,\n checked,\n defaultChecked,\n onChange,\n labelPosition,\n description,\n error,\n disabled,\n variant,\n rootRef,\n mod,\n ...others\n } = props;\n const ctx = useSwitchGroupContext();\n const _size = size || ctx?.size;\n const getStyles = useStyles({\n name: \"Switch\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const { styleProps, rest } = extractStyleProps(others);\n const uuid = useId(id);\n const contextProps = ctx ? {\n checked: ctx.value.includes(rest.value),\n onChange: ctx.onChange\n } : {};\n const [_checked, handleChange] = useUncontrolled({\n value: contextProps.checked ?? checked,\n defaultValue: defaultChecked,\n finalValue: false\n });\n return /* @__PURE__ */ jsxs(\n InlineInput,\n {\n ...getStyles(\"root\"),\n __staticSelector: \"Switch\",\n __stylesApiProps: props,\n id: uuid,\n size: _size,\n labelPosition,\n label,\n description,\n error,\n disabled,\n bodyElement: \"label\",\n labelElement: \"span\",\n classNames,\n styles,\n unstyled,\n \"data-checked\": contextProps.checked || checked || void 0,\n variant,\n ref: rootRef,\n mod,\n ...styleProps,\n ...wrapperProps,\n children: [\n /* @__PURE__ */ jsx(\n \"input\",\n {\n ...rest,\n disabled,\n checked: _checked,\n \"data-checked\": contextProps.checked || checked || void 0,\n onChange: (event) => {\n ctx ? contextProps.onChange?.(event) : onChange?.(event);\n handleChange(event.currentTarget.checked);\n },\n id: uuid,\n ref,\n type: \"checkbox\",\n role: \"switch\",\n ...getStyles(\"input\")\n }\n ),\n /* @__PURE__ */ jsxs(\n Box,\n {\n \"aria-hidden\": \"true\",\n mod: { error, \"label-position\": labelPosition, \"without-labels\": !onLabel && !offLabel },\n ...getStyles(\"track\"),\n children: [\n /* @__PURE__ */ jsx(Box, { component: \"span\", mod: \"reduce-motion\", ...getStyles(\"thumb\"), children: thumbIcon }),\n /* @__PURE__ */ jsx(\"span\", { ...getStyles(\"trackLabel\"), children: _checked ? onLabel : offLabel })\n ]\n }\n )\n ]\n }\n );\n});\nSwitch.classes = { ...classes, ...InlineInputClasses };\nSwitch.displayName = \"@mantine/core/Switch\";\nSwitch.Group = SwitchGroup;\n\nexport { Switch };\n//# sourceMappingURL=Switch.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [TableProvider, useTableContext] = createSafeContext(\n \"Table component was not found in the tree\"\n);\n\nexport { TableProvider, useTableContext };\n//# sourceMappingURL=Table.context.mjs.map\n","'use client';\nvar classes = {\"table\":\"m_b23fa0ef\",\"th\":\"m_4e7aa4f3\",\"tr\":\"m_4e7aa4fd\",\"td\":\"m_4e7aa4ef\",\"tbody\":\"m_b2404537\",\"thead\":\"m_b242d975\",\"caption\":\"m_9e5a3ac7\",\"scrollContainer\":\"m_a100c15\",\"scrollContainerInner\":\"m_62259741\"};\n\nexport { classes as default };\n//# sourceMappingURL=Table.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useTableContext } from './Table.context.mjs';\nimport classes from './Table.module.css.mjs';\n\nfunction getDataAttributes(ctx, options) {\n if (!options) {\n return void 0;\n }\n const data = {};\n if (options.columnBorder && ctx.withColumnBorders) {\n data[\"data-with-column-border\"] = true;\n }\n if (options.rowBorder && ctx.withRowBorders) {\n data[\"data-with-row-border\"] = true;\n }\n if (options.striped && ctx.striped) {\n data[\"data-striped\"] = ctx.striped;\n }\n if (options.highlightOnHover && ctx.highlightOnHover) {\n data[\"data-hover\"] = true;\n }\n if (options.captionSide && ctx.captionSide) {\n data[\"data-side\"] = ctx.captionSide;\n }\n if (options.stickyHeader && ctx.stickyHeader) {\n data[\"data-sticky\"] = true;\n }\n return data;\n}\nfunction tableElement(element, options) {\n const name = `Table${element.charAt(0).toUpperCase()}${element.slice(1)}`;\n const Component = factory((_props, ref) => {\n const props = useProps(name, {}, _props);\n const { classNames, className, style, styles, ...others } = props;\n const ctx = useTableContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n component: element,\n ref,\n ...getDataAttributes(ctx, options),\n ...ctx.getStyles(element, { className, classNames, style, styles, props }),\n ...others\n }\n );\n });\n Component.displayName = `@mantine/core/${name}`;\n Component.classes = classes;\n return Component;\n}\nconst TableTh = tableElement(\"th\", { columnBorder: true });\nconst TableTd = tableElement(\"td\", { columnBorder: true });\nconst TableTr = tableElement(\"tr\", {\n rowBorder: true,\n striped: true,\n highlightOnHover: true\n});\nconst TableThead = tableElement(\"thead\", { stickyHeader: true });\nconst TableTbody = tableElement(\"tbody\");\nconst TableTfoot = tableElement(\"tfoot\");\nconst TableCaption = tableElement(\"caption\", { captionSide: true });\n\nexport { TableCaption, TableTbody, TableTd, TableTfoot, TableTh, TableThead, TableTr, tableElement };\n//# sourceMappingURL=Table.components.mjs.map\n","'use client';\nimport { jsxs, Fragment, jsx } from 'react/jsx-runtime';\nimport { TableCaption, TableThead, TableTr, TableTh, TableTbody, TableTd, TableTfoot } from './Table.components.mjs';\n\nfunction TableDataRenderer({ data }) {\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n data.caption && /* @__PURE__ */ jsx(TableCaption, { children: data.caption }),\n data.head && /* @__PURE__ */ jsx(TableThead, { children: /* @__PURE__ */ jsx(TableTr, { children: data.head.map((item, index) => /* @__PURE__ */ jsx(TableTh, { children: item }, index)) }) }),\n data.body && /* @__PURE__ */ jsx(TableTbody, { children: data.body.map((row, rowIndex) => /* @__PURE__ */ jsx(TableTr, { children: row.map((item, index) => /* @__PURE__ */ jsx(TableTd, { children: item }, index)) }, rowIndex)) }),\n data.foot && /* @__PURE__ */ jsx(TableTfoot, { children: /* @__PURE__ */ jsx(TableTr, { children: data.foot.map((item, index) => /* @__PURE__ */ jsx(TableTh, { children: item }, index)) }) })\n ] });\n}\nTableDataRenderer.displayName = \"@mantine/core/TableDataRenderer\";\n\nexport { TableDataRenderer };\n//# sourceMappingURL=TableDataRenderer.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { ScrollArea } from '../ScrollArea/ScrollArea.mjs';\nimport classes from './Table.module.css.mjs';\n\nconst defaultProps = {\n type: \"scrollarea\"\n};\nconst varsResolver = createVarsResolver((_, { minWidth, type }) => ({\n scrollContainer: {\n \"--table-min-width\": rem(minWidth),\n \"--table-overflow\": type === \"native\" ? \"auto\" : void 0\n }\n}));\nconst TableScrollContainer = factory((_props, ref) => {\n const props = useProps(\"TableScrollContainer\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n children,\n minWidth,\n type,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"TableScrollContainer\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver,\n rootSelector: \"scrollContainer\"\n });\n return /* @__PURE__ */ jsx(\n Box,\n {\n component: type === \"scrollarea\" ? ScrollArea : \"div\",\n ...type === \"scrollarea\" ? { offsetScrollbars: \"x\" } : {},\n ref,\n ...getStyles(\"scrollContainer\"),\n ...others,\n children: /* @__PURE__ */ jsx(\"div\", { ...getStyles(\"scrollContainerInner\"), children })\n }\n );\n});\nTableScrollContainer.classes = classes;\nTableScrollContainer.displayName = \"@mantine/core/TableScrollContainer\";\n\nexport { TableScrollContainer };\n//# sourceMappingURL=TableScrollContainer.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { rem } from '../../core/utils/units-converters/rem.mjs';\nimport 'react';\nimport { getSpacing } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { getThemeColor } from '../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { TableTd, TableTh, TableTr, TableThead, TableTbody, TableTfoot, TableCaption } from './Table.components.mjs';\nimport { TableProvider } from './Table.context.mjs';\nimport { TableDataRenderer } from './TableDataRenderer.mjs';\nimport { TableScrollContainer } from './TableScrollContainer.mjs';\nimport classes from './Table.module.css.mjs';\n\nconst defaultProps = {\n withRowBorders: true,\n verticalSpacing: 7\n};\nconst varsResolver = createVarsResolver(\n (theme, {\n layout,\n captionSide,\n horizontalSpacing,\n verticalSpacing,\n borderColor,\n stripedColor,\n highlightOnHoverColor,\n striped,\n highlightOnHover,\n stickyHeaderOffset,\n stickyHeader\n }) => ({\n table: {\n \"--table-layout\": layout,\n \"--table-caption-side\": captionSide,\n \"--table-horizontal-spacing\": getSpacing(horizontalSpacing),\n \"--table-vertical-spacing\": getSpacing(verticalSpacing),\n \"--table-border-color\": borderColor ? getThemeColor(borderColor, theme) : void 0,\n \"--table-striped-color\": striped && stripedColor ? getThemeColor(stripedColor, theme) : void 0,\n \"--table-highlight-on-hover-color\": highlightOnHover && highlightOnHoverColor ? getThemeColor(highlightOnHoverColor, theme) : void 0,\n \"--table-sticky-header-offset\": stickyHeader ? rem(stickyHeaderOffset) : void 0\n }\n })\n);\nconst Table = factory((_props, ref) => {\n const props = useProps(\"Table\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n horizontalSpacing,\n verticalSpacing,\n captionSide,\n stripedColor,\n highlightOnHoverColor,\n striped,\n highlightOnHover,\n withColumnBorders,\n withRowBorders,\n withTableBorder,\n borderColor,\n layout,\n variant,\n data,\n children,\n stickyHeader,\n stickyHeaderOffset,\n mod,\n tabularNums,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Table\",\n props,\n className,\n style,\n classes,\n classNames,\n styles,\n unstyled,\n rootSelector: \"table\",\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(\n TableProvider,\n {\n value: {\n getStyles,\n stickyHeader,\n striped: striped === true ? \"odd\" : striped || void 0,\n highlightOnHover,\n withColumnBorders,\n withRowBorders,\n captionSide: captionSide || \"bottom\"\n },\n children: /* @__PURE__ */ jsx(\n Box,\n {\n component: \"table\",\n variant,\n ref,\n mod: [{ \"data-with-table-border\": withTableBorder, \"data-tabular-nums\": tabularNums }, mod],\n ...getStyles(\"table\"),\n ...others,\n children: children || !!data && /* @__PURE__ */ jsx(TableDataRenderer, { data })\n }\n )\n }\n );\n});\nTable.classes = classes;\nTable.displayName = \"@mantine/core/Table\";\nTable.Td = TableTd;\nTable.Th = TableTh;\nTable.Tr = TableTr;\nTable.Thead = TableThead;\nTable.Tbody = TableTbody;\nTable.Tfoot = TableTfoot;\nTable.Caption = TableCaption;\nTable.ScrollContainer = TableScrollContainer;\nTable.DataRenderer = TableDataRenderer;\n\nexport { Table };\n//# sourceMappingURL=Table.mjs.map\n","'use client';\nimport 'react';\nimport { createSafeContext } from '../../core/utils/create-safe-context/create-safe-context.mjs';\nimport 'react/jsx-runtime';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../core/Box/Box.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\n\nconst [TabsProvider, useTabsContext] = createSafeContext(\n \"Tabs component was not found in the tree\"\n);\n\nexport { TabsProvider, useTabsContext };\n//# sourceMappingURL=Tabs.context.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_89d60db1\",\"list--default\":\"m_576c9d4\",\"list\":\"m_89d33d6d\",\"panel\":\"m_b0c91715\",\"tab\":\"m_4ec4dce6\",\"tabSection\":\"m_fc420b1f\",\"tab--default\":\"m_539e827b\",\"list--outline\":\"m_6772fbd5\",\"tab--outline\":\"m_b59ab47c\",\"tab--pills\":\"m_c3381914\"};\n\nexport { classes as default };\n//# sourceMappingURL=Tabs.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useTabsContext } from '../Tabs.context.mjs';\nimport classes from '../Tabs.module.css.mjs';\n\nconst defaultProps = {};\nconst TabsList = factory((_props, ref) => {\n const props = useProps(\"TabsList\", defaultProps, _props);\n const { children, className, grow, justify, classNames, styles, style, mod, ...others } = props;\n const ctx = useTabsContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n ...others,\n ...ctx.getStyles(\"list\", {\n className,\n style,\n classNames,\n styles,\n props,\n variant: ctx.variant\n }),\n ref,\n role: \"tablist\",\n variant: ctx.variant,\n mod: [\n {\n grow,\n orientation: ctx.orientation,\n placement: ctx.orientation === \"vertical\" && ctx.placement,\n inverted: ctx.inverted\n },\n mod\n ],\n \"aria-orientation\": ctx.orientation,\n __vars: { \"--tabs-justify\": justify },\n children\n }\n );\n});\nTabsList.classes = classes;\nTabsList.displayName = \"@mantine/core/TabsList\";\n\nexport { TabsList };\n//# sourceMappingURL=TabsList.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { Box } from '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { useTabsContext } from '../Tabs.context.mjs';\nimport classes from '../Tabs.module.css.mjs';\n\nconst defaultProps = {};\nconst TabsPanel = factory((_props, ref) => {\n const props = useProps(\"TabsPanel\", defaultProps, _props);\n const { children, className, value, classNames, styles, style, mod, keepMounted, ...others } = props;\n const ctx = useTabsContext();\n const active = ctx.value === value;\n const content = ctx.keepMounted || keepMounted ? children : active ? children : null;\n return /* @__PURE__ */ jsx(\n Box,\n {\n ...others,\n ...ctx.getStyles(\"panel\", {\n className,\n classNames,\n styles,\n style: [style, !active ? { display: \"none\" } : void 0],\n props\n }),\n ref,\n mod: [{ orientation: ctx.orientation }, mod],\n role: \"tabpanel\",\n id: ctx.getPanelId(value),\n \"aria-labelledby\": ctx.getTabId(value),\n children: content\n }\n );\n});\nTabsPanel.classes = classes;\nTabsPanel.displayName = \"@mantine/core/TabsPanel\";\n\nexport { TabsPanel };\n//# sourceMappingURL=TabsPanel.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport 'react';\nimport { createScopedKeydownHandler } from '../../../core/utils/create-scoped-keydown-handler/create-scoped-keydown-handler.mjs';\nimport '@mantine/hooks';\nimport 'clsx';\nimport { getThemeColor } from '../../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport '../../../core/MantineProvider/Mantine.context.mjs';\nimport '../../../core/MantineProvider/default-theme.mjs';\nimport '../../../core/MantineProvider/MantineProvider.mjs';\nimport { useMantineTheme } from '../../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport '../../../core/Box/Box.mjs';\nimport { factory } from '../../../core/factory/factory.mjs';\nimport { useDirection } from '../../../core/DirectionProvider/DirectionProvider.mjs';\nimport { UnstyledButton } from '../../UnstyledButton/UnstyledButton.mjs';\nimport { useTabsContext } from '../Tabs.context.mjs';\nimport classes from '../Tabs.module.css.mjs';\n\nconst defaultProps = {};\nconst TabsTab = factory((_props, ref) => {\n const props = useProps(\"TabsTab\", defaultProps, _props);\n const {\n className,\n children,\n rightSection,\n leftSection,\n value,\n onClick,\n onKeyDown,\n disabled,\n color,\n style,\n classNames,\n styles,\n vars,\n mod,\n tabIndex,\n ...others\n } = props;\n const theme = useMantineTheme();\n const { dir } = useDirection();\n const ctx = useTabsContext();\n const active = value === ctx.value;\n const activateTab = (event) => {\n ctx.onChange(ctx.allowTabDeactivation ? value === ctx.value ? null : value : value);\n onClick?.(event);\n };\n const stylesApiProps = { classNames, styles, props };\n return /* @__PURE__ */ jsxs(\n UnstyledButton,\n {\n ...others,\n ...ctx.getStyles(\"tab\", { className, style, variant: ctx.variant, ...stylesApiProps }),\n disabled,\n unstyled: ctx.unstyled,\n variant: ctx.variant,\n mod: [\n {\n active,\n disabled,\n orientation: ctx.orientation,\n inverted: ctx.inverted,\n placement: ctx.orientation === \"vertical\" && ctx.placement\n },\n mod\n ],\n ref,\n role: \"tab\",\n id: ctx.getTabId(value),\n \"aria-selected\": active,\n tabIndex: tabIndex !== void 0 ? tabIndex : active || ctx.value === null ? 0 : -1,\n \"aria-controls\": ctx.getPanelId(value),\n onClick: activateTab,\n __vars: { \"--tabs-color\": color ? getThemeColor(color, theme) : void 0 },\n onKeyDown: createScopedKeydownHandler({\n siblingSelector: '[role=\"tab\"]',\n parentSelector: '[role=\"tablist\"]',\n activateOnFocus: ctx.activateTabWithKeyboard,\n loop: ctx.loop,\n orientation: ctx.orientation || \"horizontal\",\n dir,\n onKeyDown\n }),\n children: [\n leftSection && /* @__PURE__ */ jsx(\"span\", { ...ctx.getStyles(\"tabSection\", stylesApiProps), \"data-position\": \"left\", children: leftSection }),\n children && /* @__PURE__ */ jsx(\"span\", { ...ctx.getStyles(\"tabLabel\", stylesApiProps), children }),\n rightSection && /* @__PURE__ */ jsx(\"span\", { ...ctx.getStyles(\"tabSection\", stylesApiProps), \"data-position\": \"right\", children: rightSection })\n ]\n }\n );\n});\nTabsTab.classes = classes;\nTabsTab.displayName = \"@mantine/core/TabsTab\";\n\nexport { TabsTab };\n//# sourceMappingURL=TabsTab.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useId, useUncontrolled } from '@mantine/hooks';\nimport 'react';\nimport { getSafeId } from '../../core/utils/get-safe-id/get-safe-id.mjs';\nimport { getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport { getThemeColor } from '../../core/MantineProvider/color-functions/get-theme-color/get-theme-color.mjs';\nimport { getContrastColor } from '../../core/MantineProvider/color-functions/get-contrast-color/get-contrast-color.mjs';\nimport { getAutoContrastValue } from '../../core/MantineProvider/color-functions/get-auto-contrast-value/get-auto-contrast-value.mjs';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport { TabsProvider } from './Tabs.context.mjs';\nimport { TabsList } from './TabsList/TabsList.mjs';\nimport { TabsPanel } from './TabsPanel/TabsPanel.mjs';\nimport { TabsTab } from './TabsTab/TabsTab.mjs';\nimport classes from './Tabs.module.css.mjs';\n\nconst VALUE_ERROR = \"Tabs.Tab or Tabs.Panel component was rendered with invalid value or without value\";\nconst defaultProps = {\n keepMounted: true,\n orientation: \"horizontal\",\n loop: true,\n activateTabWithKeyboard: true,\n allowTabDeactivation: false,\n unstyled: false,\n inverted: false,\n variant: \"default\",\n placement: \"left\"\n};\nconst varsResolver = createVarsResolver((theme, { radius, color, autoContrast }) => ({\n root: {\n \"--tabs-radius\": getRadius(radius),\n \"--tabs-color\": getThemeColor(color, theme),\n \"--tabs-text-color\": getAutoContrastValue(autoContrast, theme) ? getContrastColor({ color, theme, autoContrast }) : void 0\n }\n}));\nconst Tabs = factory((_props, ref) => {\n const props = useProps(\"Tabs\", defaultProps, _props);\n const {\n defaultValue,\n value,\n onChange,\n orientation,\n children,\n loop,\n id,\n activateTabWithKeyboard,\n allowTabDeactivation,\n variant,\n color,\n radius,\n inverted,\n placement,\n keepMounted,\n classNames,\n styles,\n unstyled,\n className,\n style,\n vars,\n autoContrast,\n mod,\n ...others\n } = props;\n const uid = useId(id);\n const [currentTab, setCurrentTab] = useUncontrolled({\n value,\n defaultValue,\n finalValue: null,\n onChange\n });\n const getStyles = useStyles({\n name: \"Tabs\",\n props,\n classes,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(\n TabsProvider,\n {\n value: {\n placement,\n value: currentTab,\n orientation,\n id: uid,\n loop,\n activateTabWithKeyboard,\n getTabId: getSafeId(`${uid}-tab`, VALUE_ERROR),\n getPanelId: getSafeId(`${uid}-panel`, VALUE_ERROR),\n onChange: setCurrentTab,\n allowTabDeactivation,\n variant,\n color,\n radius,\n inverted,\n keepMounted,\n unstyled,\n getStyles\n },\n children: /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n id: uid,\n variant,\n mod: [\n {\n orientation,\n inverted: orientation === \"horizontal\" && inverted,\n placement: orientation === \"vertical\" && placement\n },\n mod\n ],\n ...getStyles(\"root\"),\n ...others,\n children\n }\n )\n }\n );\n});\nTabs.classes = classes;\nTabs.displayName = \"@mantine/core/Tabs\";\nTabs.Tab = TabsTab;\nTabs.Panel = TabsPanel;\nTabs.List = TabsList;\n\nexport { Tabs };\n//# sourceMappingURL=Tabs.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_7341320d\"};\n\nexport { classes as default };\n//# sourceMappingURL=ThemeIcon.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport { getSize, getRadius } from '../../core/utils/get-size/get-size.mjs';\nimport '@mantine/hooks';\nimport { createVarsResolver } from '../../core/styles-api/create-vars-resolver/create-vars-resolver.mjs';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './ThemeIcon.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver(\n (theme, { size, radius, variant, gradient, color, autoContrast }) => {\n const colors = theme.variantColorResolver({\n color: color || theme.primaryColor,\n theme,\n gradient,\n variant: variant || \"filled\",\n autoContrast\n });\n return {\n root: {\n \"--ti-size\": getSize(size, \"ti-size\"),\n \"--ti-radius\": radius === void 0 ? void 0 : getRadius(radius),\n \"--ti-bg\": color || variant ? colors.background : void 0,\n \"--ti-color\": color || variant ? colors.color : void 0,\n \"--ti-bd\": color || variant ? colors.border : void 0\n }\n };\n }\n);\nconst ThemeIcon = factory((_props, ref) => {\n const props = useProps(\"ThemeIcon\", defaultProps, _props);\n const { classNames, className, style, styles, unstyled, vars, autoContrast, ...others } = props;\n const getStyles = useStyles({\n name: \"ThemeIcon\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n return /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\"), ...others });\n});\nThemeIcon.classes = classes;\nThemeIcon.displayName = \"@mantine/core/ThemeIcon\";\n\nexport { ThemeIcon };\n//# sourceMappingURL=ThemeIcon.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_d6493fad\"};\n\nexport { classes as default };\n//# sourceMappingURL=TypographyStylesProvider.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'react';\nimport '@mantine/hooks';\nimport 'clsx';\nimport '../../core/MantineProvider/Mantine.context.mjs';\nimport '../../core/MantineProvider/default-theme.mjs';\nimport '../../core/MantineProvider/MantineProvider.mjs';\nimport '../../core/MantineProvider/MantineThemeProvider/MantineThemeProvider.mjs';\nimport { useProps } from '../../core/MantineProvider/use-props/use-props.mjs';\nimport '../../core/MantineProvider/MantineCssVariables/MantineCssVariables.mjs';\nimport { useStyles } from '../../core/styles-api/use-styles/use-styles.mjs';\nimport { Box } from '../../core/Box/Box.mjs';\nimport { factory } from '../../core/factory/factory.mjs';\nimport '../../core/DirectionProvider/DirectionProvider.mjs';\nimport classes from './TypographyStylesProvider.module.css.mjs';\n\nconst defaultProps = {};\nconst TypographyStylesProvider = factory((_props, ref) => {\n const props = useProps(\"TypographyStylesProvider\", defaultProps, _props);\n const { classNames, className, style, styles, unstyled, ...others } = props;\n const getStyles = useStyles({\n name: \"TypographyStylesProvider\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled\n });\n return /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"root\"), ...others });\n});\nTypographyStylesProvider.classes = classes;\nTypographyStylesProvider.displayName = \"@mantine/core/TypographyStylesProvider\";\n\nexport { TypographyStylesProvider };\n//# sourceMappingURL=TypographyStylesProvider.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconAdjustmentsHorizontal = createReactComponent(\"outline\", \"adjustments-horizontal\", \"IconAdjustmentsHorizontal\", [[\"path\", { \"d\": \"M14 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 6l8 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M16 6l4 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M8 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M4 12l2 0\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M10 12l10 0\", \"key\": \"svg-5\" }], [\"path\", { \"d\": \"M17 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\", \"key\": \"svg-6\" }], [\"path\", { \"d\": \"M4 18l11 0\", \"key\": \"svg-7\" }], [\"path\", { \"d\": \"M19 18l1 0\", \"key\": \"svg-8\" }]]);\n\nexport { IconAdjustmentsHorizontal as default };\n//# sourceMappingURL=IconAdjustmentsHorizontal.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconArrowBackUp = createReactComponent(\"outline\", \"arrow-back-up\", \"IconArrowBackUp\", [[\"path\", { \"d\": \"M9 14l-4 -4l4 -4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M5 10h11a4 4 0 1 1 0 8h-1\", \"key\": \"svg-1\" }]]);\n\nexport { IconArrowBackUp as default };\n//# sourceMappingURL=IconArrowBackUp.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconArrowLeft = createReactComponent(\"outline\", \"arrow-left\", \"IconArrowLeft\", [[\"path\", { \"d\": \"M5 12l14 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M5 12l6 6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M5 12l6 -6\", \"key\": \"svg-2\" }]]);\n\nexport { IconArrowLeft as default };\n//# sourceMappingURL=IconArrowLeft.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconArrowRight = createReactComponent(\"outline\", \"arrow-right\", \"IconArrowRight\", [[\"path\", { \"d\": \"M5 12l14 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M13 18l6 -6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M13 6l6 6\", \"key\": \"svg-2\" }]]);\n\nexport { IconArrowRight as default };\n//# sourceMappingURL=IconArrowRight.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconArrowUpRight = createReactComponent(\"outline\", \"arrow-up-right\", \"IconArrowUpRight\", [[\"path\", { \"d\": \"M17 7l-10 10\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M8 7l9 0l0 9\", \"key\": \"svg-1\" }]]);\n\nexport { IconArrowUpRight as default };\n//# sourceMappingURL=IconArrowUpRight.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconBookmark = createReactComponent(\"outline\", \"bookmark\", \"IconBookmark\", [[\"path\", { \"d\": \"M18 7v14l-6 -4l-6 4v-14a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4z\", \"key\": \"svg-0\" }]]);\n\nexport { IconBookmark as default };\n//# sourceMappingURL=IconBookmark.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconBrandFacebook = createReactComponent(\"outline\", \"brand-facebook\", \"IconBrandFacebook\", [[\"path\", { \"d\": \"M7 10v4h3v7h4v-7h3l1 -4h-4v-2a1 1 0 0 1 1 -1h3v-4h-3a5 5 0 0 0 -5 5v2h-3\", \"key\": \"svg-0\" }]]);\n\nexport { IconBrandFacebook as default };\n//# sourceMappingURL=IconBrandFacebook.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconBrandInstagram = createReactComponent(\"outline\", \"brand-instagram\", \"IconBrandInstagram\", [[\"path\", { \"d\": \"M4 8a4 4 0 0 1 4 -4h8a4 4 0 0 1 4 4v8a4 4 0 0 1 -4 4h-8a4 4 0 0 1 -4 -4z\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M16.5 7.5v.01\", \"key\": \"svg-2\" }]]);\n\nexport { IconBrandInstagram as default };\n//# sourceMappingURL=IconBrandInstagram.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconCalendarCheck = createReactComponent(\"outline\", \"calendar-check\", \"IconCalendarCheck\", [[\"path\", { \"d\": \"M11.5 21h-5.5a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v6\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16 3v4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 3v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 11h16\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M15 19l2 2l4 -4\", \"key\": \"svg-4\" }]]);\n\nexport { IconCalendarCheck as default };\n//# sourceMappingURL=IconCalendarCheck.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconCalendarDown = createReactComponent(\"outline\", \"calendar-down\", \"IconCalendarDown\", [[\"path\", { \"d\": \"M12.5 21h-6.5a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v5\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M19 16v6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M22 19l-3 3l-3 -3\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M16 3v4\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M8 3v4\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M4 11h16\", \"key\": \"svg-5\" }]]);\n\nexport { IconCalendarDown as default };\n//# sourceMappingURL=IconCalendarDown.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconCalendarEvent = createReactComponent(\"outline\", \"calendar-event\", \"IconCalendarEvent\", [[\"path\", { \"d\": \"M4 5m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16 3l0 4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 3l0 4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 11l16 0\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M8 15h2v2h-2z\", \"key\": \"svg-4\" }]]);\n\nexport { IconCalendarEvent as default };\n//# sourceMappingURL=IconCalendarEvent.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconCalendarTime = createReactComponent(\"outline\", \"calendar-time\", \"IconCalendarTime\", [[\"path\", { \"d\": \"M11.795 21h-6.795a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M18 18m-4 0a4 4 0 1 0 8 0a4 4 0 1 0 -8 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M15 3v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M7 3v4\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M3 11h16\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M18 16.496v1.504l1 1\", \"key\": \"svg-5\" }]]);\n\nexport { IconCalendarTime as default };\n//# sourceMappingURL=IconCalendarTime.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconCalendarUp = createReactComponent(\"outline\", \"calendar-up\", \"IconCalendarUp\", [[\"path\", { \"d\": \"M12.5 21h-6.5a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v5\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16 3v4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 3v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 11h16\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M19 22v-6\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M22 19l-3 -3l-3 3\", \"key\": \"svg-5\" }]]);\n\nexport { IconCalendarUp as default };\n//# sourceMappingURL=IconCalendarUp.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconCalendar = createReactComponent(\"outline\", \"calendar\", \"IconCalendar\", [[\"path\", { \"d\": \"M4 7a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12z\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16 3v4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 3v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 11h16\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M11 15h1\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M12 15v3\", \"key\": \"svg-5\" }]]);\n\nexport { IconCalendar as default };\n//# sourceMappingURL=IconCalendar.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconClockEdit = createReactComponent(\"outline\", \"clock-edit\", \"IconClockEdit\", [[\"path\", { \"d\": \"M21 12a9 9 0 1 0 -9.972 8.948c.32 .034 .644 .052 .972 .052\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 7v5l2 2\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M18.42 15.61a2.1 2.1 0 0 1 2.97 2.97l-3.39 3.42h-3v-3l3.42 -3.39z\", \"key\": \"svg-2\" }]]);\n\nexport { IconClockEdit as default };\n//# sourceMappingURL=IconClockEdit.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconClockHour4 = createReactComponent(\"outline\", \"clock-hour-4\", \"IconClockHour4\", [[\"path\", { \"d\": \"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 12l3 2\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 7v5\", \"key\": \"svg-2\" }]]);\n\nexport { IconClockHour4 as default };\n//# sourceMappingURL=IconClockHour4.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconClock = createReactComponent(\"outline\", \"clock\", \"IconClock\", [[\"path\", { \"d\": \"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 7v5l3 3\", \"key\": \"svg-1\" }]]);\n\nexport { IconClock as default };\n//# sourceMappingURL=IconClock.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconCopy = createReactComponent(\"outline\", \"copy\", \"IconCopy\", [[\"path\", { \"d\": \"M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1\", \"key\": \"svg-1\" }]]);\n\nexport { IconCopy as default };\n//# sourceMappingURL=IconCopy.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconDeviceFloppy = createReactComponent(\"outline\", \"device-floppy\", \"IconDeviceFloppy\", [[\"path\", { \"d\": \"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M14 4l0 4l-6 0l0 -4\", \"key\": \"svg-2\" }]]);\n\nexport { IconDeviceFloppy as default };\n//# sourceMappingURL=IconDeviceFloppy.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconDotsVertical = createReactComponent(\"outline\", \"dots-vertical\", \"IconDotsVertical\", [[\"path\", { \"d\": \"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 19m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-2\" }]]);\n\nexport { IconDotsVertical as default };\n//# sourceMappingURL=IconDotsVertical.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconExternalLink = createReactComponent(\"outline\", \"external-link\", \"IconExternalLink\", [[\"path\", { \"d\": \"M12 6h-6a2 2 0 0 0 -2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-6\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M11 13l9 -9\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M15 4h5v5\", \"key\": \"svg-2\" }]]);\n\nexport { IconExternalLink as default };\n//# sourceMappingURL=IconExternalLink.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconEye = createReactComponent(\"outline\", \"eye\", \"IconEye\", [[\"path\", { \"d\": \"M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6\", \"key\": \"svg-1\" }]]);\n\nexport { IconEye as default };\n//# sourceMappingURL=IconEye.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconInfoCircle = createReactComponent(\"outline\", \"info-circle\", \"IconInfoCircle\", [[\"path\", { \"d\": \"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 9h.01\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M11 12h1v4h1\", \"key\": \"svg-2\" }]]);\n\nexport { IconInfoCircle as default };\n//# sourceMappingURL=IconInfoCircle.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconLink = createReactComponent(\"outline\", \"link\", \"IconLink\", [[\"path\", { \"d\": \"M9 15l6 -6\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M11 6l.463 -.536a5 5 0 0 1 7.071 7.072l-.534 .464\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463\", \"key\": \"svg-2\" }]]);\n\nexport { IconLink as default };\n//# sourceMappingURL=IconLink.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconMenu2 = createReactComponent(\"outline\", \"menu-2\", \"IconMenu2\", [[\"path\", { \"d\": \"M4 6l16 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 12l16 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M4 18l16 0\", \"key\": \"svg-2\" }]]);\n\nexport { IconMenu2 as default };\n//# sourceMappingURL=IconMenu2.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconNavigationPin = createReactComponent(\"outline\", \"navigation-pin\", \"IconNavigationPin\", [[\"path\", { \"d\": \"M16.002 11.676l-4.002 -8.676l-7.97 17.275c-.07 .2 -.017 .424 .135 .572c.15 .148 .374 .193 .57 .116l7.265 -2.463\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M21.121 20.121a3 3 0 1 0 -4.242 0c.418 .419 1.125 1.045 2.121 1.879c1.051 -.89 1.759 -1.516 2.121 -1.879z\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M19 18v.01\", \"key\": \"svg-2\" }]]);\n\nexport { IconNavigationPin as default };\n//# sourceMappingURL=IconNavigationPin.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconNotes = createReactComponent(\"outline\", \"notes\", \"IconNotes\", [[\"path\", { \"d\": \"M5 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 7l6 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M9 11l6 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M9 15l4 0\", \"key\": \"svg-3\" }]]);\n\nexport { IconNotes as default };\n//# sourceMappingURL=IconNotes.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconPencil = createReactComponent(\"outline\", \"pencil\", \"IconPencil\", [[\"path\", { \"d\": \"M4 20h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M13.5 6.5l4 4\", \"key\": \"svg-1\" }]]);\n\nexport { IconPencil as default };\n//# sourceMappingURL=IconPencil.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconPhoto = createReactComponent(\"outline\", \"photo\", \"IconPhoto\", [[\"path\", { \"d\": \"M15 8h.01\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M3 6a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-12z\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M3 16l5 -5c.928 -.893 2.072 -.893 3 0l5 5\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M14 14l1 -1c.928 -.893 2.072 -.893 3 0l3 3\", \"key\": \"svg-3\" }]]);\n\nexport { IconPhoto as default };\n//# sourceMappingURL=IconPhoto.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconRefresh = createReactComponent(\"outline\", \"refresh\", \"IconRefresh\", [[\"path\", { \"d\": \"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4\", \"key\": \"svg-1\" }]]);\n\nexport { IconRefresh as default };\n//# sourceMappingURL=IconRefresh.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconTag = createReactComponent(\"outline\", \"tag\", \"IconTag\", [[\"path\", { \"d\": \"M7.5 7.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M3 6v5.172a2 2 0 0 0 .586 1.414l7.71 7.71a2.41 2.41 0 0 0 3.408 0l5.592 -5.592a2.41 2.41 0 0 0 0 -3.408l-7.71 -7.71a2 2 0 0 0 -1.414 -.586h-5.172a3 3 0 0 0 -3 3z\", \"key\": \"svg-1\" }]]);\n\nexport { IconTag as default };\n//# sourceMappingURL=IconTag.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconUpload = createReactComponent(\"outline\", \"upload\", \"IconUpload\", [[\"path\", { \"d\": \"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M7 9l5 -5l5 5\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 4l0 12\", \"key\": \"svg-2\" }]]);\n\nexport { IconUpload as default };\n//# sourceMappingURL=IconUpload.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconUser = createReactComponent(\"outline\", \"user\", \"IconUser\", [[\"path\", { \"d\": \"M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2\", \"key\": \"svg-1\" }]]);\n\nexport { IconUser as default };\n//# sourceMappingURL=IconUser.mjs.map\n","/**\n * @license @tabler/icons-react v3.30.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nvar IconMapPinFilled = createReactComponent(\"filled\", \"map-pin-filled\", \"IconMapPinFilled\", [[\"path\", { \"d\": \"M18.364 4.636a9 9 0 0 1 .203 12.519l-.203 .21l-4.243 4.242a3 3 0 0 1 -4.097 .135l-.144 -.135l-4.244 -4.243a9 9 0 0 1 12.728 -12.728zm-6.364 3.364a3 3 0 1 0 0 6a3 3 0 0 0 0 -6z\", \"key\": \"svg-0\" }]]);\n\nexport { IconMapPinFilled as default };\n//# sourceMappingURL=IconMapPinFilled.mjs.map\n","import { useEffect, useState } from 'react';\nimport { Card, Avatar, Text, Group, Button, Badge, Image, Box, Skeleton } from '@mantine/core';\n\ninterface Artist {\n id: number;\n name: string;\n slug: string;\n description?: string;\n avatar_url?: string;\n instructor?: boolean;\n dj?: boolean;\n [key: string]: any;\n}\n\ninterface ArtistCardProps {\n artist: Artist;\n onCardClick?: (artist: Artist) => void;\n}\n\nexport default function ArtistCard({ artist, onCardClick }: ArtistCardProps) {\n const [imageLoaded, setImageLoaded] = useState(false);\n\n // Extract the first 100 characters of the description and strip HTML tags\n const getPlainTextDescription = (html?: string) => {\n if (!html) return '';\n\n // Create a temporary element to strip HTML tags\n const tempElement = document.createElement('div');\n tempElement.innerHTML = html;\n const plainText = tempElement.textContent || tempElement.innerText || '';\n\n return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText;\n };\n\n const plainDescription = getPlainTextDescription(artist.description);\n\n // Handle card click\n const handleCardClick = (e: React.MouseEvent) => {\n console.log('Passing artist to drawer:', artist);\n // If clicking on a link or button inside the card, don't trigger the drawer\n if ((e.target as HTMLElement).closest('a') || (e.target as HTMLElement).closest('button')) {\n return;\n }\n\n // Prevent default behavior\n e.preventDefault();\n e.stopPropagation();\n\n // Call the parent's onCardClick if provided\n if (onCardClick) {\n onCardClick(artist); // FIXED: Pass artist object instead of event\n }\n };\n\n return (\n \n \n {!imageLoaded && }\n \n \n \n \n {artist.name}\n \n\n \n {artist.instructor && (\n \n Instructor\n \n )}\n {artist.dj && (\n \n DJ\n \n )}\n \n \n \n );\n}\n","import { Button, Text } from '@mantine/core';\nimport { Link } from '@inertiajs/react';\nimport { Post } from './types';\ninterface PostDrawerContentProps {\n post: Post;\n}\nexport default function PostDrawerContent({ post }: PostDrawerContentProps) {\n return (\n <>\n \n {post.title}\n \n \n

Go to Post

\n \n \n );\n}\n","import { useState, useEffect } from 'react';\nimport {\n Text,\n Title,\n Group,\n Badge,\n Button,\n Image,\n Stack,\n Divider,\n Spoiler,\n Box,\n Flex,\n Avatar,\n ActionIcon,\n Tooltip,\n} from '@mantine/core';\nimport {\n IconCalendar,\n IconMapPin,\n IconClock,\n IconTicket,\n IconExternalLink,\n IconNavigationPin,\n} from '@tabler/icons-react';\n\nimport '../../styles/ShowView.css';\n\ninterface Event {\n id: number;\n name: string;\n event_start_date: string;\n event_end_date: string;\n description: string;\n event_type_ids: number[];\n event_types: { id: number; name: string }[];\n dance_style_ids: number[];\n dance_styles: { id: number; name: string }[];\n artist_ids: number[];\n artists: { id: number; name: string; avatar_url?: string }[];\n address: string;\n city: string;\n state: string;\n country?: string;\n ticket_url?: string;\n slug: string;\n banner_url?: string;\n [key: string]: any;\n}\n\ninterface EventDrawerContentProps {\n event: Event;\n}\n\nexport default function EventDrawerContent({ event }: EventDrawerContentProps) {\n useEffect(() => {\n console.log('Event data:', event);\n console.log('Event types:', event.event_types);\n console.log('Dance styles:', event.dance_styles);\n console.log('Artists:', event.artists);\n }, [event]);\n\n // Format dates for display\n const formatDate = (dateString: string) => {\n const date = new Date(dateString);\n return date.toLocaleDateString('en-US', {\n weekday: 'long',\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n });\n };\n\n const formatTime = (dateString: string) => {\n const date = new Date(dateString);\n return date.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: '2-digit',\n hour12: true,\n timeZone: 'UTC', // Forces display in UTC time\n });\n };\n\n // Format date range\n const formatDateRange = () => {\n const startDate = new Date(event.event_start_date);\n const endDate = new Date(event.event_end_date);\n if (startDate.toDateString() === endDate.toDateString()) {\n return formatDate(event.event_start_date);\n }\n return `${formatDate(event.event_start_date)} - ${formatDate(event.event_end_date)}`;\n };\n\n const isPastEvent = new Date(event.event_end_date) < new Date();\n\n // Format month for the date box\n const getMonthAbbreviation = (dateString: string) => {\n const date = new Date(dateString);\n return date.toLocaleString('en-US', { month: 'short' }).toUpperCase();\n };\n\n // Format day for the date box\n const getDayOfMonth = (dateString: string) => {\n const date = new Date(dateString);\n return date.getDate();\n };\n\n // Get day of week and full date\n const getFullDisplayDate = (dateString: string) => {\n const date = new Date(dateString);\n return date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });\n };\n\n const areSameDates = (startDateStr: string, endDateStr: string) => {\n const startDate = new Date(startDateStr);\n const endDate = new Date(endDateStr);\n return (\n startDate.getFullYear() === endDate.getFullYear() &&\n startDate.getMonth() === endDate.getMonth() &&\n startDate.getDate() === endDate.getDate()\n );\n };\n\n const month = getMonthAbbreviation(event.event_start_date);\n const day = getDayOfMonth(event.event_start_date);\n const fullStartDate = getFullDisplayDate(event.event_start_date);\n const fullEndDate = getFullDisplayDate(event.event_end_date);\n const startTime = formatTime(event.event_start_date);\n const endTime = formatTime(event.event_end_date);\n\n console.log('Start Time:', startTime);\n console.log('End Time:', endTime);\n\n // Get country flag emoji\n const getCountryFlag = (country?: string) => {\n if (!country || country.toLowerCase() === 'united states' || country.toLowerCase() === 'usa') {\n return '🇺🇸';\n }\n return '';\n };\n\n return (\n \n {/* Event Image */}\n {event.banner_url && (\n \n \n \n )}\n\n {/* Event Title */}\n \n \n {event.name}\n \n \n\n
\n \n About Event:\n \n
\n \n\n \n \n {/* Date Box */}\n \n \n \n {month}\n \n \n \n \n {day}\n \n \n \n\n {/* Date and Time Text */}\n
\n \n {areSameDates(event.event_start_date, event.event_end_date)\n ? fullStartDate\n : `${fullStartDate} - ${fullEndDate}`}\n \n \n {startTime} - {endTime}\n \n
\n
\n\n {/* Merged Address Section with Navigation Icon */}\n \n \n \n \n ({\n width: '100%', // full width on mobile/smaller screens\n [theme.fn.largerThan('sm')]: { width: 400 }, // 400px on larger screens\n })}\n style={{ color: '#f2f2f2', lineHeight: 1 }}\n >\n {event.address}\n \n \n \n \n \n \n \n
\n\n {/* Description */}\n \n
\n \n Details:{' '}\n \n
\n \n \n \n \n
\n\n {/* Event Types */}\n {event.event_types && event.event_types.length > 0 && (\n <>\n
\n \n Event Tags:\n \n
\n \n \n {event.event_types.map((type) => (\n \n {type.name}\n \n ))}\n \n \n )}\n\n {/* Dance Styles */}\n {event.dance_styles && event.dance_styles.length > 0 && (\n <>\n
\n \n Dance Styles:\n \n
\n \n \n {event.dance_styles.map((style: { id: number; name: string }) => (\n \n {style.name}\n \n ))}\n \n \n )}\n\n {/* Artists Section */}\n {event.artists && event.artists.length > 0 && (\n <>\n
\n \n Artists:\n \n
\n \n \n {event.artists.map((artist) => (\n \n \n \n {artist.name}\n \n \n ))}\n \n \n )}\n\n {/* Uncomment Action Buttons if needed */}\n {/*\n \n \n {!isPastEvent && event.ticket_url && (\n \n )}\n \n */}\n
\n );\n}\n","import { useState, useEffect } from 'react';\nimport { Text, Title, Group, Badge, Button, Image, Stack, Divider, Spoiler, Box, Flex, Avatar } from '@mantine/core';\nimport { IconCalendar, IconMapPin, IconClock, IconTicket, IconExternalLink } from '@tabler/icons-react';\n\nimport '../../styles/ShowView.css';\n\ninterface Artist {\n id: number;\n name: string;\n slug: string;\n description?: any; // Changed to any to account for complex description object\n avatar_url?: string;\n instructor?: boolean;\n dj?: boolean;\n dance_style_ids: number[];\n dance_styles: { id: number; name: string }[];\n}\n\ninterface ArtistDrawerContentProps {\n artist: Artist;\n}\n\nexport default function ArtistDrawerContent({ artist }: ArtistDrawerContentProps) {\n useEffect(() => {\n console.log('Artist received in drawer:', artist);\n }, [artist]);\n\n // Check if artist is a PointerEvent or other non-Artist object\n if (!artist || typeof artist !== 'object' || 'isTrusted' in artist) {\n return Loading artist information...;\n }\n\n return (\n \n {/* Display artist image */}\n {artist.avatar_url && (\n \n \n \n )}\n \n {artist?.name || 'Unknown Artist'}\n \n\n {/* Display artist role badges */}\n \n {artist.instructor && (\n \n Instructor\n \n )}\n {artist.dj && (\n \n DJ\n \n )}\n \n\n {artist.dance_styles && artist.dance_styles.length > 0 && (\n <>\n
\n \n Dance Styles\n \n
\n \n\n \n {artist.dance_styles.map((style: { id: number; name: string }) => (\n \n {style.name}\n \n ))}\n \n \n )}\n\n {/* Description */}\n {artist.description && (\n \n
\n \n About\n \n
\n \n \n \n \n
\n )}\n
\n );\n}\n","// DynamicDrawer.tsx\nimport { Drawer, Button, CopyButton, Group, Tooltip } from '@mantine/core';\nimport { IconCopy, IconExternalLink, IconCheck } from '@tabler/icons-react';\nimport PostDrawerContent from './PostDrawerContent';\nimport EventDrawerContent from './EventDrawerContent';\nimport ArtistDrawerContent from './ArtistDrawerContent';\n\nexport type DrawerContentType = 'post' | 'event' | 'artist';\n\ninterface DynamicDrawerProps {\n opened: boolean;\n type: DrawerContentType;\n data: any; // Or use a union type: Post | Event | Artist\n onClose: () => void;\n}\n\nexport default function DynamicDrawer({ opened, type, data, onClose }: DynamicDrawerProps) {\n let content = null;\n let pageUrl = '';\n let entityName = '';\n let entityTypeName = '';\n\n // Determine content, URL and entity type based on drawer type\n switch (type) {\n case 'post':\n content = ;\n pageUrl = data ? `${window.location.origin}/posts/${data.slug}` : '';\n entityName = data?.title || '';\n entityTypeName = 'Post';\n break;\n case 'event':\n content = ;\n pageUrl = data ? `${window.location.origin}/events/${data.slug}` : '';\n entityName = data?.name || '';\n entityTypeName = 'Event';\n break;\n case 'artist':\n content = ;\n pageUrl = data ? `${window.location.origin}/artists/${data.slug}` : '';\n entityName = data?.name || '';\n entityTypeName = 'Artist';\n break;\n default:\n break;\n }\n\n // Custom header with buttons\n const drawerHeader = (\n \n {/* No title here, just buttons */}\n \n {/* Copy Link Button */}\n \n {({ copied, copy }) => (\n : }\n style={{\n color: '#f2f2f2',\n }}\n onClick={copy}\n >\n {copied ? 'Copied!' : 'Copy Link'}\n \n )}\n \n\n {/* Navigate to Page Button */}\n }\n style={{\n color: '#f2f2f2',\n }}\n >\n {entityTypeName} Page\n \n \n \n );\n\n return (\n \n
\n {content}\n
\n \n );\n}\n","import { useState, useEffect } from 'react';\nimport {\n Box,\n Container,\n Grid,\n Title,\n Text,\n TextInput,\n Group,\n MultiSelect,\n Checkbox,\n Pagination,\n Badge,\n MantineProvider,\n ActionIcon,\n Drawer,\n Button,\n Stack,\n Divider,\n} from '@mantine/core';\nimport { Head } from '@inertiajs/react';\nimport { IconSearch, IconAdjustmentsHorizontal } from '@tabler/icons-react';\nimport ArtistCard from '../../components/Cards/ArtistCard';\nimport DynamicDrawer from '../../components/Drawer/DynamicDrawer';\nimport '../../styles/ShowView.css';\n\ninterface DanceStyle {\n id: number;\n name: string;\n}\n\ninterface Artist {\n id: number;\n name: string;\n slug: string;\n avatar_url?: string;\n instructor: boolean;\n dj: boolean;\n dance_styles?: DanceStyle[];\n dance_style_ids?: number[];\n description?: string | { body: string };\n [key: string]: any;\n}\n\ninterface ArtistIndexProps {\n artists: Artist[];\n totalArtists: number;\n danceStyles: DanceStyle[];\n}\n\nexport default function ArtistIndex({ artists, totalArtists, danceStyles }: ArtistIndexProps) {\n // State for search and filtering\n const [searchTerm, setSearchTerm] = useState('');\n const [selectedDanceStyles, setSelectedDanceStyles] = useState([]);\n const [isInstructor, setIsInstructor] = useState(false);\n const [isDj, setIsDj] = useState(false);\n\n // State for drawer\n const [filterDrawerOpened, setFilterDrawerOpened] = useState(false);\n\n // State for pagination\n const [currentPage, setCurrentPage] = useState(1);\n const [itemsPerPage, setItemsPerPage] = useState(16);\n\n // State for filtered artists\n const [filteredArtists, setFilteredArtists] = useState(artists);\n\n // State for dynamic drawer\n const [artistDrawerOpened, setArtistDrawerOpened] = useState(false);\n const [selectedArtist, setSelectedArtist] = useState(null);\n\n // Calculate active filter count\n const activeFilterCount = selectedDanceStyles.length + (isInstructor ? 1 : 0) + (isDj ? 1 : 0);\n\n // Effect to filter artists when search or filter criteria change\n useEffect(() => {\n let result = [...artists];\n\n // Filter by name\n if (searchTerm) {\n result = result.filter((artist) => artist.name.toLowerCase().includes(searchTerm.toLowerCase()));\n }\n\n // Filter by dance styles\n if (selectedDanceStyles.length > 0) {\n result = result.filter((artist) => {\n // Check if artist has dance_styles array with objects\n if (artist.dance_styles?.length > 0) {\n return artist.dance_styles.some((style) => selectedDanceStyles.includes(style.id.toString()));\n }\n // Check if artist has dance_style_ids array with IDs\n else if (artist.dance_style_ids?.length > 0) {\n return artist.dance_style_ids.some((styleId) => selectedDanceStyles.includes(styleId.toString()));\n }\n return false;\n });\n }\n\n // Filter by instructor/DJ\n if (isInstructor) {\n result = result.filter((artist) => artist.instructor);\n }\n\n if (isDj) {\n result = result.filter((artist) => artist.dj);\n }\n\n setFilteredArtists(result);\n setCurrentPage(1); // Reset to first page on filter change\n }, [searchTerm, selectedDanceStyles, isInstructor, isDj, artists]);\n\n // Calculate pagination\n const totalPages = Math.ceil(filteredArtists.length / itemsPerPage);\n const paginatedArtists = filteredArtists.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);\n\n // Handle artist card click\n const handleArtistClick = (artist: Artist) => {\n setSelectedArtist(artist);\n setArtistDrawerOpened(true);\n };\n\n // Handle artist drawer close\n const handleArtistDrawerClose = () => {\n setArtistDrawerOpened(false);\n };\n\n // Handle clear all filters\n const handleClearFilters = () => {\n setSelectedDanceStyles([]);\n setIsInstructor(false);\n setIsDj(false);\n };\n\n // Format dance styles for MultiSelect\n const danceStyleOptions = danceStyles.map((style) => ({\n value: style.id.toString(),\n label: style.name,\n }));\n\n return (\n <>\n \n \n\n \n {/* Search Section */}\n \n \n }\n placeholder=\"Search artists...\"\n value={searchTerm}\n onChange={(e) => setSearchTerm(e.currentTarget.value)}\n w={{ base: '80%', md: '600px' }}\n />\n\n {/* Filter Action Icon with Badge */}\n \n setFilterDrawerOpened(true)}>\n \n \n {activeFilterCount > 0 && (\n \n {activeFilterCount}\n \n )}\n \n \n \n\n {/* Results Section */}\n \n \n Currently showing {paginatedArtists.length} of {filteredArtists.length} artists.\n \n\n {/* Pagination */}\n {totalPages > 1 && (\n \n )}\n\n {/* Artist Grid */}\n \n {paginatedArtists.map((artist) => (\n \n \n \n ))}\n \n\n {/* Show message if no results */}\n {paginatedArtists.length === 0 && (\n \n No artists found matching your search criteria.\n \n )}\n\n {/* Bottom Pagination */}\n {totalPages > 1 && (\n \n )}\n \n \n\n {/* Filter Drawer from bottom */}\n setFilterDrawerOpened(false)}\n position=\"right\"\n size=\"md\"\n withCloseButton={true}\n style={{ zIndex: 1000 }}\n styles={{\n root: { zIndex: 1000 },\n header: {\n backgroundColor: '#18181B',\n color: '#f2f2f2',\n borderBottom: '1px solid #333',\n },\n body: {\n backgroundColor: '#18181B',\n color: '#f2f2f2',\n },\n close: {\n color: '#f2f2f2',\n '&:hover': { backgroundColor: 'rgba(255, 255, 255, 0.1)' },\n },\n }}\n >\n \n \n Filters\n \n\n \n\n {/* Dance Styles Filter */}\n \n \n Dance Styles\n \n \n \n\n \n\n {/* Artist Type Filters */}\n \n \n Artist Type\n \n \n setIsInstructor(e.currentTarget.checked)}\n styles={{\n label: { color: '#f2f2f2' },\n input: {\n '&:checked': {\n backgroundColor: '#EA580C',\n borderColor: '#EA580C',\n },\n },\n }}\n />\n setIsDj(e.currentTarget.checked)}\n styles={{\n label: { color: '#f2f2f2' },\n input: {\n '&:checked': {\n backgroundColor: '#EA580C',\n borderColor: '#EA580C',\n },\n },\n }}\n />\n \n \n\n \n\n {/* Bottom Action Row with Count and Clear Filters */}\n \n \n Clear All Filters\n \n setFilterDrawerOpened(false)}\n >\n Show {filteredArtists.length} Artists\n \n \n \n \n\n {/* Artist Dynamic Drawer */}\n {selectedArtist && (\n \n )}\n \n \n );\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","// ::- Persistent data structure representing an ordered mapping from\n// strings to values, with some convenient update methods.\nfunction OrderedMap(content) {\n this.content = content;\n}\n\nOrderedMap.prototype = {\n constructor: OrderedMap,\n\n find: function(key) {\n for (var i = 0; i < this.content.length; i += 2)\n if (this.content[i] === key) return i\n return -1\n },\n\n // :: (string) → ?any\n // Retrieve the value stored under `key`, or return undefined when\n // no such key exists.\n get: function(key) {\n var found = this.find(key);\n return found == -1 ? undefined : this.content[found + 1]\n },\n\n // :: (string, any, ?string) → OrderedMap\n // Create a new map by replacing the value of `key` with a new\n // value, or adding a binding to the end of the map. If `newKey` is\n // given, the key of the binding will be replaced with that key.\n update: function(key, value, newKey) {\n var self = newKey && newKey != key ? this.remove(newKey) : this;\n var found = self.find(key), content = self.content.slice();\n if (found == -1) {\n content.push(newKey || key, value);\n } else {\n content[found + 1] = value;\n if (newKey) content[found] = newKey;\n }\n return new OrderedMap(content)\n },\n\n // :: (string) → OrderedMap\n // Return a map with the given key removed, if it existed.\n remove: function(key) {\n var found = this.find(key);\n if (found == -1) return this\n var content = this.content.slice();\n content.splice(found, 2);\n return new OrderedMap(content)\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the start of the map.\n addToStart: function(key, value) {\n return new OrderedMap([key, value].concat(this.remove(key).content))\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the end of the map.\n addToEnd: function(key, value) {\n var content = this.remove(key).content.slice();\n content.push(key, value);\n return new OrderedMap(content)\n },\n\n // :: (string, string, any) → OrderedMap\n // Add a key after the given key. If `place` is not found, the new\n // key is added to the end.\n addBefore: function(place, key, value) {\n var without = this.remove(key), content = without.content.slice();\n var found = without.find(place);\n content.splice(found == -1 ? content.length : found, 0, key, value);\n return new OrderedMap(content)\n },\n\n // :: ((key: string, value: any))\n // Call the given function for each key/value pair in the map, in\n // order.\n forEach: function(f) {\n for (var i = 0; i < this.content.length; i += 2)\n f(this.content[i], this.content[i + 1]);\n },\n\n // :: (union) → OrderedMap\n // Create a new map by prepending the keys in this map that don't\n // appear in `map` before the keys in `map`.\n prepend: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(map.content.concat(this.subtract(map).content))\n },\n\n // :: (union) → OrderedMap\n // Create a new map by appending the keys in this map that don't\n // appear in `map` after the keys in `map`.\n append: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(this.subtract(map).content.concat(map.content))\n },\n\n // :: (union) → OrderedMap\n // Create a map containing all the keys in this map that don't\n // appear in `map`.\n subtract: function(map) {\n var result = this;\n map = OrderedMap.from(map);\n for (var i = 0; i < map.content.length; i += 2)\n result = result.remove(map.content[i]);\n return result\n },\n\n // :: () → Object\n // Turn ordered map into a plain object.\n toObject: function() {\n var result = {};\n this.forEach(function(key, value) { result[key] = value; });\n return result\n },\n\n // :: number\n // The amount of keys in this map.\n get size() {\n return this.content.length >> 1\n }\n};\n\n// :: (?union) → OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n if (value instanceof OrderedMap) return value\n var content = [];\n if (value) for (var prop in value) content.push(prop, value[prop]);\n return new OrderedMap(content)\n};\n\nexport default OrderedMap;\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 for (let j = 0; childA.text[j] == childB.text[j]; 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 same = 0, minSize = Math.min(childA.text.length, childB.text.length);\n while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {\n same++;\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}\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, round = -1) {\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 || round > 0)\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 new Fragment(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/*\nReplaceError = function(this: any, message: string) {\n let err = Error.call(this, message)\n ;(err as any).__proto__ = ReplaceError.prototype\n return err\n} as any\n\nReplaceError.prototype = Object.create(Error.prototype)\nReplaceError.prototype.constructor = ReplaceError\nReplaceError.prototype.name = \"ReplaceError\"\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);\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, parent) {\n let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && !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);\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 node.type.checkContent(content);\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](/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](/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 between\n the given two positions that are relative to start of this\n node's content. The callback is invoked with the node, its\n 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 name in values)\n if (!(name in attrs))\n throw new RangeError(`Unsupported attribute ${name} for ${type} of type ${name}`);\n for (let name in attrs) {\n let attr = attrs[name];\n if (attr.validate)\n attr.validate(values[name]);\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 = this.nodeFromJSON.bind(this);\n this.markFromJSON = this.markFromJSON.bind(this);\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 Deserialize a node from its JSON representation. This method is\n bound.\n */\n nodeFromJSON(json) {\n return Node.fromJSON(this, json);\n }\n /**\n Deserialize a mark from its JSON representation. This method is\n bound.\n */\n markFromJSON(json) {\n return Mark.fromJSON(this, json);\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.ParseRule.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, 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 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|\\r/g, \" \");\n }\n else {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n if (value)\n this.insertNode(this.parser.schema.text(value), marks);\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);\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)) {\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));\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) {\n let route, sync;\n for (let depth = this.open; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length)) {\n route = found;\n sync = cx;\n if (!found.length)\n break;\n }\n if (cx.solid)\n break;\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) {\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);\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);\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 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 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 (typeof structure == \"string\")\n return { dom: doc.createTextNode(structure) };\n if (structure.nodeType != null)\n return { dom: structure };\n if (structure.dom && structure.dom.nodeType != null)\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\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 {\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](/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(\n /**\n The step maps in this mapping.\n */\n 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.length) {\n this.maps = maps;\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n }\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 @internal\n */\n copy() {\n return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.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 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 from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);\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}\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;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);\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 }\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 , 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 let inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf)\n return false;\n this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\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 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, tr.doc.resolve(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 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 @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 a mark of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n if (!(mark instanceof Mark)) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n mark = mark.isInSet(node.marks);\n if (!mark)\n return this;\n }\n this.step(new RemoveNodeMarkStep(pos, mark));\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.\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 to = to == null ? from : to;\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)\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 Start a [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","import { TextSelection, NodeSelection, AllSelection, Selection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, Slice, DOMParser } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nconst domIndex = function (node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node)\n return index;\n }\n};\nconst parentNode = function (node) {\n let parent = node.assignedSlot || node.parentNode;\n return parent && parent.nodeType == 11 ? parent.host : parent;\n};\nlet reusedRange = null;\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nconst textRange = function (node, from, to) {\n let range = reusedRange || (reusedRange = document.createRange());\n range.setEnd(node, to == null ? node.nodeValue.length : to);\n range.setStart(node, from || 0);\n return range;\n};\nconst clearReusedRange = function () {\n reusedRange = null;\n};\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nconst isEquivalentPosition = function (node, off, targetNode, targetOff) {\n return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1));\n};\nconst atomElements = /^(img|br|input|textarea|hr)$/i;\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n for (;;) {\n if (node == targetNode && off == targetOff)\n return true;\n if (off == (dir < 0 ? 0 : nodeSize(node))) {\n let parent = node.parentNode;\n if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) ||\n node.contentEditable == \"false\")\n return false;\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n }\n else if (node.nodeType == 1) {\n node = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (node.contentEditable == \"false\")\n return false;\n off = dir < 0 ? nodeSize(node) : 0;\n }\n else {\n return false;\n }\n }\n}\nfunction nodeSize(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction textNodeBefore$1(node, offset) {\n for (;;) {\n if (node.nodeType == 3 && offset)\n return node;\n if (node.nodeType == 1 && offset > 0) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset - 1];\n offset = nodeSize(node);\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction textNodeAfter$1(node, offset) {\n for (;;) {\n if (node.nodeType == 3 && offset < node.nodeValue.length)\n return node;\n if (node.nodeType == 1 && offset < node.childNodes.length) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset];\n offset = 0;\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction isOnEdge(node, offset, parent) {\n for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n if (node == parent)\n return true;\n let index = domIndex(node);\n node = node.parentNode;\n if (!node)\n return false;\n atStart = atStart && index == 0;\n atEnd = atEnd && index == nodeSize(node);\n }\n}\nfunction hasBlockDesc(dom) {\n let desc;\n for (let cur = dom; cur; cur = cur.parentNode)\n if (desc = cur.pmViewDesc)\n break;\n return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);\n}\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nconst selectionCollapsed = function (domSel) {\n return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);\n};\nfunction keyEvent(keyCode, key) {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"keydown\", true, true);\n event.keyCode = keyCode;\n event.key = event.code = key;\n return event;\n}\nfunction deepActiveElement(doc) {\n let elt = doc.activeElement;\n while (elt && elt.shadowRoot)\n elt = elt.shadowRoot.activeElement;\n return elt;\n}\nfunction caretFromPoint(doc, x, y) {\n if (doc.caretPositionFromPoint) {\n try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n let pos = doc.caretPositionFromPoint(x, y);\n // Clip the offset, because Chrome will return a text offset\n // into nodes, which can't be treated as a regular DOM\n // offset\n if (pos)\n return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };\n }\n catch (_) { }\n }\n if (doc.caretRangeFromPoint) {\n let range = doc.caretRangeFromPoint(x, y);\n if (range)\n return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };\n }\n}\n\nconst nav = typeof navigator != \"undefined\" ? navigator : null;\nconst doc = typeof document != \"undefined\" ? document : null;\nconst agent = (nav && nav.userAgent) || \"\";\nconst ie_edge = /Edge\\/(\\d+)/.exec(agent);\nconst ie_upto10 = /MSIE \\d/.exec(agent);\nconst ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(agent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;\nconst gecko = !ie && /gecko\\/(\\d+)/i.test(agent);\ngecko && +(/Firefox\\/(\\d+)/.exec(agent) || [0, 0])[1];\nconst _chrome = !ie && /Chrome\\/(\\d+)/.exec(agent);\nconst chrome = !!_chrome;\nconst chrome_version = _chrome ? +_chrome[1] : 0;\nconst safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);\n// Is true for both iOS and iPadOS for convenience\nconst ios = safari && (/Mobile\\/\\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);\nconst mac = ios || (nav ? /Mac/.test(nav.platform) : false);\nconst windows = nav ? /Win/.test(nav.platform) : false;\nconst android = /Android \\d/.test(agent);\nconst webkit = !!doc && \"webkitFontSmoothing\" in doc.documentElement.style;\nconst webkit_version = webkit ? +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;\n\nfunction windowRect(doc) {\n let vp = doc.defaultView && doc.defaultView.visualViewport;\n if (vp)\n return {\n left: 0, right: vp.width,\n top: 0, bottom: vp.height\n };\n return { left: 0, right: doc.documentElement.clientWidth,\n top: 0, bottom: doc.documentElement.clientHeight };\n}\nfunction getSide(value, side) {\n return typeof value == \"number\" ? value : value[side];\n}\nfunction clientRect(node) {\n let rect = node.getBoundingClientRect();\n // Adjust for elements with style \"transform: scale()\"\n let scaleX = (rect.width / node.offsetWidth) || 1;\n let scaleY = (rect.height / node.offsetHeight) || 1;\n // Make sure scrollbar width isn't included in the rectangle\n return { left: rect.left, right: rect.left + node.clientWidth * scaleX,\n top: rect.top, bottom: rect.top + node.clientHeight * scaleY };\n}\nfunction scrollRectIntoView(view, rect, startDOM) {\n let scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n let doc = view.dom.ownerDocument;\n for (let parent = startDOM || view.dom;; parent = parentNode(parent)) {\n if (!parent)\n break;\n if (parent.nodeType != 1)\n continue;\n let elt = parent;\n let atTop = elt == doc.body;\n let bounding = atTop ? windowRect(doc) : clientRect(elt);\n let moveX = 0, moveY = 0;\n if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\"));\n else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n moveY = rect.bottom - rect.top > bounding.bottom - bounding.top\n ? rect.top + getSide(scrollMargin, \"top\") - bounding.top\n : rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\");\n if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\"));\n else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\");\n if (moveX || moveY) {\n if (atTop) {\n doc.defaultView.scrollBy(moveX, moveY);\n }\n else {\n let startX = elt.scrollLeft, startY = elt.scrollTop;\n if (moveY)\n elt.scrollTop += moveY;\n if (moveX)\n elt.scrollLeft += moveX;\n let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;\n rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };\n }\n }\n if (atTop || /^(fixed|sticky)$/.test(getComputedStyle(parent).position))\n break;\n }\n}\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n let refDOM, refTop;\n for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {\n let dom = view.root.elementFromPoint(x, y);\n if (!dom || dom == view.dom || !view.dom.contains(dom))\n continue;\n let localRect = dom.getBoundingClientRect();\n if (localRect.top >= startY - 20) {\n refDOM = dom;\n refTop = localRect.top;\n break;\n }\n }\n return { refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom) };\n}\nfunction scrollStack(dom) {\n let stack = [], doc = dom.ownerDocument;\n for (let cur = dom; cur; cur = parentNode(cur)) {\n stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });\n if (dom == doc)\n break;\n }\n return stack;\n}\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos({ refDOM, refTop, stack }) {\n let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\nfunction restoreScrollStack(stack, dTop) {\n for (let i = 0; i < stack.length; i++) {\n let { dom, top, left } = stack[i];\n if (dom.scrollTop != top + dTop)\n dom.scrollTop = top + dTop;\n if (dom.scrollLeft != left)\n dom.scrollLeft = left;\n }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n if (dom.setActive)\n return dom.setActive(); // in IE\n if (preventScrollSupported)\n return dom.focus(preventScrollSupported);\n let stored = scrollStack(dom);\n dom.focus(preventScrollSupported == null ? {\n get preventScroll() {\n preventScrollSupported = { preventScroll: true };\n return true;\n }\n } : undefined);\n if (!preventScrollSupported) {\n preventScrollSupported = false;\n restoreScrollStack(stored, 0);\n }\n}\nfunction findOffsetInNode(node, coords) {\n let closest, dxClosest = 2e8, coordsClosest, offset = 0;\n let rowBot = coords.top, rowTop = coords.top;\n let firstBelow, coordsBelow;\n for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n let rects;\n if (child.nodeType == 1)\n rects = child.getClientRects();\n else if (child.nodeType == 3)\n rects = textRange(child).getClientRects();\n else\n continue;\n for (let i = 0; i < rects.length; i++) {\n let rect = rects[i];\n if (rect.top <= rowBot && rect.bottom >= rowTop) {\n rowBot = Math.max(rect.bottom, rowBot);\n rowTop = Math.min(rect.top, rowTop);\n let dx = rect.left > coords.left ? rect.left - coords.left\n : rect.right < coords.left ? coords.left - rect.right : 0;\n if (dx < dxClosest) {\n closest = child;\n dxClosest = dx;\n coordsClosest = dx && closest.nodeType == 3 ? {\n left: rect.right < coords.left ? rect.right : rect.left,\n top: coords.top\n } : coords;\n if (child.nodeType == 1 && dx)\n offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);\n continue;\n }\n }\n else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {\n firstBelow = child;\n coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };\n }\n if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n coords.left >= rect.left && coords.top >= rect.bottom))\n offset = childIndex + 1;\n }\n }\n if (!closest && firstBelow) {\n closest = firstBelow;\n coordsClosest = coordsBelow;\n dxClosest = 0;\n }\n if (closest && closest.nodeType == 3)\n return findOffsetInText(closest, coordsClosest);\n if (!closest || (dxClosest && closest.nodeType == 1))\n return { node, offset };\n return findOffsetInNode(closest, coordsClosest);\n}\nfunction findOffsetInText(node, coords) {\n let len = node.nodeValue.length;\n let range = document.createRange();\n for (let i = 0; i < len; i++) {\n range.setEnd(node, i + 1);\n range.setStart(node, i);\n let rect = singleRect(range, 1);\n if (rect.top == rect.bottom)\n continue;\n if (inRect(coords, rect))\n return { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };\n }\n return { node, offset: 0 };\n}\nfunction inRect(coords, rect) {\n return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 &&\n coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;\n}\nfunction targetKludge(dom, coords) {\n let parent = dom.parentNode;\n if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n return parent;\n return dom;\n}\nfunction posFromElement(view, elt, coords) {\n let { node, offset } = findOffsetInNode(elt, coords), bias = -1;\n if (node.nodeType == 1 && !node.firstChild) {\n let rect = node.getBoundingClientRect();\n bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n }\n return view.docView.posFromDOM(node, offset, bias);\n}\nfunction posFromCaret(view, node, offset, coords) {\n // Browser (in caretPosition/RangeFromPoint) will agressively\n // normalize towards nearby inline nodes. Since we are interested in\n // positions between block nodes too, we first walk up the hierarchy\n // of nodes to see if there are block nodes that the coordinates\n // fall outside of. If so, we take the position before/after that\n // block. If not, we call `posFromDOM` on the raw node/offset.\n let outsideBlock = -1;\n for (let cur = node, sawBlock = false;;) {\n if (cur == view.dom)\n break;\n let desc = view.docView.nearestDesc(cur, true), rect;\n if (!desc)\n return null;\n if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) &&\n // Ignore elements with zero-size bounding rectangles\n ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {\n if (desc.node.isBlock && desc.parent) {\n // Only apply the horizontal test to the innermost block. Vertical for any parent.\n if (!sawBlock && rect.left > coords.left || rect.top > coords.top)\n outsideBlock = desc.posBefore;\n else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)\n outsideBlock = desc.posAfter;\n sawBlock = true;\n }\n if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {\n // If we are inside a leaf, return the side of the leaf closer to the coords\n let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2\n : coords.left < (rect.left + rect.right) / 2;\n return before ? desc.posBefore : desc.posAfter;\n }\n }\n cur = desc.dom.parentNode;\n }\n return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);\n}\nfunction elementFromPoint(element, coords, box) {\n let len = element.childNodes.length;\n if (len && box.top < box.bottom) {\n for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n let child = element.childNodes[i];\n if (child.nodeType == 1) {\n let rects = child.getClientRects();\n for (let j = 0; j < rects.length; j++) {\n let rect = rects[j];\n if (inRect(coords, rect))\n return elementFromPoint(child, coords, rect);\n }\n }\n if ((i = (i + 1) % len) == startI)\n break;\n }\n }\n return element;\n}\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n let doc = view.dom.ownerDocument, node, offset = 0;\n let caret = caretFromPoint(doc, coords.left, coords.top);\n if (caret)\n ({ node, offset } = caret);\n let elt = (view.root.elementFromPoint ? view.root : doc)\n .elementFromPoint(coords.left, coords.top);\n let pos;\n if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {\n let box = view.dom.getBoundingClientRect();\n if (!inRect(coords, box))\n return null;\n elt = elementFromPoint(view.dom, coords, box);\n if (!elt)\n return null;\n }\n // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n if (safari) {\n for (let p = elt; node && p; p = parentNode(p))\n if (p.draggable)\n node = undefined;\n }\n elt = targetKludge(elt, coords);\n if (node) {\n if (gecko && node.nodeType == 1) {\n // Firefox will sometimes return offsets into nodes, which\n // have no actual children, from caretPositionFromPoint (#953)\n offset = Math.min(offset, node.childNodes.length);\n // It'll also move the returned position before image nodes,\n // even if those are behind it.\n if (offset < node.childNodes.length) {\n let next = node.childNodes[offset], box;\n if (next.nodeName == \"IMG\" && (box = next.getBoundingClientRect()).right <= coords.left &&\n box.bottom > coords.top)\n offset++;\n }\n }\n let prev;\n // When clicking above the right side of an uneditable node, Chrome will report a cursor position after that node.\n if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 &&\n prev.contentEditable == \"false\" && prev.getBoundingClientRect().top >= coords.top)\n offset--;\n // Suspiciously specific kludge to work around caret*FromPoint\n // never returning a position at the end of the document\n if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 &&\n coords.top > node.lastChild.getBoundingClientRect().bottom)\n pos = view.state.doc.content.size;\n // Ignore positions directly after a BR, since caret*FromPoint\n // 'round up' positions that would be more accurately placed\n // before the BR node.\n else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != \"BR\")\n pos = posFromCaret(view, node, offset, coords);\n }\n if (pos == null)\n pos = posFromElement(view, elt, coords);\n let desc = view.docView.nearestDesc(elt, true);\n return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };\n}\nfunction nonZero(rect) {\n return rect.top < rect.bottom || rect.left < rect.right;\n}\nfunction singleRect(target, bias) {\n let rects = target.getClientRects();\n if (rects.length) {\n let first = rects[bias < 0 ? 0 : rects.length - 1];\n if (nonZero(first))\n return first;\n }\n return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();\n}\nconst BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);\n let supportEmptyRange = webkit || gecko;\n if (node.nodeType == 3) {\n // These browsers support querying empty text ranges. Prefer that in\n // bidi context or when at the end of a node.\n if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {\n let rect = singleRect(textRange(node, offset, offset), side);\n // Firefox returns bad results (the position before the space)\n // when querying a position directly after line-broken\n // whitespace. Detect this situation and and kludge around it\n if (gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n if (rectBefore.top == rect.top) {\n let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n if (rectAfter.top != rect.top)\n return flattenV(rectAfter, rectAfter.left < rectBefore.left);\n }\n }\n return rect;\n }\n else {\n let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;\n if (side < 0 && !offset) {\n to++;\n takeSide = -1;\n }\n else if (side >= 0 && offset == node.nodeValue.length) {\n from--;\n takeSide = 1;\n }\n else if (side < 0) {\n from--;\n }\n else {\n to++;\n }\n return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);\n }\n }\n let $dom = view.state.doc.resolve(pos - (atom || 0));\n // Return a horizontal line in block context\n if (!$dom.parent.inlineContent) {\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n if (before.nodeType == 1)\n return flattenH(before.getBoundingClientRect(), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n if (after.nodeType == 1)\n return flattenH(after.getBoundingClientRect(), true);\n }\n return flattenH(node.getBoundingClientRect(), side >= 0);\n }\n // Inline, not in text node (this is not Bidi-safe)\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1))\n // BR nodes tend to only return the rectangle before them.\n // Only use them if they are the last element in their parent\n : before.nodeType == 1 && (before.nodeName != \"BR\" || !before.nextSibling) ? before : null;\n if (target)\n return flattenV(singleRect(target, 1), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)\n after = after.nextSibling;\n let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, (supportEmptyRange ? 0 : 1))\n : after.nodeType == 1 ? after : null;\n if (target)\n return flattenV(singleRect(target, -1), true);\n }\n // All else failed, just try to get a rectangle for the target node\n return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0);\n}\nfunction flattenV(rect, left) {\n if (rect.width == 0)\n return rect;\n let x = left ? rect.left : rect.right;\n return { top: rect.top, bottom: rect.bottom, left: x, right: x };\n}\nfunction flattenH(rect, top) {\n if (rect.height == 0)\n return rect;\n let y = top ? rect.top : rect.bottom;\n return { top: y, bottom: y, left: rect.left, right: rect.right };\n}\nfunction withFlushedState(view, state, f) {\n let viewState = view.state, active = view.root.activeElement;\n if (viewState != state)\n view.updateState(state);\n if (active != view.dom)\n view.focus();\n try {\n return f();\n }\n finally {\n if (viewState != state)\n view.updateState(viewState);\n if (active != view.dom && active)\n active.focus();\n }\n}\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n let sel = state.selection;\n let $pos = dir == \"up\" ? sel.$from : sel.$to;\n return withFlushedState(view, state, () => {\n let { node: dom } = view.docView.domFromPos($pos.pos, dir == \"up\" ? -1 : 1);\n for (;;) {\n let nearest = view.docView.nearestDesc(dom, true);\n if (!nearest)\n break;\n if (nearest.node.isBlock) {\n dom = nearest.contentDOM || nearest.dom;\n break;\n }\n dom = nearest.dom.parentNode;\n }\n let coords = coordsAtPos(view, $pos.pos, 1);\n for (let child = dom.firstChild; child; child = child.nextSibling) {\n let boxes;\n if (child.nodeType == 1)\n boxes = child.getClientRects();\n else if (child.nodeType == 3)\n boxes = textRange(child, 0, child.nodeValue.length).getClientRects();\n else\n continue;\n for (let i = 0; i < boxes.length; i++) {\n let box = boxes[i];\n if (box.bottom > box.top + 1 &&\n (dir == \"up\" ? coords.top - box.top > (box.bottom - coords.top) * 2\n : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))\n return false;\n }\n }\n return true;\n });\n}\nconst maybeRTL = /[\\u0590-\\u08ac]/;\nfunction endOfTextblockHorizontal(view, state, dir) {\n let { $head } = state.selection;\n if (!$head.parent.isTextblock)\n return false;\n let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n let sel = view.domSelection();\n if (!sel)\n return $head.pos == $head.start() || $head.pos == $head.end();\n // If the textblock is all LTR, or the browser doesn't support\n // Selection.modify (Edge), fall back to a primitive approach\n if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n return dir == \"left\" || dir == \"backward\" ? atStart : atEnd;\n return withFlushedState(view, state, () => {\n // This is a huge hack, but appears to be the best we can\n // currently do: use `Selection.modify` to move the selection by\n // one character, and see if that moves the cursor out of the\n // textblock (or doesn't move it at all, when at the start/end of\n // the document).\n let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();\n let oldBidiLevel = sel.caretBidiLevel // Only for Firefox\n ;\n sel.modify(\"move\", dir, \"character\");\n let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();\n let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) ||\n (oldNode == newNode && oldOff == newOff);\n // Restore the previous selection\n try {\n sel.collapse(anchorNode, anchorOffset);\n if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)\n sel.extend(oldNode, oldOff);\n }\n catch (_) { }\n if (oldBidiLevel != null)\n sel.caretBidiLevel = oldBidiLevel;\n return result;\n });\n}\nlet cachedState = null;\nlet cachedDir = null;\nlet cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n if (cachedState == state && cachedDir == dir)\n return cachedResult;\n cachedState = state;\n cachedDir = dir;\n return cachedResult = dir == \"up\" || dir == \"down\"\n ? endOfTextblockVertical(view, state, dir)\n : endOfTextblockHorizontal(view, state, dir);\n}\n\n// View descriptions are data structures that describe the DOM that is\n// used to represent the editor's content. They are used for:\n//\n// - Incremental redrawing when the document changes\n//\n// - Figuring out what part of the document a given DOM position\n// corresponds to\n//\n// - Wiring in custom implementations of the editing interface for a\n// given node\n//\n// They form a doubly-linked mutable tree, starting at `view.docView`.\nconst NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nclass ViewDesc {\n constructor(parent, children, dom, \n // This is the node that holds the child views. It may be null for\n // descs that don't have children.\n contentDOM) {\n this.parent = parent;\n this.children = children;\n this.dom = dom;\n this.contentDOM = contentDOM;\n this.dirty = NOT_DIRTY;\n // An expando property on the DOM node provides a link back to its\n // description.\n dom.pmViewDesc = this;\n }\n // Used to check whether a given description corresponds to a\n // widget/mark/node.\n matchesWidget(widget) { return false; }\n matchesMark(mark) { return false; }\n matchesNode(node, outerDeco, innerDeco) { return false; }\n matchesHack(nodeName) { return false; }\n // When parsing in-editor content (in domchange.js), we allow\n // descriptions to determine the parse rules that should be used to\n // parse them.\n parseRule() { return null; }\n // Used by the editor's event handler to ignore events that come\n // from certain descs.\n stopEvent(event) { return false; }\n // The size of the content represented by this desc.\n get size() {\n let size = 0;\n for (let i = 0; i < this.children.length; i++)\n size += this.children[i].size;\n return size;\n }\n // For block nodes, this represents the space taken up by their\n // start/end tokens.\n get border() { return 0; }\n destroy() {\n this.parent = undefined;\n if (this.dom.pmViewDesc == this)\n this.dom.pmViewDesc = undefined;\n for (let i = 0; i < this.children.length; i++)\n this.children[i].destroy();\n }\n posBeforeChild(child) {\n for (let i = 0, pos = this.posAtStart;; i++) {\n let cur = this.children[i];\n if (cur == child)\n return pos;\n pos += cur.size;\n }\n }\n get posBefore() {\n return this.parent.posBeforeChild(this);\n }\n get posAtStart() {\n return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;\n }\n get posAfter() {\n return this.posBefore + this.size;\n }\n get posAtEnd() {\n return this.posAtStart + this.size - 2 * this.border;\n }\n localPosFromDOM(dom, offset, bias) {\n // If the DOM position is in the content, use the child desc after\n // it to figure out a position.\n if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {\n if (bias < 0) {\n let domBefore, desc;\n if (dom == this.contentDOM) {\n domBefore = dom.childNodes[offset - 1];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domBefore = dom.previousSibling;\n }\n while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))\n domBefore = domBefore.previousSibling;\n return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;\n }\n else {\n let domAfter, desc;\n if (dom == this.contentDOM) {\n domAfter = dom.childNodes[offset];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domAfter = dom.nextSibling;\n }\n while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))\n domAfter = domAfter.nextSibling;\n return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;\n }\n }\n // Otherwise, use various heuristics, falling back on the bias\n // parameter, to determine whether to return the position at the\n // start or at the end of this view desc.\n let atEnd;\n if (dom == this.dom && this.contentDOM) {\n atEnd = offset > domIndex(this.contentDOM);\n }\n else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;\n }\n else if (this.dom.firstChild) {\n if (offset == 0)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = false;\n break;\n }\n if (search.previousSibling)\n break;\n }\n if (atEnd == null && offset == dom.childNodes.length)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = true;\n break;\n }\n if (search.nextSibling)\n break;\n }\n }\n return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;\n }\n nearestDesc(dom, onlyNodes = false) {\n for (let first = true, cur = dom; cur; cur = cur.parentNode) {\n let desc = this.getDesc(cur), nodeDOM;\n if (desc && (!onlyNodes || desc.node)) {\n // If dom is outside of this desc's nodeDOM, don't count it.\n if (first && (nodeDOM = desc.nodeDOM) &&\n !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))\n first = false;\n else\n return desc;\n }\n }\n }\n getDesc(dom) {\n let desc = dom.pmViewDesc;\n for (let cur = desc; cur; cur = cur.parent)\n if (cur == this)\n return desc;\n }\n posFromDOM(dom, offset, bias) {\n for (let scan = dom; scan; scan = scan.parentNode) {\n let desc = this.getDesc(scan);\n if (desc)\n return desc.localPosFromDOM(dom, offset, bias);\n }\n return -1;\n }\n // Find the desc for the node after the given pos, if any. (When a\n // parent node overrode rendering, there might not be one.)\n descAt(pos) {\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == pos && end != offset) {\n while (!child.border && child.children.length) {\n for (let i = 0; i < child.children.length; i++) {\n let inner = child.children[i];\n if (inner.size) {\n child = inner;\n break;\n }\n }\n }\n return child;\n }\n if (pos < end)\n return child.descAt(pos - offset - child.border);\n offset = end;\n }\n }\n domFromPos(pos, side) {\n if (!this.contentDOM)\n return { node: this.dom, offset: 0, atom: pos + 1 };\n // First find the position in the child array\n let i = 0, offset = 0;\n for (let curPos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = curPos + child.size;\n if (end > pos || child instanceof TrailingHackViewDesc) {\n offset = pos - curPos;\n break;\n }\n curPos = end;\n }\n // If this points into the middle of a child, call through\n if (offset)\n return this.children[i].domFromPos(offset - this.children[i].border, side);\n // Go back if there were any zero-length widgets with side >= 0 before this point\n for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) { }\n // Scan towards the first useable node\n if (side <= 0) {\n let prev, enter = true;\n for (;; i--, enter = false) {\n prev = i ? this.children[i - 1] : null;\n if (!prev || prev.dom.parentNode == this.contentDOM)\n break;\n }\n if (prev && side && enter && !prev.border && !prev.domAtom)\n return prev.domFromPos(prev.size, side);\n return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };\n }\n else {\n let next, enter = true;\n for (;; i++, enter = false) {\n next = i < this.children.length ? this.children[i] : null;\n if (!next || next.dom.parentNode == this.contentDOM)\n break;\n }\n if (next && enter && !next.border && !next.domAtom)\n return next.domFromPos(0, side);\n return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };\n }\n }\n // Used to find a DOM range in a single parent for a given changed\n // range.\n parseRange(from, to, base = 0) {\n if (this.children.length == 0)\n return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };\n let fromOffset = -1, toOffset = -1;\n for (let offset = base, i = 0;; i++) {\n let child = this.children[i], end = offset + child.size;\n if (fromOffset == -1 && from <= end) {\n let childBase = offset + child.border;\n // FIXME maybe descend mark views to parse a narrower range?\n if (from >= childBase && to <= end - child.border && child.node &&\n child.contentDOM && this.contentDOM.contains(child.contentDOM))\n return child.parseRange(from, to, childBase);\n from = offset;\n for (let j = i; j > 0; j--) {\n let prev = this.children[j - 1];\n if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n fromOffset = domIndex(prev.dom) + 1;\n break;\n }\n from -= prev.size;\n }\n if (fromOffset == -1)\n fromOffset = 0;\n }\n if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n to = end;\n for (let j = i + 1; j < this.children.length; j++) {\n let next = this.children[j];\n if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n toOffset = domIndex(next.dom);\n break;\n }\n to += next.size;\n }\n if (toOffset == -1)\n toOffset = this.contentDOM.childNodes.length;\n break;\n }\n offset = end;\n }\n return { node: this.contentDOM, from, to, fromOffset, toOffset };\n }\n emptyChildAt(side) {\n if (this.border || !this.contentDOM || !this.children.length)\n return false;\n let child = this.children[side < 0 ? 0 : this.children.length - 1];\n return child.size == 0 || child.emptyChildAt(side);\n }\n domAfterPos(pos) {\n let { node, offset } = this.domFromPos(pos, 0);\n if (node.nodeType != 1 || offset == node.childNodes.length)\n throw new RangeError(\"No node after pos \" + pos);\n return node.childNodes[offset];\n }\n // View descs are responsible for setting any selection that falls\n // entirely inside of them, so that custom implementations can do\n // custom things with the selection. Note that this falls apart when\n // a selection starts in such a node and ends in another, in which\n // case we just use whatever domFromPos produces as a best effort.\n setSelection(anchor, head, view, force = false) {\n // If the selection falls entirely in a child, give it to that child\n let from = Math.min(anchor, head), to = Math.max(anchor, head);\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (from > offset && to < end)\n return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);\n offset = end;\n }\n let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);\n let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);\n let domSel = view.root.getSelection();\n let selRange = view.domSelectionRange();\n let brKludge = false;\n // On Firefox, using Selection.collapse to put the cursor after a\n // BR node for some reason doesn't always work (#1073). On Safari,\n // the cursor sometimes inexplicable visually lags behind its\n // reported position in such situations (#1092).\n if ((gecko || safari) && anchor == head) {\n let { node, offset } = anchorDOM;\n if (node.nodeType == 3) {\n brKludge = !!(offset && node.nodeValue[offset - 1] == \"\\n\");\n // Issue #1128\n if (brKludge && offset == node.nodeValue.length) {\n for (let scan = node, after; scan; scan = scan.parentNode) {\n if (after = scan.nextSibling) {\n if (after.nodeName == \"BR\")\n anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };\n break;\n }\n let desc = scan.pmViewDesc;\n if (desc && desc.node && desc.node.isBlock)\n break;\n }\n }\n }\n else {\n let prev = node.childNodes[offset - 1];\n brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n }\n }\n // Firefox can act strangely when the selection is in front of an\n // uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536\n if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {\n let after = selRange.focusNode.childNodes[selRange.focusOffset];\n if (after && after.contentEditable == \"false\")\n force = true;\n }\n if (!(force || brKludge && safari) &&\n isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) &&\n isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))\n return;\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n let domSelExtended = false;\n if ((domSel.extend || anchor == head) && !brKludge) {\n domSel.collapse(anchorDOM.node, anchorDOM.offset);\n try {\n if (anchor != head)\n domSel.extend(headDOM.node, headDOM.offset);\n domSelExtended = true;\n }\n catch (_) {\n // In some cases with Chrome the selection is empty after calling\n // collapse, even when it should be valid. This appears to be a bug, but\n // it is difficult to isolate. If this happens fallback to the old path\n // without using extend.\n // Similarly, this could crash on Safari if the editor is hidden, and\n // there was no selection.\n }\n }\n if (!domSelExtended) {\n if (anchor > head) {\n let tmp = anchorDOM;\n anchorDOM = headDOM;\n headDOM = tmp;\n }\n let range = document.createRange();\n range.setEnd(headDOM.node, headDOM.offset);\n range.setStart(anchorDOM.node, anchorDOM.offset);\n domSel.removeAllRanges();\n domSel.addRange(range);\n }\n }\n ignoreMutation(mutation) {\n return !this.contentDOM && mutation.type != \"selection\";\n }\n get contentLost() {\n return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);\n }\n // Remove a subtree of the element tree that has been touched\n // by a DOM change, so that the next update will redraw it.\n markDirty(from, to) {\n for (let offset = 0, i = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n let startInside = offset + child.border, endInside = end - child.border;\n if (from >= startInside && to <= endInside) {\n this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;\n if (from == startInside && to == endInside &&\n (child.contentLost || child.dom.parentNode != this.contentDOM))\n child.dirty = NODE_DIRTY;\n else\n child.markDirty(from - startInside, to - startInside);\n return;\n }\n else {\n child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length\n ? CONTENT_DIRTY : NODE_DIRTY;\n }\n }\n offset = end;\n }\n this.dirty = CONTENT_DIRTY;\n }\n markParentsDirty() {\n let level = 1;\n for (let node = this.parent; node; node = node.parent, level++) {\n let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n if (node.dirty < dirty)\n node.dirty = dirty;\n }\n }\n get domAtom() { return false; }\n get ignoreForCoords() { return false; }\n isText(text) { return false; }\n}\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nclass WidgetViewDesc extends ViewDesc {\n constructor(parent, widget, view, pos) {\n let self, dom = widget.type.toDOM;\n if (typeof dom == \"function\")\n dom = dom(view, () => {\n if (!self)\n return pos;\n if (self.parent)\n return self.parent.posBeforeChild(self);\n });\n if (!widget.type.spec.raw) {\n if (dom.nodeType != 1) {\n let wrap = document.createElement(\"span\");\n wrap.appendChild(dom);\n dom = wrap;\n }\n dom.contentEditable = \"false\";\n dom.classList.add(\"ProseMirror-widget\");\n }\n super(parent, [], dom, null);\n this.widget = widget;\n this.widget = widget;\n self = this;\n }\n matchesWidget(widget) {\n return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);\n }\n parseRule() { return { ignore: true }; }\n stopEvent(event) {\n let stop = this.widget.spec.stopEvent;\n return stop ? stop(event) : false;\n }\n ignoreMutation(mutation) {\n return mutation.type != \"selection\" || this.widget.spec.ignoreSelection;\n }\n destroy() {\n this.widget.type.destroy(this.dom);\n super.destroy();\n }\n get domAtom() { return true; }\n get side() { return this.widget.type.side; }\n}\nclass CompositionViewDesc extends ViewDesc {\n constructor(parent, dom, textDOM, text) {\n super(parent, [], dom, null);\n this.textDOM = textDOM;\n this.text = text;\n }\n get size() { return this.text.length; }\n localPosFromDOM(dom, offset) {\n if (dom != this.textDOM)\n return this.posAtStart + (offset ? this.size : 0);\n return this.posAtStart + offset;\n }\n domFromPos(pos) {\n return { node: this.textDOM, offset: pos };\n }\n ignoreMutation(mut) {\n return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue;\n }\n}\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nclass MarkViewDesc extends ViewDesc {\n constructor(parent, mark, dom, contentDOM, spec) {\n super(parent, [], dom, contentDOM);\n this.mark = mark;\n this.spec = spec;\n }\n static create(parent, mark, inline, view) {\n let custom = view.nodeViews[mark.type.name];\n let spec = custom && custom(mark, view, inline);\n if (!spec || !spec.dom)\n spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);\n return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);\n }\n parseRule() {\n if ((this.dirty & NODE_DIRTY) || this.mark.type.spec.reparseInView)\n return null;\n return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };\n }\n matchesMark(mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark); }\n markDirty(from, to) {\n super.markDirty(from, to);\n // Move dirty info to nearest node view\n if (this.dirty != NOT_DIRTY) {\n let parent = this.parent;\n while (!parent.node)\n parent = parent.parent;\n if (parent.dirty < this.dirty)\n parent.dirty = this.dirty;\n this.dirty = NOT_DIRTY;\n }\n }\n slice(from, to, view) {\n let copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n let nodes = this.children, size = this.size;\n if (to < size)\n nodes = replaceNodes(nodes, to, size, view);\n if (from > 0)\n nodes = replaceNodes(nodes, 0, from, view);\n for (let i = 0; i < nodes.length; i++)\n nodes[i].parent = copy;\n copy.children = nodes;\n return copy;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n}\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nclass NodeViewDesc extends ViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {\n super(parent, [], dom, contentDOM);\n this.node = node;\n this.outerDeco = outerDeco;\n this.innerDeco = innerDeco;\n this.nodeDOM = nodeDOM;\n }\n // By default, a node is rendered using the `toDOM` method from the\n // node type spec. But client code can use the `nodeViews` spec to\n // supply a custom node view, which can influence various aspects of\n // the way the node works.\n //\n // (Using subclassing for this was intentionally decided against,\n // since it'd require exposing a whole slew of finicky\n // implementation details to the user code that they probably will\n // never need.)\n static create(parent, node, outerDeco, innerDeco, view, pos) {\n let custom = view.nodeViews[node.type.name], descObj;\n let spec = custom && custom(node, view, () => {\n // (This is a function that allows the custom view to find its\n // own position)\n if (!descObj)\n return pos;\n if (descObj.parent)\n return descObj.parent.posBeforeChild(descObj);\n }, outerDeco, innerDeco);\n let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n if (node.isText) {\n if (!dom)\n dom = document.createTextNode(node.text);\n else if (dom.nodeType != 3)\n throw new RangeError(\"Text must be rendered as a DOM text node\");\n }\n else if (!dom) {\n let spec = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);\n ({ dom, contentDOM } = spec);\n }\n if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by
\n if (!dom.hasAttribute(\"contenteditable\"))\n dom.contentEditable = \"false\";\n if (node.type.spec.draggable)\n dom.draggable = true;\n }\n let nodeDOM = dom;\n dom = applyOuterDeco(dom, outerDeco, node);\n if (spec)\n return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);\n else if (node.isText)\n return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view);\n else\n return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);\n }\n parseRule() {\n // Experimental kludge to allow opt-in re-parsing of nodes\n if (this.node.type.spec.reparseInView)\n return null;\n // FIXME the assumption that this can always return the current\n // attrs means that if the user somehow manages to change the\n // attrs in the dom, that won't be picked up. Not entirely sure\n // whether this is a problem\n let rule = { node: this.node.type.name, attrs: this.node.attrs };\n if (this.node.type.whitespace == \"pre\")\n rule.preserveWhitespace = \"full\";\n if (!this.contentDOM) {\n rule.getContent = () => this.node.content;\n }\n else if (!this.contentLost) {\n rule.contentElement = this.contentDOM;\n }\n else {\n // Chrome likes to randomly recreate parent nodes when\n // backspacing things. When that happens, this tries to find the\n // new parent.\n for (let i = this.children.length - 1; i >= 0; i--) {\n let child = this.children[i];\n if (this.dom.contains(child.dom.parentNode)) {\n rule.contentElement = child.dom.parentNode;\n break;\n }\n }\n if (!rule.contentElement)\n rule.getContent = () => Fragment.empty;\n }\n return rule;\n }\n matchesNode(node, outerDeco, innerDeco) {\n return this.dirty == NOT_DIRTY && node.eq(this.node) &&\n sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);\n }\n get size() { return this.node.nodeSize; }\n get border() { return this.node.isLeaf ? 0 : 1; }\n // Syncs `this.children` to match `this.node.content` and the local\n // decorations, possibly introducing nesting for marks. Then, in a\n // separate step, syncs the DOM inside `this.contentDOM` to\n // `this.children`.\n updateChildren(view, pos) {\n let inline = this.node.inlineContent, off = pos;\n let composition = view.composing ? this.localCompositionInfo(view, pos) : null;\n let localComposition = composition && composition.pos > -1 ? composition : null;\n let compositionInChild = composition && composition.pos < 0;\n let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);\n iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {\n if (widget.spec.marks)\n updater.syncToMarks(widget.spec.marks, inline, view);\n else if (widget.type.side >= 0 && !insideNode)\n updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view);\n // If the next node is a desc matching this widget, reuse it,\n // otherwise insert the widget as a new view desc.\n updater.placeWidget(widget, view, off);\n }, (child, outerDeco, innerDeco, i) => {\n // Make sure the wrapping mark descs match the node's marks.\n updater.syncToMarks(child.marks, inline, view);\n // Try several strategies for drawing this node\n let compIndex;\n if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;\n else if (compositionInChild && view.state.selection.from > off &&\n view.state.selection.to < off + child.nodeSize &&\n (compIndex = updater.findIndexWithChild(composition.node)) > -1 &&\n updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;\n else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;\n else {\n // Add it as a new view\n updater.addNode(child, outerDeco, innerDeco, view, off);\n }\n off += child.nodeSize;\n });\n // Drop all remaining descs after the current position.\n updater.syncToMarks([], inline, view);\n if (this.node.isTextblock)\n updater.addTextblockHacks();\n updater.destroyRest();\n // Sync the DOM if anything changed\n if (updater.changed || this.dirty == CONTENT_DIRTY) {\n // May have to protect focused DOM from being changed if a composition is active\n if (localComposition)\n this.protectLocalComposition(view, localComposition);\n renderDescs(this.contentDOM, this.children, view);\n if (ios)\n iosHacks(this.dom);\n }\n }\n localCompositionInfo(view, pos) {\n // Only do something if both the selection and a focused text node\n // are inside of this node\n let { from, to } = view.state.selection;\n if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size)\n return null;\n let textNode = view.input.compositionNode;\n if (!textNode || !this.dom.contains(textNode.parentNode))\n return null;\n if (this.node.inlineContent) {\n // Find the text in the focused node in the node, stop if it's not\n // there (may have been modified through other means, in which\n // case it should overwritten)\n let text = textNode.nodeValue;\n let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n return textPos < 0 ? null : { node: textNode, pos: textPos, text };\n }\n else {\n return { node: textNode, pos: -1, text: \"\" };\n }\n }\n protectLocalComposition(view, { node, pos, text }) {\n // The node is already part of a local view desc, leave it there\n if (this.getDesc(node))\n return;\n // Create a composition view for the orphaned nodes\n let topNode = node;\n for (;; topNode = topNode.parentNode) {\n if (topNode.parentNode == this.contentDOM)\n break;\n while (topNode.previousSibling)\n topNode.parentNode.removeChild(topNode.previousSibling);\n while (topNode.nextSibling)\n topNode.parentNode.removeChild(topNode.nextSibling);\n if (topNode.pmViewDesc)\n topNode.pmViewDesc = undefined;\n }\n let desc = new CompositionViewDesc(this, topNode, node, text);\n view.input.compositionNodes.push(desc);\n // Patch up this.children to contain the composition view\n this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n }\n // If this desc must be updated to match the given node decoration,\n // do so and return true.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY ||\n !node.sameMarkup(this.node))\n return false;\n this.updateInner(node, outerDeco, innerDeco, view);\n return true;\n }\n updateInner(node, outerDeco, innerDeco, view) {\n this.updateOuterDeco(outerDeco);\n this.node = node;\n this.innerDeco = innerDeco;\n if (this.contentDOM)\n this.updateChildren(view, this.posAtStart);\n this.dirty = NOT_DIRTY;\n }\n updateOuterDeco(outerDeco) {\n if (sameOuterDeco(outerDeco, this.outerDeco))\n return;\n let needsWrap = this.nodeDOM.nodeType != 1;\n let oldDOM = this.dom;\n this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));\n if (this.dom != oldDOM) {\n oldDOM.pmViewDesc = undefined;\n this.dom.pmViewDesc = this;\n }\n this.outerDeco = outerDeco;\n }\n // Mark this node as being the selected node.\n selectNode() {\n if (this.nodeDOM.nodeType == 1)\n this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.dom.draggable = true;\n }\n // Remove selected node marking from this node.\n deselectNode() {\n if (this.nodeDOM.nodeType == 1) {\n this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.dom.removeAttribute(\"draggable\");\n }\n }\n get domAtom() { return this.node.isAtom; }\n}\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view) {\n applyOuterDeco(dom, outerDeco, doc);\n let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom, view, 0);\n if (docView.contentDOM)\n docView.updateChildren(view, 0);\n return docView;\n}\nclass TextViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {\n super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);\n }\n parseRule() {\n let skip = this.nodeDOM.parentNode;\n while (skip && skip != this.dom && !skip.pmIsDeco)\n skip = skip.parentNode;\n return { skip: (skip || true) };\n }\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n !node.sameMarkup(this.node))\n return false;\n this.updateOuterDeco(outerDeco);\n if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n this.nodeDOM.nodeValue = node.text;\n if (view.trackWrites == this.nodeDOM)\n view.trackWrites = null;\n }\n this.node = node;\n this.dirty = NOT_DIRTY;\n return true;\n }\n inParent() {\n let parentDOM = this.parent.contentDOM;\n for (let n = this.nodeDOM; n; n = n.parentNode)\n if (n == parentDOM)\n return true;\n return false;\n }\n domFromPos(pos) {\n return { node: this.nodeDOM, offset: pos };\n }\n localPosFromDOM(dom, offset, bias) {\n if (dom == this.nodeDOM)\n return this.posAtStart + Math.min(offset, this.node.text.length);\n return super.localPosFromDOM(dom, offset, bias);\n }\n ignoreMutation(mutation) {\n return mutation.type != \"characterData\" && mutation.type != \"selection\";\n }\n slice(from, to, view) {\n let node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view);\n }\n markDirty(from, to) {\n super.markDirty(from, to);\n if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length))\n this.dirty = NODE_DIRTY;\n }\n get domAtom() { return false; }\n isText(text) { return this.node.text == text; }\n}\n// A dummy desc used to tag trailing BR or IMG nodes created to work\n// around contentEditable terribleness.\nclass TrailingHackViewDesc extends ViewDesc {\n parseRule() { return { ignore: true }; }\n matchesHack(nodeName) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; }\n get domAtom() { return true; }\n get ignoreForCoords() { return this.dom.nodeName == \"IMG\"; }\n}\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nclass CustomNodeViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {\n super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);\n this.spec = spec;\n }\n // A custom `update` method gets to decide whether the update goes\n // through. If it does, and there's a `contentDOM` node, our logic\n // updates the children.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY)\n return false;\n if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {\n let result = this.spec.update(node, outerDeco, innerDeco);\n if (result)\n this.updateInner(node, outerDeco, innerDeco, view);\n return result;\n }\n else if (!this.contentDOM && !node.isLeaf) {\n return false;\n }\n else {\n return super.update(node, outerDeco, innerDeco, view);\n }\n }\n selectNode() {\n this.spec.selectNode ? this.spec.selectNode() : super.selectNode();\n }\n deselectNode() {\n this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();\n }\n setSelection(anchor, head, view, force) {\n this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root)\n : super.setSelection(anchor, head, view, force);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n stopEvent(event) {\n return this.spec.stopEvent ? this.spec.stopEvent(event) : false;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n}\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n let dom = parentDOM.firstChild, written = false;\n for (let i = 0; i < descs.length; i++) {\n let desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) {\n dom = rm(dom);\n written = true;\n }\n dom = dom.nextSibling;\n }\n else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n let pos = dom ? dom.previousSibling : parentDOM.lastChild;\n renderDescs(desc.contentDOM, desc.children, view);\n dom = pos ? pos.nextSibling : parentDOM.firstChild;\n }\n }\n while (dom) {\n dom = rm(dom);\n written = true;\n }\n if (written && view.trackWrites == parentDOM)\n view.trackWrites = null;\n}\nconst OuterDecoLevel = function (nodeName) {\n if (nodeName)\n this.nodeName = nodeName;\n};\nOuterDecoLevel.prototype = Object.create(null);\nconst noDeco = [new OuterDecoLevel];\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n if (outerDeco.length == 0)\n return noDeco;\n let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n for (let i = 0; i < outerDeco.length; i++) {\n let attrs = outerDeco[i].type.attrs;\n if (!attrs)\n continue;\n if (attrs.nodeName)\n result.push(top = new OuterDecoLevel(attrs.nodeName));\n for (let name in attrs) {\n let val = attrs[name];\n if (val == null)\n continue;\n if (needsWrap && result.length == 1)\n result.push(top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\"));\n if (name == \"class\")\n top.class = (top.class ? top.class + \" \" : \"\") + val;\n else if (name == \"style\")\n top.style = (top.style ? top.style + \";\" : \"\") + val;\n else if (name != \"nodeName\")\n top[name] = val;\n }\n }\n return result;\n}\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n // Shortcut for trivial case\n if (prevComputed == noDeco && curComputed == noDeco)\n return nodeDOM;\n let curDOM = nodeDOM;\n for (let i = 0; i < curComputed.length; i++) {\n let deco = curComputed[i], prev = prevComputed[i];\n if (i) {\n let parent;\n if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {\n curDOM = parent;\n }\n else {\n parent = document.createElement(deco.nodeName);\n parent.pmIsDeco = true;\n parent.appendChild(curDOM);\n prev = noDeco[0];\n curDOM = parent;\n }\n }\n patchAttributes(curDOM, prev || noDeco[0], deco);\n }\n return curDOM;\n}\nfunction patchAttributes(dom, prev, cur) {\n for (let name in prev)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n dom.removeAttribute(name);\n for (let name in cur)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && cur[name] != prev[name])\n dom.setAttribute(name, cur[name]);\n if (prev.class != cur.class) {\n let prevList = prev.class ? prev.class.split(\" \").filter(Boolean) : [];\n let curList = cur.class ? cur.class.split(\" \").filter(Boolean) : [];\n for (let i = 0; i < prevList.length; i++)\n if (curList.indexOf(prevList[i]) == -1)\n dom.classList.remove(prevList[i]);\n for (let i = 0; i < curList.length; i++)\n if (prevList.indexOf(curList[i]) == -1)\n dom.classList.add(curList[i]);\n if (dom.classList.length == 0)\n dom.removeAttribute(\"class\");\n }\n if (prev.style != cur.style) {\n if (prev.style) {\n let prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n while (m = prop.exec(prev.style))\n dom.style.removeProperty(m[1]);\n }\n if (cur.style)\n dom.style.cssText += cur.style;\n }\n}\nfunction applyOuterDeco(dom, deco, node) {\n return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1));\n}\nfunction sameOuterDeco(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].type.eq(b[i].type))\n return false;\n return true;\n}\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n let next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next;\n}\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nclass ViewTreeUpdater {\n constructor(top, lock, view) {\n this.lock = lock;\n this.view = view;\n // Index into `this.top`'s child array, represents the current\n // update position.\n this.index = 0;\n // When entering a mark, the current top and index are pushed\n // onto this.\n this.stack = [];\n // Tracks whether anything was changed\n this.changed = false;\n this.top = top;\n this.preMatch = preMatch(top.node.content, top);\n }\n // Destroy and remove the children between the given indices in\n // `this.top`.\n destroyBetween(start, end) {\n if (start == end)\n return;\n for (let i = start; i < end; i++)\n this.top.children[i].destroy();\n this.top.children.splice(start, end - start);\n this.changed = true;\n }\n // Destroy all remaining children in `this.top`.\n destroyRest() {\n this.destroyBetween(this.index, this.top.children.length);\n }\n // Sync the current stack of mark descs with the given array of\n // marks, reusing existing mark descs when possible.\n syncToMarks(marks, inline, view) {\n let keep = 0, depth = this.stack.length >> 1;\n let maxKeep = Math.min(depth, marks.length);\n while (keep < maxKeep &&\n (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1])\n .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n keep++;\n while (keep < depth) {\n this.destroyRest();\n this.top.dirty = NOT_DIRTY;\n this.index = this.stack.pop();\n this.top = this.stack.pop();\n depth--;\n }\n while (depth < marks.length) {\n this.stack.push(this.top, this.index + 1);\n let found = -1;\n for (let i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) {\n let next = this.top.children[i];\n if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {\n found = i;\n break;\n }\n }\n if (found > -1) {\n if (found > this.index) {\n this.changed = true;\n this.destroyBetween(this.index, found);\n }\n this.top = this.top.children[this.index];\n }\n else {\n let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n this.top.children.splice(this.index, 0, markDesc);\n this.top = markDesc;\n this.changed = true;\n }\n this.index = 0;\n depth++;\n }\n }\n // Try to find a node desc matching the given data. Skip over it and\n // return true when successful.\n findNodeMatch(node, outerDeco, innerDeco, index) {\n let found = -1, targetDesc;\n if (index >= this.preMatch.index &&\n (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&\n targetDesc.matchesNode(node, outerDeco, innerDeco)) {\n found = this.top.children.indexOf(targetDesc, this.index);\n }\n else {\n for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {\n let child = this.top.children[i];\n if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {\n found = i;\n break;\n }\n }\n }\n if (found < 0)\n return false;\n this.destroyBetween(this.index, found);\n this.index++;\n return true;\n }\n updateNodeAt(node, outerDeco, innerDeco, index, view) {\n let child = this.top.children[index];\n if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)\n child.dirty = CONTENT_DIRTY;\n if (!child.update(node, outerDeco, innerDeco, view))\n return false;\n this.destroyBetween(this.index, index);\n this.index++;\n return true;\n }\n findIndexWithChild(domNode) {\n for (;;) {\n let parent = domNode.parentNode;\n if (!parent)\n return -1;\n if (parent == this.top.contentDOM) {\n let desc = domNode.pmViewDesc;\n if (desc)\n for (let i = this.index; i < this.top.children.length; i++) {\n if (this.top.children[i] == desc)\n return i;\n }\n return -1;\n }\n domNode = parent;\n }\n }\n // Try to update the next node, if any, to the given data. Checks\n // pre-matches to avoid overwriting nodes that could still be used.\n updateNextNode(node, outerDeco, innerDeco, view, index, pos) {\n for (let i = this.index; i < this.top.children.length; i++) {\n let next = this.top.children[i];\n if (next instanceof NodeViewDesc) {\n let preMatch = this.preMatch.matched.get(next);\n if (preMatch != null && preMatch != index)\n return false;\n let nextDOM = next.dom, updated;\n // Can't update if nextDOM is or contains this.lock, except if\n // it's a text node whose content already matches the new text\n // and whose decorations match the new ones.\n let locked = this.isLocked(nextDOM) &&\n !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));\n if (!locked && next.update(node, outerDeco, innerDeco, view)) {\n this.destroyBetween(this.index, i);\n if (next.dom != nextDOM)\n this.changed = true;\n this.index++;\n return true;\n }\n else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {\n this.destroyBetween(this.index, i);\n this.top.children[this.index] = updated;\n if (updated.contentDOM) {\n updated.dirty = CONTENT_DIRTY;\n updated.updateChildren(view, pos + 1);\n updated.dirty = NOT_DIRTY;\n }\n this.changed = true;\n this.index++;\n return true;\n }\n break;\n }\n }\n return false;\n }\n // When a node with content is replaced by a different node with\n // identical content, move over its children.\n recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {\n if (next.dirty || node.isAtom || !next.children.length ||\n !next.node.content.eq(node.content) ||\n !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))\n return null;\n let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (wrapper.contentDOM) {\n wrapper.children = next.children;\n next.children = [];\n for (let ch of wrapper.children)\n ch.parent = wrapper;\n }\n next.destroy();\n return wrapper;\n }\n // Insert the node as a newly created node desc.\n addNode(node, outerDeco, innerDeco, view, pos) {\n let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (desc.contentDOM)\n desc.updateChildren(view, pos + 1);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n placeWidget(widget, view, pos) {\n let next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n if (next && next.matchesWidget(widget) &&\n (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n this.index++;\n }\n else {\n let desc = new WidgetViewDesc(this.top, widget, view, pos);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n }\n // Make sure a textblock looks and behaves correctly in\n // contentEditable.\n addTextblockHacks() {\n let lastChild = this.top.children[this.index - 1], parent = this.top;\n while (lastChild instanceof MarkViewDesc) {\n parent = lastChild;\n lastChild = parent.children[parent.children.length - 1];\n }\n if (!lastChild || // Empty textblock\n !(lastChild instanceof TextViewDesc) ||\n /\\n$/.test(lastChild.node.text) ||\n (this.view.requiresGeckoHackNode && /\\s$/.test(lastChild.node.text))) {\n // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)\n if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == \"false\")\n this.addHackNode(\"IMG\", parent);\n this.addHackNode(\"BR\", this.top);\n }\n }\n addHackNode(nodeName, parent) {\n if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {\n this.index++;\n }\n else {\n let dom = document.createElement(nodeName);\n if (nodeName == \"IMG\") {\n dom.className = \"ProseMirror-separator\";\n dom.alt = \"\";\n }\n if (nodeName == \"BR\")\n dom.className = \"ProseMirror-trailingBreak\";\n let hack = new TrailingHackViewDesc(this.top, [], dom, null);\n if (parent != this.top)\n parent.children.push(hack);\n else\n parent.children.splice(this.index++, 0, hack);\n this.changed = true;\n }\n }\n isLocked(node) {\n return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode));\n }\n}\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing those\n// for other nodes. Returns the fragment index of the first node that\n// is part of the sequence of matched nodes at the end of the\n// fragment.\nfunction preMatch(frag, parentDesc) {\n let curDesc = parentDesc, descI = curDesc.children.length;\n let fI = frag.childCount, matched = new Map, matches = [];\n outer: while (fI > 0) {\n let desc;\n for (;;) {\n if (descI) {\n let next = curDesc.children[descI - 1];\n if (next instanceof MarkViewDesc) {\n curDesc = next;\n descI = next.children.length;\n }\n else {\n desc = next;\n descI--;\n break;\n }\n }\n else if (curDesc == parentDesc) {\n break outer;\n }\n else {\n // FIXME\n descI = curDesc.parent.children.indexOf(curDesc);\n curDesc = curDesc.parent;\n }\n }\n let node = desc.node;\n if (!node)\n continue;\n if (node != frag.child(fI - 1))\n break;\n --fI;\n matched.set(desc, fI);\n matches.push(desc);\n }\n return { index: fI, matched, matches: matches.reverse() };\n}\nfunction compareSide(a, b) {\n return a.type.side - b.type.side;\n}\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n let locals = deco.locals(parent), offset = 0;\n // Simple, cheap variant for when there are no local decorations\n if (locals.length == 0) {\n for (let i = 0; i < parent.childCount; i++) {\n let child = parent.child(i);\n onNode(child, locals, deco.forChild(offset, child), i);\n offset += child.nodeSize;\n }\n return;\n }\n let decoIndex = 0, active = [], restNode = null;\n for (let parentIndex = 0;;) {\n let widget, widgets;\n while (decoIndex < locals.length && locals[decoIndex].to == offset) {\n let next = locals[decoIndex++];\n if (next.widget) {\n if (!widget)\n widget = next;\n else\n (widgets || (widgets = [widget])).push(next);\n }\n }\n if (widget) {\n if (widgets) {\n widgets.sort(compareSide);\n for (let i = 0; i < widgets.length; i++)\n onWidget(widgets[i], parentIndex, !!restNode);\n }\n else {\n onWidget(widget, parentIndex, !!restNode);\n }\n }\n let child, index;\n if (restNode) {\n index = -1;\n child = restNode;\n restNode = null;\n }\n else if (parentIndex < parent.childCount) {\n index = parentIndex;\n child = parent.child(parentIndex++);\n }\n else {\n break;\n }\n for (let i = 0; i < active.length; i++)\n if (active[i].to <= offset)\n active.splice(i--, 1);\n while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n active.push(locals[decoIndex++]);\n let end = offset + child.nodeSize;\n if (child.isText) {\n let cutAt = end;\n if (decoIndex < locals.length && locals[decoIndex].from < cutAt)\n cutAt = locals[decoIndex].from;\n for (let i = 0; i < active.length; i++)\n if (active[i].to < cutAt)\n cutAt = active[i].to;\n if (cutAt < end) {\n restNode = child.cut(cutAt - offset);\n child = child.cut(0, cutAt - offset);\n end = cutAt;\n index = -1;\n }\n }\n else {\n while (decoIndex < locals.length && locals[decoIndex].to < end)\n decoIndex++;\n }\n let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice();\n onNode(child, outerDeco, deco.forChild(offset, child), index);\n offset = end;\n }\n}\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n let oldCSS = dom.style.cssText;\n dom.style.cssText = oldCSS + \"; list-style: square !important\";\n window.getComputedStyle(dom).listStyle;\n dom.style.cssText = oldCSS;\n }\n}\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n let child = frag.child(i++), childStart = pos;\n pos += child.nodeSize;\n if (!child.isText)\n continue;\n let str = child.text;\n while (i < frag.childCount) {\n let next = frag.child(i++);\n pos += next.nodeSize;\n if (!next.isText)\n break;\n str += next.text;\n }\n if (pos >= from) {\n if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)\n return to - text.length;\n let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1;\n if (found >= 0 && found + text.length + childStart >= from)\n return childStart + found;\n if (from == to && str.length >= (to + text.length) - childStart &&\n str.slice(to - childStart, to - childStart + text.length) == text)\n return to;\n }\n }\n return -1;\n}\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n let result = [];\n for (let i = 0, off = 0; i < nodes.length; i++) {\n let child = nodes[i], start = off, end = off += child.size;\n if (start >= to || end <= from) {\n result.push(child);\n }\n else {\n if (start < from)\n result.push(child.slice(0, from - start, view));\n if (replacement) {\n result.push(replacement);\n replacement = undefined;\n }\n if (end > to)\n result.push(child.slice(to - start, child.size, view));\n }\n }\n return result;\n}\n\nfunction selectionFromDOM(view, origin = null) {\n let domSel = view.domSelectionRange(), doc = view.state.doc;\n if (!domSel.focusNode)\n return null;\n let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);\n if (head < 0)\n return null;\n let $head = doc.resolve(head), anchor, selection;\n if (selectionCollapsed(domSel)) {\n anchor = head;\n while (nearestDesc && !nearestDesc.node)\n nearestDesc = nearestDesc.parent;\n let nearestDescNode = nearestDesc.node;\n if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent\n && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n let pos = nearestDesc.posBefore;\n selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n }\n }\n else {\n if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {\n let min = head, max = head;\n for (let i = 0; i < domSel.rangeCount; i++) {\n let range = domSel.getRangeAt(i);\n min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));\n max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));\n }\n if (min < 0)\n return null;\n [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];\n $head = doc.resolve(head);\n }\n else {\n anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);\n }\n if (anchor < 0)\n return null;\n }\n let $anchor = doc.resolve(anchor);\n if (!selection) {\n let bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n selection = selectionBetween(view, $anchor, $head, bias);\n }\n return selection;\n}\nfunction editorOwnsSelection(view) {\n return view.editable ? view.hasFocus() :\n hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);\n}\nfunction selectionToDOM(view, force = false) {\n let sel = view.state.selection;\n syncNodeSelection(view, sel);\n if (!editorOwnsSelection(view))\n return;\n // The delayed drag selection causes issues with Cell Selections\n // in Safari. And the drag selection delay is to workarond issues\n // which only present in Chrome.\n if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) {\n let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;\n if (domSel.anchorNode && curSel.anchorNode &&\n isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {\n view.input.mouseDown.delayedSelectionSync = true;\n view.domObserver.setCurSelection();\n return;\n }\n }\n view.domObserver.disconnectSelection();\n if (view.cursorWrapper) {\n selectCursorWrapper(view);\n }\n else {\n let { anchor, head } = sel, resetEditableFrom, resetEditableTo;\n if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n if (!sel.$from.parent.inlineContent)\n resetEditableFrom = temporarilyEditableNear(view, sel.from);\n if (!sel.empty && !sel.$from.parent.inlineContent)\n resetEditableTo = temporarilyEditableNear(view, sel.to);\n }\n view.docView.setSelection(anchor, head, view, force);\n if (brokenSelectBetweenUneditable) {\n if (resetEditableFrom)\n resetEditable(resetEditableFrom);\n if (resetEditableTo)\n resetEditable(resetEditableTo);\n }\n if (sel.visible) {\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }\n else {\n view.dom.classList.add(\"ProseMirror-hideselection\");\n if (\"onselectionchange\" in document)\n removeClassOnSelectionChange(view);\n }\n }\n view.domObserver.setCurSelection();\n view.domObserver.connectSelection();\n}\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\nconst brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;\nfunction temporarilyEditableNear(view, pos) {\n let { node, offset } = view.docView.domFromPos(pos, 0);\n let after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n let before = offset ? node.childNodes[offset - 1] : null;\n if (safari && after && after.contentEditable == \"false\")\n return setEditable(after);\n if ((!after || after.contentEditable == \"false\") &&\n (!before || before.contentEditable == \"false\")) {\n if (after)\n return setEditable(after);\n else if (before)\n return setEditable(before);\n }\n}\nfunction setEditable(element) {\n element.contentEditable = \"true\";\n if (safari && element.draggable) {\n element.draggable = false;\n element.wasDraggable = true;\n }\n return element;\n}\nfunction resetEditable(element) {\n element.contentEditable = \"false\";\n if (element.wasDraggable) {\n element.draggable = true;\n element.wasDraggable = null;\n }\n}\nfunction removeClassOnSelectionChange(view) {\n let doc = view.dom.ownerDocument;\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n let domSel = view.domSelectionRange();\n let node = domSel.anchorNode, offset = domSel.anchorOffset;\n doc.addEventListener(\"selectionchange\", view.input.hideSelectionGuard = () => {\n if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n setTimeout(() => {\n if (!editorOwnsSelection(view) || view.state.selection.visible)\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }, 20);\n }\n });\n}\nfunction selectCursorWrapper(view) {\n let domSel = view.domSelection(), range = document.createRange();\n if (!domSel)\n return;\n let node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n if (img)\n range.setStart(node.parentNode, domIndex(node) + 1);\n else\n range.setStart(node, 0);\n range.collapse(true);\n domSel.removeAllRanges();\n domSel.addRange(range);\n // Kludge to kill 'control selection' in IE11 when selecting an\n // invisible cursor wrapper, since that would result in those weird\n // resize handles and a selection that considers the absolutely\n // positioned wrapper, rather than the root editable node, the\n // focused element.\n if (!img && !view.state.selection.visible && ie && ie_version <= 11) {\n node.disabled = true;\n node.disabled = false;\n }\n}\nfunction syncNodeSelection(view, sel) {\n if (sel instanceof NodeSelection) {\n let desc = view.docView.descAt(sel.from);\n if (desc != view.lastSelectedViewDesc) {\n clearNodeSelection(view);\n if (desc)\n desc.selectNode();\n view.lastSelectedViewDesc = desc;\n }\n }\n else {\n clearNodeSelection(view);\n }\n}\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n if (view.lastSelectedViewDesc) {\n if (view.lastSelectedViewDesc.parent)\n view.lastSelectedViewDesc.deselectNode();\n view.lastSelectedViewDesc = undefined;\n }\n}\nfunction selectionBetween(view, $anchor, $head, bias) {\n return view.someProp(\"createSelectionBetween\", f => f(view, $anchor, $head))\n || TextSelection.between($anchor, $head, bias);\n}\nfunction hasFocusAndSelection(view) {\n if (view.editable && !view.hasFocus())\n return false;\n return hasSelection(view);\n}\nfunction hasSelection(view) {\n let sel = view.domSelectionRange();\n if (!sel.anchorNode)\n return false;\n try {\n // Firefox will raise 'permission denied' errors when accessing\n // properties of `sel.anchorNode` when it's in a generated CSS\n // element.\n return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) &&\n (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));\n }\n catch (_) {\n return false;\n }\n}\nfunction anchorInRightPlace(view) {\n let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);\n let domSel = view.domSelectionRange();\n return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);\n}\n\nfunction moveSelectionBlock(state, dir) {\n let { $anchor, $head } = state.selection;\n let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n return $start && Selection.findFrom($start, dir);\n}\nfunction apply(view, sel) {\n view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n return true;\n}\nfunction selectHorizontally(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection) {\n if (mods.indexOf(\"s\") > -1) {\n let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;\n if (!node || node.isText || !node.isLeaf)\n return false;\n let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));\n return apply(view, new TextSelection(sel.$anchor, $newHead));\n }\n else if (!sel.empty) {\n return false;\n }\n else if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n return false;\n }\n else if (!(mac && mods.indexOf(\"m\") > -1)) {\n let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n if (!node || node.isText)\n return false;\n let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))\n return false;\n if (NodeSelection.isSelectable(node)) {\n return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));\n }\n else if (webkit) {\n // Chrome and Safari will introduce extra pointless cursor\n // positions around inline uneditable nodes, so we have to\n // take over and move the cursor past them (#937)\n return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));\n }\n else {\n return false;\n }\n }\n }\n else if (sel instanceof NodeSelection && sel.node.isInline) {\n return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));\n }\n else {\n let next = moveSelectionBlock(view.state, dir);\n if (next)\n return apply(view, next);\n return false;\n }\n}\nfunction nodeLen(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction isIgnorable(dom, dir) {\n let desc = dom.pmViewDesc;\n return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != \"BR\");\n}\nfunction skipIgnoredNodes(view, dir) {\n return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);\n}\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesBefore(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let moveNode, moveOffset, force = false;\n // Gecko will do odd things when the selection is directly in front\n // of a non-editable node, so in that case, move it into the next\n // node if possible. Issue prosemirror/prosemirror#832.\n if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1))\n force = true;\n for (;;) {\n if (offset > 0) {\n if (node.nodeType != 1) {\n break;\n }\n else {\n let before = node.childNodes[offset - 1];\n if (isIgnorable(before, -1)) {\n moveNode = node;\n moveOffset = --offset;\n }\n else if (before.nodeType == 3) {\n node = before;\n offset = node.nodeValue.length;\n }\n else\n break;\n }\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let prev = node.previousSibling;\n while (prev && isIgnorable(prev, -1)) {\n moveNode = node.parentNode;\n moveOffset = domIndex(prev);\n prev = prev.previousSibling;\n }\n if (!prev) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = 0;\n }\n else {\n node = prev;\n offset = nodeLen(node);\n }\n }\n }\n if (force)\n setSelFocus(view, node, offset);\n else if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesAfter(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let len = nodeLen(node);\n let moveNode, moveOffset;\n for (;;) {\n if (offset < len) {\n if (node.nodeType != 1)\n break;\n let after = node.childNodes[offset];\n if (isIgnorable(after, 1)) {\n moveNode = node;\n moveOffset = ++offset;\n }\n else\n break;\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let next = node.nextSibling;\n while (next && isIgnorable(next, 1)) {\n moveNode = next.parentNode;\n moveOffset = domIndex(next) + 1;\n next = next.nextSibling;\n }\n if (!next) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = len = 0;\n }\n else {\n node = next;\n offset = 0;\n len = nodeLen(node);\n }\n }\n }\n if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\nfunction isBlockNode(dom) {\n let desc = dom.pmViewDesc;\n return desc && desc.node && desc.node.isBlock;\n}\nfunction textNodeAfter(node, offset) {\n while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n while (node && offset < node.childNodes.length) {\n let next = node.childNodes[offset];\n if (next.nodeType == 3)\n return next;\n if (next.nodeType == 1 && next.contentEditable == \"false\")\n break;\n node = next;\n offset = 0;\n }\n}\nfunction textNodeBefore(node, offset) {\n while (node && !offset && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n while (node && offset) {\n let next = node.childNodes[offset - 1];\n if (next.nodeType == 3)\n return next;\n if (next.nodeType == 1 && next.contentEditable == \"false\")\n break;\n node = next;\n offset = node.childNodes.length;\n }\n}\nfunction setSelFocus(view, node, offset) {\n if (node.nodeType != 3) {\n let before, after;\n if (after = textNodeAfter(node, offset)) {\n node = after;\n offset = 0;\n }\n else if (before = textNodeBefore(node, offset)) {\n node = before;\n offset = before.nodeValue.length;\n }\n }\n let sel = view.domSelection();\n if (!sel)\n return;\n if (selectionCollapsed(sel)) {\n let range = document.createRange();\n range.setEnd(node, offset);\n range.setStart(node, offset);\n sel.removeAllRanges();\n sel.addRange(range);\n }\n else if (sel.extend) {\n sel.extend(node, offset);\n }\n view.domObserver.setCurSelection();\n let { state } = view;\n // If no state update ends up happening, reset the selection.\n setTimeout(() => {\n if (view.state == state)\n selectionToDOM(view);\n }, 50);\n}\nfunction findDirection(view, pos) {\n let $pos = view.state.doc.resolve(pos);\n if (!(chrome || windows) && $pos.parent.inlineContent) {\n let coords = view.coordsAtPos(pos);\n if (pos > $pos.start()) {\n let before = view.coordsAtPos(pos - 1);\n let mid = (before.top + before.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)\n return before.left < coords.left ? \"ltr\" : \"rtl\";\n }\n if (pos < $pos.end()) {\n let after = view.coordsAtPos(pos + 1);\n let mid = (after.top + after.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)\n return after.left > coords.left ? \"ltr\" : \"rtl\";\n }\n }\n let computed = getComputedStyle(view.dom).direction;\n return computed == \"rtl\" ? \"rtl\" : \"ltr\";\n}\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1)\n return false;\n if (mac && mods.indexOf(\"m\") > -1)\n return false;\n let { $from, $to } = sel;\n if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n }\n if (!$from.parent.inlineContent) {\n let side = dir < 0 ? $from : $to;\n let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);\n return beyond ? apply(view, beyond) : false;\n }\n return false;\n}\nfunction stopNativeHorizontalDelete(view, dir) {\n if (!(view.state.selection instanceof TextSelection))\n return true;\n let { $head, $anchor, empty } = view.state.selection;\n if (!$head.sameParent($anchor))\n return true;\n if (!empty)\n return false;\n if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\"))\n return true;\n let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n if (nextNode && !nextNode.isText) {\n let tr = view.state.tr;\n if (dir < 0)\n tr.delete($head.pos - nextNode.nodeSize, $head.pos);\n else\n tr.delete($head.pos, $head.pos + nextNode.nodeSize);\n view.dispatch(tr);\n return true;\n }\n return false;\n}\nfunction switchEditable(view, node, state) {\n view.domObserver.stop();\n node.contentEditable = state;\n view.domObserver.start();\n}\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n if (!safari || view.state.selection.$head.parentOffset > 0)\n return false;\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 &&\n focusNode.firstChild && focusNode.firstChild.contentEditable == \"false\") {\n let child = focusNode.firstChild;\n switchEditable(view, child, \"true\");\n setTimeout(() => switchEditable(view, child, \"false\"), 20);\n }\n return false;\n}\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\nfunction getMods(event) {\n let result = \"\";\n if (event.ctrlKey)\n result += \"c\";\n if (event.metaKey)\n result += \"m\";\n if (event.altKey)\n result += \"a\";\n if (event.shiftKey)\n result += \"s\";\n return result;\n}\nfunction captureKeyDown(view, event) {\n let code = event.keyCode, mods = getMods(event);\n if (code == 8 || (mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);\n }\n else if ((code == 46 && !event.shiftKey) || (mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);\n }\n else if (code == 13 || code == 27) { // Enter, Esc\n return true;\n }\n else if (code == 37 || (mac && code == 66 && mods == \"c\")) { // Left arrow, Ctrl-b on Mac\n let dir = code == 37 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? -1 : 1) : -1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 39 || (mac && code == 70 && mods == \"c\")) { // Right arrow, Ctrl-f on Mac\n let dir = code == 39 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? 1 : -1) : 1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 38 || (mac && code == 80 && mods == \"c\")) { // Up arrow, Ctrl-p on Mac\n return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);\n }\n else if (code == 40 || (mac && code == 78 && mods == \"c\")) { // Down arrow, Ctrl-n on Mac\n return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);\n }\n else if (mods == (mac ? \"m\" : \"c\") &&\n (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n return true;\n }\n return false;\n}\n\nfunction serializeForClipboard(view, slice) {\n view.someProp(\"transformCopied\", f => { slice = f(slice, view); });\n let context = [], { content, openStart, openEnd } = slice;\n while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n openStart--;\n openEnd--;\n let node = content.firstChild;\n context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n content = node.content;\n }\n let serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n let doc = detachedDoc(), wrap = doc.createElement(\"div\");\n wrap.appendChild(serializer.serializeFragment(content, { document: doc }));\n let firstChild = wrap.firstChild, needsWrap, wrappers = 0;\n while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n for (let i = needsWrap.length - 1; i >= 0; i--) {\n let wrapper = doc.createElement(needsWrap[i]);\n while (wrap.firstChild)\n wrapper.appendChild(wrap.firstChild);\n wrap.appendChild(wrapper);\n wrappers++;\n }\n firstChild = wrap.firstChild;\n }\n if (firstChild && firstChild.nodeType == 1)\n firstChild.setAttribute(\"data-pm-slice\", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : \"\"} ${JSON.stringify(context)}`);\n let text = view.someProp(\"clipboardTextSerializer\", f => f(slice, view)) ||\n slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n return { dom: wrap, text, slice };\n}\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n let inCode = $context.parent.type.spec.code;\n let dom, slice;\n if (!html && !text)\n return null;\n let asText = text && (plainText || inCode || !html);\n if (asText) {\n view.someProp(\"transformPastedText\", f => { text = f(text, inCode || plainText, view); });\n if (inCode)\n return text ? new Slice(Fragment.from(view.state.schema.text(text.replace(/\\r\\n?/g, \"\\n\"))), 0, 0) : Slice.empty;\n let parsed = view.someProp(\"clipboardTextParser\", f => f(text, $context, plainText, view));\n if (parsed) {\n slice = parsed;\n }\n else {\n let marks = $context.marks();\n let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);\n dom = document.createElement(\"div\");\n text.split(/(?:\\r\\n?|\\n)+/).forEach(block => {\n let p = dom.appendChild(document.createElement(\"p\"));\n if (block)\n p.appendChild(serializer.serializeNode(schema.text(block, marks)));\n });\n }\n }\n else {\n view.someProp(\"transformPastedHTML\", f => { html = f(html, view); });\n dom = readHTML(html);\n if (webkit)\n restoreReplacedSpaces(dom);\n }\n let contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n let sliceData = contextNode && /^(\\d+) (\\d+)(?: -(\\d+))? (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\") || \"\");\n if (sliceData && sliceData[3])\n for (let i = +sliceData[3]; i > 0; i--) {\n let child = dom.firstChild;\n while (child && child.nodeType != 1)\n child = child.nextSibling;\n if (!child)\n break;\n dom = child;\n }\n if (!slice) {\n let parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n slice = parser.parseSlice(dom, {\n preserveWhitespace: !!(asText || sliceData),\n context: $context,\n ruleFromNode(dom) {\n if (dom.nodeName == \"BR\" && !dom.nextSibling &&\n dom.parentNode && !inlineParents.test(dom.parentNode.nodeName))\n return { ignore: true };\n return null;\n }\n });\n }\n if (sliceData) {\n slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);\n }\n else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);\n if (slice.openStart || slice.openEnd) {\n let openStart = 0, openEnd = 0;\n for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { }\n for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { }\n slice = closeSlice(slice, openStart, openEnd);\n }\n }\n view.someProp(\"transformPasted\", f => { slice = f(slice, view); });\n return slice;\n}\nconst inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n if (fragment.childCount < 2)\n return fragment;\n for (let d = $context.depth; d >= 0; d--) {\n let parent = $context.node(d);\n let match = parent.contentMatchAt($context.index(d));\n let lastWrap, result = [];\n fragment.forEach(node => {\n if (!result)\n return;\n let wrap = match.findWrapping(node.type), inLast;\n if (!wrap)\n return result = null;\n if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n result[result.length - 1] = inLast;\n }\n else {\n if (result.length)\n result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);\n let wrapped = withWrappers(node, wrap);\n result.push(wrapped);\n match = match.matchType(wrapped.type);\n lastWrap = wrap;\n }\n });\n if (result)\n return Fragment.from(result);\n }\n return fragment;\n}\nfunction withWrappers(node, wrap, from = 0) {\n for (let i = wrap.length - 1; i >= from; i--)\n node = wrap[i].create(null, Fragment.from(node));\n return node;\n}\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n if (inner)\n return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));\n let match = sibling.contentMatchAt(sibling.childCount);\n if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1))));\n }\n}\nfunction closeRight(node, depth) {\n if (depth == 0)\n return node;\n let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n return node.copy(fragment.append(fill));\n}\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n if (fragment.childCount > 1)\n openEnd = 0;\n if (depth < to - 1)\n inner = closeRange(inner, side, from, to, depth + 1, openEnd);\n if (depth >= from)\n inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner)\n : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));\n return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));\n}\nfunction closeSlice(slice, openStart, openEnd) {\n if (openStart < slice.openStart)\n slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);\n if (openEnd < slice.openEnd)\n slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);\n return slice;\n}\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"..\"` the table cells are ignored.\nconst wrapMap = {\n thead: [\"table\"],\n tbody: [\"table\"],\n tfoot: [\"table\"],\n caption: [\"table\"],\n colgroup: [\"table\"],\n col: [\"table\", \"colgroup\"],\n tr: [\"table\", \"tbody\"],\n td: [\"table\", \"tbody\", \"tr\"],\n th: [\"table\", \"tbody\", \"tr\"]\n};\nlet _detachedDoc = null;\nfunction detachedDoc() {\n return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument(\"title\"));\n}\nlet _policy = null;\nfunction maybeWrapTrusted(html) {\n let trustedTypes = window.trustedTypes;\n if (!trustedTypes)\n return html;\n // With the require-trusted-types-for CSP, Chrome will block\n // innerHTML, even on a detached document. This wraps the string in\n // a way that makes the browser allow us to use its parser again.\n if (!_policy)\n _policy = trustedTypes.createPolicy(\"ProseMirrorClipboard\", { createHTML: (s) => s });\n return _policy.createHTML(html);\n}\nfunction readHTML(html) {\n let metas = /^(\\s*]*>)*/.exec(html);\n if (metas)\n html = html.slice(metas[0].length);\n let elt = detachedDoc().createElement(\"div\");\n let firstTag = /<([a-z][^>\\s]+)/i.exec(html), wrap;\n if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])\n html = wrap.map(n => \"<\" + n + \">\").join(\"\") + html + wrap.map(n => \"\").reverse().join(\"\");\n elt.innerHTML = maybeWrapTrusted(html);\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n elt = elt.querySelector(wrap[i]) || elt;\n return elt;\n}\n// Webkit browsers do some hard-to-predict replacement of regular\n// spaces with non-breaking spaces when putting content on the\n// clipboard. This tries to convert such non-breaking spaces (which\n// will be wrapped in a plain span on Chrome, a span with class\n// Apple-converted-space on Safari) back to regular spaces.\nfunction restoreReplacedSpaces(dom) {\n let nodes = dom.querySelectorAll(chrome ? \"span:not([class]):not([style])\" : \"span.Apple-converted-space\");\n for (let i = 0; i < nodes.length; i++) {\n let node = nodes[i];\n if (node.childNodes.length == 1 && node.textContent == \"\\u00a0\" && node.parentNode)\n node.parentNode.replaceChild(dom.ownerDocument.createTextNode(\" \"), node);\n }\n}\nfunction addContext(slice, context) {\n if (!slice.size)\n return slice;\n let schema = slice.content.firstChild.type.schema, array;\n try {\n array = JSON.parse(context);\n }\n catch (e) {\n return slice;\n }\n let { content, openStart, openEnd } = slice;\n for (let i = array.length - 2; i >= 0; i -= 2) {\n let type = schema.nodes[array[i]];\n if (!type || type.hasRequiredAttrs())\n break;\n content = Fragment.from(type.create(array[i + 1], content));\n openStart++;\n openEnd++;\n }\n return new Slice(content, openStart, openEnd);\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nconst handlers = {};\nconst editHandlers = {};\nconst passiveHandlers = { touchstart: true, touchmove: true };\nclass InputState {\n constructor() {\n this.shiftKey = false;\n this.mouseDown = null;\n this.lastKeyCode = null;\n this.lastKeyCodeTime = 0;\n this.lastClick = { time: 0, x: 0, y: 0, type: \"\" };\n this.lastSelectionOrigin = null;\n this.lastSelectionTime = 0;\n this.lastIOSEnter = 0;\n this.lastIOSEnterFallbackTimeout = -1;\n this.lastFocus = 0;\n this.lastTouch = 0;\n this.lastChromeDelete = 0;\n this.composing = false;\n this.compositionNode = null;\n this.composingTimeout = -1;\n this.compositionNodes = [];\n this.compositionEndedAt = -2e8;\n this.compositionID = 1;\n // Set to a composition ID when there are pending changes at compositionend\n this.compositionPendingChanges = 0;\n this.domChangeCount = 0;\n this.eventHandlers = Object.create(null);\n this.hideSelectionGuard = null;\n }\n}\nfunction initInput(view) {\n for (let event in handlers) {\n let handler = handlers[event];\n view.dom.addEventListener(event, view.input.eventHandlers[event] = (event) => {\n if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n (view.editable || !(event.type in editHandlers)))\n handler(view, event);\n }, passiveHandlers[event] ? { passive: true } : undefined);\n }\n // On Safari, for reasons beyond my understanding, adding an input\n // event handler makes an issue where the composition vanishes when\n // you press enter go away.\n if (safari)\n view.dom.addEventListener(\"input\", () => null);\n ensureListeners(view);\n}\nfunction setSelectionOrigin(view, origin) {\n view.input.lastSelectionOrigin = origin;\n view.input.lastSelectionTime = Date.now();\n}\nfunction destroyInput(view) {\n view.domObserver.stop();\n for (let type in view.input.eventHandlers)\n view.dom.removeEventListener(type, view.input.eventHandlers[type]);\n clearTimeout(view.input.composingTimeout);\n clearTimeout(view.input.lastIOSEnterFallbackTimeout);\n}\nfunction ensureListeners(view) {\n view.someProp(\"handleDOMEvents\", currentHandlers => {\n for (let type in currentHandlers)\n if (!view.input.eventHandlers[type])\n view.dom.addEventListener(type, view.input.eventHandlers[type] = event => runCustomHandler(view, event));\n });\n}\nfunction runCustomHandler(view, event) {\n return view.someProp(\"handleDOMEvents\", handlers => {\n let handler = handlers[event.type];\n return handler ? handler(view, event) || event.defaultPrevented : false;\n });\n}\nfunction eventBelongsToView(view, event) {\n if (!event.bubbles)\n return true;\n if (event.defaultPrevented)\n return false;\n for (let node = event.target; node != view.dom; node = node.parentNode)\n if (!node || node.nodeType == 11 ||\n (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n return false;\n return true;\n}\nfunction dispatchEvent(view, event) {\n if (!runCustomHandler(view, event) && handlers[event.type] &&\n (view.editable || !(event.type in editHandlers)))\n handlers[event.type](view, event);\n}\neditHandlers.keydown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.keyCode == 16 || event.shiftKey;\n if (inOrNearComposition(view, event))\n return;\n view.input.lastKeyCode = event.keyCode;\n view.input.lastKeyCodeTime = Date.now();\n // Suppress enter key events on Chrome Android, because those tend\n // to be part of a confused sequence of composition events fired,\n // and handling them eagerly tends to corrupt the input.\n if (android && chrome && event.keyCode == 13)\n return;\n if (event.keyCode != 229)\n view.domObserver.forceFlush();\n // On iOS, if we preventDefault enter key presses, the virtual\n // keyboard gets confused. So the hack here is to set a flag that\n // makes the DOM change code recognize that what just happens should\n // be replaced by whatever the Enter key handlers do.\n if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n let now = Date.now();\n view.input.lastIOSEnter = now;\n view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {\n if (view.input.lastIOSEnter == now) {\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")));\n view.input.lastIOSEnter = 0;\n }\n }, 200);\n }\n else if (view.someProp(\"handleKeyDown\", f => f(view, event)) || captureKeyDown(view, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"key\");\n }\n};\neditHandlers.keyup = (view, event) => {\n if (event.keyCode == 16)\n view.input.shiftKey = false;\n};\neditHandlers.keypress = (view, _event) => {\n let event = _event;\n if (inOrNearComposition(view, event) || !event.charCode ||\n event.ctrlKey && !event.altKey || mac && event.metaKey)\n return;\n if (view.someProp(\"handleKeyPress\", f => f(view, event))) {\n event.preventDefault();\n return;\n }\n let sel = view.state.selection;\n if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n let text = String.fromCharCode(event.charCode);\n if (!/[\\r\\n]/.test(text) && !view.someProp(\"handleTextInput\", f => f(view, sel.$from.pos, sel.$to.pos, text)))\n view.dispatch(view.state.tr.insertText(text).scrollIntoView());\n event.preventDefault();\n }\n};\nfunction eventCoords(event) { return { left: event.clientX, top: event.clientY }; }\nfunction isNear(event, click) {\n let dx = click.x - event.clientX, dy = click.y - event.clientY;\n return dx * dx + dy * dy < 100;\n}\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n if (view.someProp(propName, f => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n : f(view, pos, $pos.node(i), $pos.before(i), event, false)))\n return true;\n }\n return false;\n}\nfunction updateSelection(view, selection, origin) {\n if (!view.focused)\n view.focus();\n if (view.state.selection.eq(selection))\n return;\n let tr = view.state.tr.setSelection(selection);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n view.dispatch(tr);\n}\nfunction selectClickedLeaf(view, inside) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n updateSelection(view, new NodeSelection($pos), \"pointer\");\n return true;\n }\n return false;\n}\nfunction selectClickedNode(view, inside) {\n if (inside == -1)\n return false;\n let sel = view.state.selection, selectedNode, selectAt;\n if (sel instanceof NodeSelection)\n selectedNode = sel.node;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n if (NodeSelection.isSelectable(node)) {\n if (selectedNode && sel.$from.depth > 0 &&\n i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n selectAt = $pos.before(sel.$from.depth);\n else\n selectAt = $pos.before(i);\n break;\n }\n }\n if (selectAt != null) {\n updateSelection(view, NodeSelection.create(view.state.doc, selectAt), \"pointer\");\n return true;\n }\n else {\n return false;\n }\n}\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n view.someProp(\"handleClick\", f => f(view, pos, event)) ||\n (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));\n}\nfunction handleDoubleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n view.someProp(\"handleDoubleClick\", f => f(view, pos, event));\n}\nfunction handleTripleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n view.someProp(\"handleTripleClick\", f => f(view, pos, event)) ||\n defaultTripleClick(view, inside, event);\n}\nfunction defaultTripleClick(view, inside, event) {\n if (event.button != 0)\n return false;\n let doc = view.state.doc;\n if (inside == -1) {\n if (doc.inlineContent) {\n updateSelection(view, TextSelection.create(doc, 0, doc.content.size), \"pointer\");\n return true;\n }\n return false;\n }\n let $pos = doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n let nodePos = $pos.before(i);\n if (node.inlineContent)\n updateSelection(view, TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), \"pointer\");\n else if (NodeSelection.isSelectable(node))\n updateSelection(view, NodeSelection.create(doc, nodePos), \"pointer\");\n else\n continue;\n return true;\n }\n}\nfunction forceDOMFlush(view) {\n return endComposition(view);\n}\nconst selectNodeModifier = mac ? \"metaKey\" : \"ctrlKey\";\nhandlers.mousedown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.shiftKey;\n let flushed = forceDOMFlush(view);\n let now = Date.now(), type = \"singleClick\";\n if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier]) {\n if (view.input.lastClick.type == \"singleClick\")\n type = \"doubleClick\";\n else if (view.input.lastClick.type == \"doubleClick\")\n type = \"tripleClick\";\n }\n view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type };\n let pos = view.posAtCoords(eventCoords(event));\n if (!pos)\n return;\n if (type == \"singleClick\") {\n if (view.input.mouseDown)\n view.input.mouseDown.done();\n view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);\n }\n else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"pointer\");\n }\n};\nclass MouseDown {\n constructor(view, pos, event, flushed) {\n this.view = view;\n this.pos = pos;\n this.event = event;\n this.flushed = flushed;\n this.delayedSelectionSync = false;\n this.mightDrag = null;\n this.startDoc = view.state.doc;\n this.selectNode = !!event[selectNodeModifier];\n this.allowDefault = event.shiftKey;\n let targetNode, targetPos;\n if (pos.inside > -1) {\n targetNode = view.state.doc.nodeAt(pos.inside);\n targetPos = pos.inside;\n }\n else {\n let $pos = view.state.doc.resolve(pos.pos);\n targetNode = $pos.parent;\n targetPos = $pos.depth ? $pos.before() : 0;\n }\n const target = flushed ? null : event.target;\n const targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n this.target = targetDesc && targetDesc.dom.nodeType == 1 ? targetDesc.dom : null;\n let { selection } = view.state;\n if (event.button == 0 &&\n targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)\n this.mightDrag = {\n node: targetNode,\n pos: targetPos,\n addAttr: !!(this.target && !this.target.draggable),\n setUneditable: !!(this.target && gecko && !this.target.hasAttribute(\"contentEditable\"))\n };\n if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.draggable = true;\n if (this.mightDrag.setUneditable)\n setTimeout(() => {\n if (this.view.input.mouseDown == this)\n this.target.setAttribute(\"contentEditable\", \"false\");\n }, 20);\n this.view.domObserver.start();\n }\n view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n setSelectionOrigin(view, \"pointer\");\n }\n done() {\n this.view.root.removeEventListener(\"mouseup\", this.up);\n this.view.root.removeEventListener(\"mousemove\", this.move);\n if (this.mightDrag && this.target) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.removeAttribute(\"draggable\");\n if (this.mightDrag.setUneditable)\n this.target.removeAttribute(\"contentEditable\");\n this.view.domObserver.start();\n }\n if (this.delayedSelectionSync)\n setTimeout(() => selectionToDOM(this.view));\n this.view.input.mouseDown = null;\n }\n up(event) {\n this.done();\n if (!this.view.dom.contains(event.target))\n return;\n let pos = this.pos;\n if (this.view.state.doc != this.startDoc)\n pos = this.view.posAtCoords(eventCoords(event));\n this.updateAllowDefault(event);\n if (this.allowDefault || !pos) {\n setSelectionOrigin(this.view, \"pointer\");\n }\n else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n event.preventDefault();\n }\n else if (event.button == 0 &&\n (this.flushed ||\n // Safari ignores clicks on draggable elements\n (safari && this.mightDrag && !this.mightDrag.node.isAtom) ||\n // Chrome will sometimes treat a node selection as a\n // cursor, but still report that the node is selected\n // when asked through getSelection. You'll then get a\n // situation where clicking at the point where that\n // (hidden) cursor is doesn't change the selection, and\n // thus doesn't get a reaction from ProseMirror. This\n // works around that.\n (chrome && !this.view.state.selection.visible &&\n Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2))) {\n updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), \"pointer\");\n event.preventDefault();\n }\n else {\n setSelectionOrigin(this.view, \"pointer\");\n }\n }\n move(event) {\n this.updateAllowDefault(event);\n setSelectionOrigin(this.view, \"pointer\");\n if (event.buttons == 0)\n this.done();\n }\n updateAllowDefault(event) {\n if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 ||\n Math.abs(this.event.y - event.clientY) > 4))\n this.allowDefault = true;\n }\n}\nhandlers.touchstart = view => {\n view.input.lastTouch = Date.now();\n forceDOMFlush(view);\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.touchmove = view => {\n view.input.lastTouch = Date.now();\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.contextmenu = view => forceDOMFlush(view);\nfunction inOrNearComposition(view, event) {\n if (view.composing)\n return true;\n // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n // emitted. The keydown event triggers newline insertion, which we don't want.\n // This method returns true if the keydown event should be ignored.\n // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n // This guards against the case where compositionend is triggered without the keyboard\n // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n // afterwards- we wouldn't want to ignore the keydown event in this case.\n if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {\n view.input.compositionEndedAt = -2e8;\n return true;\n }\n return false;\n}\n// Drop active composition after 5 seconds of inactivity on Android\nconst timeoutComposition = android ? 5000 : -1;\neditHandlers.compositionstart = editHandlers.compositionupdate = view => {\n if (!view.composing) {\n view.domObserver.flush();\n let { state } = view, $pos = state.selection.$to;\n if (state.selection instanceof TextSelection &&\n (state.storedMarks ||\n (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(m => m.type.spec.inclusive === false)))) {\n // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n view.markCursor = view.state.storedMarks || $pos.marks();\n endComposition(view, true);\n view.markCursor = null;\n }\n else {\n endComposition(view, !state.selection.empty);\n // In firefox, if the cursor is after but outside a marked node,\n // the inserted text won't inherit the marks. So this moves it\n // inside if necessary.\n if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n let sel = view.domSelectionRange();\n for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) {\n let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n if (!before)\n break;\n if (before.nodeType == 3) {\n let sel = view.domSelection();\n if (sel)\n sel.collapse(before, before.nodeValue.length);\n break;\n }\n else {\n node = before;\n offset = -1;\n }\n }\n }\n }\n view.input.composing = true;\n }\n scheduleComposeEnd(view, timeoutComposition);\n};\neditHandlers.compositionend = (view, event) => {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = event.timeStamp;\n view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;\n view.input.compositionNode = null;\n if (view.input.compositionPendingChanges)\n Promise.resolve().then(() => view.domObserver.flush());\n view.input.compositionID++;\n scheduleComposeEnd(view, 20);\n }\n};\nfunction scheduleComposeEnd(view, delay) {\n clearTimeout(view.input.composingTimeout);\n if (delay > -1)\n view.input.composingTimeout = setTimeout(() => endComposition(view), delay);\n}\nfunction clearComposition(view) {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = timestampFromCustomEvent();\n }\n while (view.input.compositionNodes.length > 0)\n view.input.compositionNodes.pop().markParentsDirty();\n}\nfunction findCompositionNode(view) {\n let sel = view.domSelectionRange();\n if (!sel.focusNode)\n return null;\n let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);\n let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);\n if (textBefore && textAfter && textBefore != textAfter) {\n let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;\n if (textBefore == lastChanged || textAfter == lastChanged)\n return lastChanged;\n if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {\n return textAfter;\n }\n else if (view.input.compositionNode == textAfter) {\n let descBefore = textBefore.pmViewDesc;\n if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))\n return textAfter;\n }\n }\n return textBefore || textAfter;\n}\nfunction timestampFromCustomEvent() {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"event\", true, true);\n return event.timeStamp;\n}\n/**\n@internal\n*/\nfunction endComposition(view, restarting = false) {\n if (android && view.domObserver.flushingSoon >= 0)\n return;\n view.domObserver.forceFlush();\n clearComposition(view);\n if (restarting || view.docView && view.docView.dirty) {\n let sel = selectionFromDOM(view);\n if (sel && !sel.eq(view.state.selection))\n view.dispatch(view.state.tr.setSelection(sel));\n else if ((view.markCursor || restarting) && !view.state.selection.empty)\n view.dispatch(view.state.tr.deleteSelection());\n else\n view.updateState(view.state);\n return true;\n }\n return false;\n}\nfunction captureCopy(view, dom) {\n // The extra wrapper is somehow necessary on IE/Edge to prevent the\n // content from being mangled when it is put onto the clipboard\n if (!view.dom.parentNode)\n return;\n let wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n wrap.appendChild(dom);\n wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n let sel = getSelection(), range = document.createRange();\n range.selectNodeContents(dom);\n // Done because IE will fire a selectionchange moving the selection\n // to its start when removeAllRanges is called and the editor still\n // has focus (which will mess up the editor's selection state).\n view.dom.blur();\n sel.removeAllRanges();\n sel.addRange(range);\n setTimeout(() => {\n if (wrap.parentNode)\n wrap.parentNode.removeChild(wrap);\n view.focus();\n }, 50);\n}\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = (ie && ie_version < 15) ||\n (ios && webkit_version < 604);\nhandlers.copy = editHandlers.cut = (view, _event) => {\n let event = _event;\n let sel = view.state.selection, cut = event.type == \"cut\";\n if (sel.empty)\n return;\n // IE and Edge's clipboard interface is completely broken\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice);\n if (data) {\n event.preventDefault();\n data.clearData();\n data.setData(\"text/html\", dom.innerHTML);\n data.setData(\"text/plain\", text);\n }\n else {\n captureCopy(view, dom);\n }\n if (cut)\n view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\"));\n};\nfunction sliceSingleNode(slice) {\n return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;\n}\nfunction capturePaste(view, event) {\n if (!view.dom.parentNode)\n return;\n let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;\n let target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n if (!plainText)\n target.contentEditable = \"true\";\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n setTimeout(() => {\n view.focus();\n if (target.parentNode)\n target.parentNode.removeChild(target);\n if (plainText)\n doPaste(view, target.value, null, plain, event);\n else\n doPaste(view, target.textContent, target.innerHTML, plain, event);\n }, 50);\n}\nfunction doPaste(view, text, html, preferPlain, event) {\n let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from);\n if (view.someProp(\"handlePaste\", f => f(view, event, slice || Slice.empty)))\n return true;\n if (!slice)\n return false;\n let singleNode = sliceSingleNode(slice);\n let tr = singleNode\n ? view.state.tr.replaceSelectionWith(singleNode, preferPlain)\n : view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n return true;\n}\nfunction getText(clipboardData) {\n let text = clipboardData.getData(\"text/plain\") || clipboardData.getData(\"Text\");\n if (text)\n return text;\n let uris = clipboardData.getData(\"text/uri-list\");\n return uris ? uris.replace(/\\r?\\n/g, \" \") : \"\";\n}\neditHandlers.paste = (view, _event) => {\n let event = _event;\n // Handling paste from JavaScript during composition is very poorly\n // handled by browsers, so as a dodgy but preferable kludge, we just\n // let the browser do its native thing there, except on Android,\n // where the editor is almost always composing.\n if (view.composing && !android)\n return;\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n if (data && doPaste(view, getText(data), data.getData(\"text/html\"), plain, event))\n event.preventDefault();\n else\n capturePaste(view, event);\n};\nclass Dragging {\n constructor(slice, move, node) {\n this.slice = slice;\n this.move = move;\n this.node = node;\n }\n}\nconst dragCopyModifier = mac ? \"altKey\" : \"ctrlKey\";\nhandlers.dragstart = (view, _event) => {\n let event = _event;\n let mouseDown = view.input.mouseDown;\n if (mouseDown)\n mouseDown.done();\n if (!event.dataTransfer)\n return;\n let sel = view.state.selection;\n let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));\n let node;\n if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;\n else if (mouseDown && mouseDown.mightDrag) {\n node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);\n }\n else if (event.target && event.target.nodeType == 1) {\n let desc = view.docView.nearestDesc(event.target, true);\n if (desc && desc.node.type.spec.draggable && desc != view.docView)\n node = NodeSelection.create(view.state.doc, desc.posBefore);\n }\n let draggedSlice = (node || view.state.selection).content();\n let { dom, text, slice } = serializeForClipboard(view, draggedSlice);\n // Pre-120 Chrome versions clear files when calling `clearData` (#1472)\n if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)\n event.dataTransfer.clearData();\n event.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n // See https://github.com/ProseMirror/prosemirror/issues/1156\n event.dataTransfer.effectAllowed = \"copyMove\";\n if (!brokenClipboardAPI)\n event.dataTransfer.setData(\"text/plain\", text);\n view.dragging = new Dragging(slice, !event[dragCopyModifier], node);\n};\nhandlers.dragend = view => {\n let dragging = view.dragging;\n window.setTimeout(() => {\n if (view.dragging == dragging)\n view.dragging = null;\n }, 50);\n};\neditHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();\neditHandlers.drop = (view, _event) => {\n let event = _event;\n let dragging = view.dragging;\n view.dragging = null;\n if (!event.dataTransfer)\n return;\n let eventPos = view.posAtCoords(eventCoords(event));\n if (!eventPos)\n return;\n let $mouse = view.state.doc.resolve(eventPos.pos);\n let slice = dragging && dragging.slice;\n if (slice) {\n view.someProp(\"transformPasted\", f => { slice = f(slice, view); });\n }\n else {\n slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData(\"text/html\"), false, $mouse);\n }\n let move = !!(dragging && !event[dragCopyModifier]);\n if (view.someProp(\"handleDrop\", f => f(view, event, slice || Slice.empty, move))) {\n event.preventDefault();\n return;\n }\n if (!slice)\n return;\n event.preventDefault();\n let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n if (insertPos == null)\n insertPos = $mouse.pos;\n let tr = view.state.tr;\n if (move) {\n let { node } = dragging;\n if (node)\n node.replace(tr);\n else\n tr.deleteSelection();\n }\n let pos = tr.mapping.map(insertPos);\n let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n let beforeInsert = tr.doc;\n if (isNode)\n tr.replaceRangeWith(pos, pos, slice.content.firstChild);\n else\n tr.replaceRange(pos, pos, slice);\n if (tr.doc.eq(beforeInsert))\n return;\n let $pos = tr.doc.resolve(pos);\n if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n tr.setSelection(new NodeSelection($pos));\n }\n else {\n let end = tr.mapping.map(insertPos);\n tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);\n tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n }\n view.focus();\n view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n};\nhandlers.focus = view => {\n view.input.lastFocus = Date.now();\n if (!view.focused) {\n view.domObserver.stop();\n view.dom.classList.add(\"ProseMirror-focused\");\n view.domObserver.start();\n view.focused = true;\n setTimeout(() => {\n if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))\n selectionToDOM(view);\n }, 20);\n }\n};\nhandlers.blur = (view, _event) => {\n let event = _event;\n if (view.focused) {\n view.domObserver.stop();\n view.dom.classList.remove(\"ProseMirror-focused\");\n view.domObserver.start();\n if (event.relatedTarget && view.dom.contains(event.relatedTarget))\n view.domObserver.currentSelection.clear();\n view.focused = false;\n }\n};\nhandlers.beforeinput = (view, _event) => {\n let event = _event;\n // We should probably do more with beforeinput events, but support\n // is so spotty that I'm still waiting to see where they are going.\n // Very specific hack to deal with backspace sometimes failing on\n // Chrome Android when after an uneditable node.\n if (chrome && android && event.inputType == \"deleteContentBackward\") {\n view.domObserver.flushSoon();\n let { domChangeCount } = view.input;\n setTimeout(() => {\n if (view.input.domChangeCount != domChangeCount)\n return; // Event already had some effect\n // This bug tends to close the virtual keyboard, so we refocus\n view.dom.blur();\n view.focus();\n if (view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\"))))\n return;\n let { $cursor } = view.state.selection;\n // Crude approximation of backspace behavior when no command handled it\n if ($cursor && $cursor.pos > 0)\n view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());\n }, 50);\n }\n};\n// Make sure all handlers get registered\nfor (let prop in editHandlers)\n handlers[prop] = editHandlers[prop];\n\nfunction compareObjs(a, b) {\n if (a == b)\n return true;\n for (let p in a)\n if (a[p] !== b[p])\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n return true;\n}\nclass WidgetType {\n constructor(toDOM, spec) {\n this.toDOM = toDOM;\n this.spec = spec || noSpec;\n this.side = this.spec.side || 0;\n }\n map(mapping, span, offset, oldOffset) {\n let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n return deleted ? null : new Decoration(pos - offset, pos - offset, this);\n }\n valid() { return true; }\n eq(other) {\n return this == other ||\n (other instanceof WidgetType &&\n (this.spec.key && this.spec.key == other.spec.key ||\n this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)));\n }\n destroy(node) {\n if (this.spec.destroy)\n this.spec.destroy(node);\n }\n}\nclass InlineType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n return from >= to ? null : new Decoration(from, to, this);\n }\n valid(_, span) { return span.from < span.to; }\n eq(other) {\n return this == other ||\n (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n static is(span) { return span.type instanceof InlineType; }\n destroy() { }\n}\nclass NodeType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.mapResult(span.from + oldOffset, 1);\n if (from.deleted)\n return null;\n let to = mapping.mapResult(span.to + oldOffset, -1);\n if (to.deleted || to.pos <= from.pos)\n return null;\n return new Decoration(from.pos - offset, to.pos - offset, this);\n }\n valid(node, span) {\n let { index, offset } = node.content.findIndex(span.from), child;\n return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to;\n }\n eq(other) {\n return this == other ||\n (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n destroy() { }\n}\n/**\nDecoration objects can be provided to the view through the\n[`decorations` prop](https://prosemirror.net/docs/ref/#view.EditorProps.decorations). They come in\nseveral variants—see the static members of this class for details.\n*/\nclass Decoration {\n /**\n @internal\n */\n constructor(\n /**\n The start position of the decoration.\n */\n from, \n /**\n The end position. Will be the same as `from` for [widget\n decorations](https://prosemirror.net/docs/ref/#view.Decoration^widget).\n */\n to, \n /**\n @internal\n */\n type) {\n this.from = from;\n this.to = to;\n this.type = type;\n }\n /**\n @internal\n */\n copy(from, to) {\n return new Decoration(from, to, this.type);\n }\n /**\n @internal\n */\n eq(other, offset = 0) {\n return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;\n }\n /**\n @internal\n */\n map(mapping, offset, oldOffset) {\n return this.type.map(mapping, this, offset, oldOffset);\n }\n /**\n Creates a widget decoration, which is a DOM node that's shown in\n the document at the given position. It is recommended that you\n delay rendering the widget by passing a function that will be\n called when the widget is actually drawn in a view, but you can\n also directly pass a DOM node. `getPos` can be used to find the\n widget's current document position.\n */\n static widget(pos, toDOM, spec) {\n return new Decoration(pos, pos, new WidgetType(toDOM, spec));\n }\n /**\n Creates an inline decoration, which adds the given attributes to\n each inline node between `from` and `to`.\n */\n static inline(from, to, attrs, spec) {\n return new Decoration(from, to, new InlineType(attrs, spec));\n }\n /**\n Creates a node decoration. `from` and `to` should point precisely\n before and after a node in the document. That node, and only that\n node, will receive the given attributes.\n */\n static node(from, to, attrs, spec) {\n return new Decoration(from, to, new NodeType(attrs, spec));\n }\n /**\n The spec provided when creating this decoration. Can be useful\n if you've stored extra information in that object.\n */\n get spec() { return this.type.spec; }\n /**\n @internal\n */\n get inline() { return this.type instanceof InlineType; }\n /**\n @internal\n */\n get widget() { return this.type instanceof WidgetType; }\n}\nconst none = [], noSpec = {};\n/**\nA collection of [decorations](https://prosemirror.net/docs/ref/#view.Decoration), organized in such\na way that the drawing algorithm can efficiently use and compare\nthem. This is a persistent data structure—it is not modified,\nupdates create a new value.\n*/\nclass DecorationSet {\n /**\n @internal\n */\n constructor(local, children) {\n this.local = local.length ? local : none;\n this.children = children.length ? children : none;\n }\n /**\n Create a set of decorations, using the structure of the given\n document. This will consume (modify) the `decorations` array, so\n you must make a copy if you want need to preserve that.\n */\n static create(doc, decorations) {\n return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;\n }\n /**\n Find all decorations in this set which touch the given range\n (including decorations that start or end directly at the\n boundaries) and match the given predicate on their spec. When\n `start` and `end` are omitted, all decorations in the set are\n considered. When `predicate` isn't given, all decorations are\n assumed to match.\n */\n find(start, end, predicate) {\n let result = [];\n this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n return result;\n }\n findInner(start, end, result, offset, predicate) {\n for (let i = 0; i < this.local.length; i++) {\n let span = this.local[i];\n if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))\n result.push(span.copy(span.from + offset, span.to + offset));\n }\n for (let i = 0; i < this.children.length; i += 3) {\n if (this.children[i] < end && this.children[i + 1] > start) {\n let childOff = this.children[i] + 1;\n this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n }\n }\n }\n /**\n Map the set of decorations in response to a change in the\n document.\n */\n map(mapping, doc, options) {\n if (this == empty || mapping.maps.length == 0)\n return this;\n return this.mapInner(mapping, doc, 0, 0, options || noSpec);\n }\n /**\n @internal\n */\n mapInner(mapping, node, offset, oldOffset, options) {\n let newLocal;\n for (let i = 0; i < this.local.length; i++) {\n let mapped = this.local[i].map(mapping, offset, oldOffset);\n if (mapped && mapped.type.valid(node, mapped))\n (newLocal || (newLocal = [])).push(mapped);\n else if (options.onRemove)\n options.onRemove(this.local[i].spec);\n }\n if (this.children.length)\n return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);\n else\n return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;\n }\n /**\n Add the given array of decorations to the ones in the set,\n producing a new set. Consumes the `decorations` array. Needs\n access to the current document to create the appropriate tree\n structure.\n */\n add(doc, decorations) {\n if (!decorations.length)\n return this;\n if (this == empty)\n return DecorationSet.create(doc, decorations);\n return this.addInner(doc, decorations, 0);\n }\n addInner(doc, decorations, offset) {\n let children, childIndex = 0;\n doc.forEach((childNode, childOffset) => {\n let baseOffset = childOffset + offset, found;\n if (!(found = takeSpansForNode(decorations, childNode, baseOffset)))\n return;\n if (!children)\n children = this.children.slice();\n while (childIndex < children.length && children[childIndex] < childOffset)\n childIndex += 3;\n if (children[childIndex] == childOffset)\n children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1);\n else\n children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec));\n childIndex += 3;\n });\n let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n for (let i = 0; i < local.length; i++)\n if (!local[i].type.valid(doc, local[i]))\n local.splice(i--, 1);\n return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);\n }\n /**\n Create a new set that contains the decorations in this set, minus\n the ones in the given array.\n */\n remove(decorations) {\n if (decorations.length == 0 || this == empty)\n return this;\n return this.removeInner(decorations, 0);\n }\n removeInner(decorations, offset) {\n let children = this.children, local = this.local;\n for (let i = 0; i < children.length; i += 3) {\n let found;\n let from = children[i] + offset, to = children[i + 1] + offset;\n for (let j = 0, span; j < decorations.length; j++)\n if (span = decorations[j]) {\n if (span.from > from && span.to < to) {\n decorations[j] = null;\n (found || (found = [])).push(span);\n }\n }\n if (!found)\n continue;\n if (children == this.children)\n children = this.children.slice();\n let removed = children[i + 2].removeInner(found, from + 1);\n if (removed != empty) {\n children[i + 2] = removed;\n }\n else {\n children.splice(i, 3);\n i -= 3;\n }\n }\n if (local.length)\n for (let i = 0, span; i < decorations.length; i++)\n if (span = decorations[i]) {\n for (let j = 0; j < local.length; j++)\n if (local[j].eq(span, offset)) {\n if (local == this.local)\n local = this.local.slice();\n local.splice(j--, 1);\n }\n }\n if (children == this.children && local == this.local)\n return this;\n return local.length || children.length ? new DecorationSet(local, children) : empty;\n }\n forChild(offset, node) {\n if (this == empty)\n return this;\n if (node.isLeaf)\n return DecorationSet.empty;\n let child, local;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] >= offset) {\n if (this.children[i] == offset)\n child = this.children[i + 2];\n break;\n }\n let start = offset + 1, end = start + node.content.size;\n for (let i = 0; i < this.local.length; i++) {\n let dec = this.local[i];\n if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n if (from < to)\n (local || (local = [])).push(dec.copy(from, to));\n }\n }\n if (local) {\n let localSet = new DecorationSet(local.sort(byPos), none);\n return child ? new DecorationGroup([localSet, child]) : localSet;\n }\n return child || empty;\n }\n /**\n @internal\n */\n eq(other) {\n if (this == other)\n return true;\n if (!(other instanceof DecorationSet) ||\n this.local.length != other.local.length ||\n this.children.length != other.children.length)\n return false;\n for (let i = 0; i < this.local.length; i++)\n if (!this.local[i].eq(other.local[i]))\n return false;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] != other.children[i] ||\n this.children[i + 1] != other.children[i + 1] ||\n !this.children[i + 2].eq(other.children[i + 2]))\n return false;\n return true;\n }\n /**\n @internal\n */\n locals(node) {\n return removeOverlap(this.localsInner(node));\n }\n /**\n @internal\n */\n localsInner(node) {\n if (this == empty)\n return none;\n if (node.inlineContent || !this.local.some(InlineType.is))\n return this.local;\n let result = [];\n for (let i = 0; i < this.local.length; i++) {\n if (!(this.local[i].type instanceof InlineType))\n result.push(this.local[i]);\n }\n return result;\n }\n forEachSet(f) { f(this); }\n}\n/**\nThe empty set of decorations.\n*/\nDecorationSet.empty = new DecorationSet([], []);\n/**\n@internal\n*/\nDecorationSet.removeOverlap = removeOverlap;\nconst empty = DecorationSet.empty;\n// An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nclass DecorationGroup {\n constructor(members) {\n this.members = members;\n }\n map(mapping, doc) {\n const mappedDecos = this.members.map(member => member.map(mapping, doc, noSpec));\n return DecorationGroup.from(mappedDecos);\n }\n forChild(offset, child) {\n if (child.isLeaf)\n return DecorationSet.empty;\n let found = [];\n for (let i = 0; i < this.members.length; i++) {\n let result = this.members[i].forChild(offset, child);\n if (result == empty)\n continue;\n if (result instanceof DecorationGroup)\n found = found.concat(result.members);\n else\n found.push(result);\n }\n return DecorationGroup.from(found);\n }\n eq(other) {\n if (!(other instanceof DecorationGroup) ||\n other.members.length != this.members.length)\n return false;\n for (let i = 0; i < this.members.length; i++)\n if (!this.members[i].eq(other.members[i]))\n return false;\n return true;\n }\n locals(node) {\n let result, sorted = true;\n for (let i = 0; i < this.members.length; i++) {\n let locals = this.members[i].localsInner(node);\n if (!locals.length)\n continue;\n if (!result) {\n result = locals;\n }\n else {\n if (sorted) {\n result = result.slice();\n sorted = false;\n }\n for (let j = 0; j < locals.length; j++)\n result.push(locals[j]);\n }\n }\n return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;\n }\n // Create a group for the given array of decoration sets, or return\n // a single set when possible.\n static from(members) {\n switch (members.length) {\n case 0: return empty;\n case 1: return members[0];\n default: return new DecorationGroup(members.every(m => m instanceof DecorationSet) ? members :\n members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));\n }\n }\n forEachSet(f) {\n for (let i = 0; i < this.members.length; i++)\n this.members[i].forEachSet(f);\n }\n}\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n let children = oldChildren.slice();\n // Mark the children that are directly touched by changes, and\n // move those that are after the changes.\n for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {\n let moved = 0;\n mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {\n let dSize = (newEnd - newStart) - (oldEnd - oldStart);\n for (let i = 0; i < children.length; i += 3) {\n let end = children[i + 1];\n if (end < 0 || oldStart > end + baseOffset - moved)\n continue;\n let start = children[i] + baseOffset - moved;\n if (oldEnd >= start) {\n children[i + 1] = oldStart <= start ? -2 : -1;\n }\n else if (oldStart >= baseOffset && dSize) {\n children[i] += dSize;\n children[i + 1] += dSize;\n }\n }\n moved += dSize;\n });\n baseOffset = mapping.maps[i].map(baseOffset, -1);\n }\n // Find the child nodes that still correspond to a single node,\n // recursively call mapInner on them and update their positions.\n let mustRebuild = false;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) { // Touched nodes\n if (children[i + 1] == -2) {\n mustRebuild = true;\n children[i + 1] = -1;\n continue;\n }\n let from = mapping.map(oldChildren[i] + oldOffset), fromLocal = from - offset;\n if (fromLocal < 0 || fromLocal >= node.content.size) {\n mustRebuild = true;\n continue;\n }\n // Must read oldChildren because children was tagged with -1\n let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;\n let { index, offset: childOffset } = node.content.findIndex(fromLocal);\n let childNode = node.maybeChild(index);\n if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n let mapped = children[i + 2]\n .mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options);\n if (mapped != empty) {\n children[i] = fromLocal;\n children[i + 1] = toLocal;\n children[i + 2] = mapped;\n }\n else {\n children[i + 1] = -2;\n mustRebuild = true;\n }\n }\n else {\n mustRebuild = true;\n }\n }\n // Remaining children must be collected and rebuilt into the appropriate structure\n if (mustRebuild) {\n let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);\n let built = buildTree(decorations, node, 0, options);\n newLocal = built.local;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) {\n children.splice(i, 3);\n i -= 3;\n }\n for (let i = 0, j = 0; i < built.children.length; i += 3) {\n let from = built.children[i];\n while (j < children.length && children[j] < from)\n j += 3;\n children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);\n }\n }\n return new DecorationSet(newLocal.sort(byPos), children);\n}\nfunction moveSpans(spans, offset) {\n if (!offset || !spans.length)\n return spans;\n let result = [];\n for (let i = 0; i < spans.length; i++) {\n let span = spans[i];\n result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n }\n return result;\n}\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n // Gather all decorations from the remaining marked children\n function gather(set, oldOffset) {\n for (let i = 0; i < set.local.length; i++) {\n let mapped = set.local[i].map(mapping, offset, oldOffset);\n if (mapped)\n decorations.push(mapped);\n else if (options.onRemove)\n options.onRemove(set.local[i].spec);\n }\n for (let i = 0; i < set.children.length; i += 3)\n gather(set.children[i + 2], set.children[i] + oldOffset + 1);\n }\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] == -1)\n gather(children[i + 2], oldChildren[i] + oldOffset + 1);\n return decorations;\n}\nfunction takeSpansForNode(spans, node, offset) {\n if (node.isLeaf)\n return null;\n let end = offset + node.nodeSize, found = null;\n for (let i = 0, span; i < spans.length; i++) {\n if ((span = spans[i]) && span.from > offset && span.to < end) {\n (found || (found = [])).push(span);\n spans[i] = null;\n }\n }\n return found;\n}\nfunction withoutNulls(array) {\n let result = [];\n for (let i = 0; i < array.length; i++)\n if (array[i] != null)\n result.push(array[i]);\n return result;\n}\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtracted from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n let children = [], hasNulls = false;\n node.forEach((childNode, localStart) => {\n let found = takeSpansForNode(spans, childNode, localStart + offset);\n if (found) {\n hasNulls = true;\n let subtree = buildTree(found, childNode, offset + localStart + 1, options);\n if (subtree != empty)\n children.push(localStart, localStart + childNode.nodeSize, subtree);\n }\n });\n let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n for (let i = 0; i < locals.length; i++)\n if (!locals[i].type.valid(node, locals[i])) {\n if (options.onRemove)\n options.onRemove(locals[i].spec);\n locals.splice(i--, 1);\n }\n return locals.length || children.length ? new DecorationSet(locals, children) : empty;\n}\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n return a.from - b.from || a.to - b.to;\n}\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n let working = spans;\n for (let i = 0; i < working.length - 1; i++) {\n let span = working[i];\n if (span.from != span.to)\n for (let j = i + 1; j < working.length; j++) {\n let next = working[j];\n if (next.from == span.from) {\n if (next.to != span.to) {\n if (working == spans)\n working = spans.slice();\n // Followed by a partially overlapping larger span. Split that\n // span.\n working[j] = next.copy(next.from, span.to);\n insertAhead(working, j + 1, next.copy(span.to, next.to));\n }\n continue;\n }\n else {\n if (next.from < span.to) {\n if (working == spans)\n working = spans.slice();\n // The end of this one overlaps with a subsequent span. Split\n // this one.\n working[i] = span.copy(span.from, next.from);\n insertAhead(working, j, span.copy(next.from, span.to));\n }\n break;\n }\n }\n }\n return working;\n}\nfunction insertAhead(array, i, deco) {\n while (i < array.length && byPos(deco, array[i]) > 0)\n i++;\n array.splice(i, 0, deco);\n}\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n let found = [];\n view.someProp(\"decorations\", f => {\n let result = f(view.state);\n if (result && result != empty)\n found.push(result);\n });\n if (view.cursorWrapper)\n found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));\n return DecorationGroup.from(found);\n}\n\nconst observeOptions = {\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributes: true,\n attributeOldValue: true,\n subtree: true\n};\n// IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified\nconst useCharData = ie && ie_version <= 11;\nclass SelectionState {\n constructor() {\n this.anchorNode = null;\n this.anchorOffset = 0;\n this.focusNode = null;\n this.focusOffset = 0;\n }\n set(sel) {\n this.anchorNode = sel.anchorNode;\n this.anchorOffset = sel.anchorOffset;\n this.focusNode = sel.focusNode;\n this.focusOffset = sel.focusOffset;\n }\n clear() {\n this.anchorNode = this.focusNode = null;\n }\n eq(sel) {\n return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;\n }\n}\nclass DOMObserver {\n constructor(view, handleDOMChange) {\n this.view = view;\n this.handleDOMChange = handleDOMChange;\n this.queue = [];\n this.flushingSoon = -1;\n this.observer = null;\n this.currentSelection = new SelectionState;\n this.onCharData = null;\n this.suppressingSelectionUpdates = false;\n this.lastChangedTextNode = null;\n this.observer = window.MutationObserver &&\n new window.MutationObserver(mutations => {\n for (let i = 0; i < mutations.length; i++)\n this.queue.push(mutations[i]);\n // IE11 will sometimes (on backspacing out a single character\n // text node after a BR node) call the observer callback\n // before actually updating the DOM, which will cause\n // ProseMirror to miss the change (see #930)\n if (ie && ie_version <= 11 && mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length))\n this.flushSoon();\n else\n this.flush();\n });\n if (useCharData) {\n this.onCharData = e => {\n this.queue.push({ target: e.target, type: \"characterData\", oldValue: e.prevValue });\n this.flushSoon();\n };\n }\n this.onSelectionChange = this.onSelectionChange.bind(this);\n }\n flushSoon() {\n if (this.flushingSoon < 0)\n this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20);\n }\n forceFlush() {\n if (this.flushingSoon > -1) {\n window.clearTimeout(this.flushingSoon);\n this.flushingSoon = -1;\n this.flush();\n }\n }\n start() {\n if (this.observer) {\n this.observer.takeRecords();\n this.observer.observe(this.view.dom, observeOptions);\n }\n if (this.onCharData)\n this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.connectSelection();\n }\n stop() {\n if (this.observer) {\n let take = this.observer.takeRecords();\n if (take.length) {\n for (let i = 0; i < take.length; i++)\n this.queue.push(take[i]);\n window.setTimeout(() => this.flush(), 20);\n }\n this.observer.disconnect();\n }\n if (this.onCharData)\n this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.disconnectSelection();\n }\n connectSelection() {\n this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n }\n disconnectSelection() {\n this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n }\n suppressSelectionUpdates() {\n this.suppressingSelectionUpdates = true;\n setTimeout(() => this.suppressingSelectionUpdates = false, 50);\n }\n onSelectionChange() {\n if (!hasFocusAndSelection(this.view))\n return;\n if (this.suppressingSelectionUpdates)\n return selectionToDOM(this.view);\n // Deletions on IE11 fire their events in the wrong order, giving\n // us a selection change event before the DOM changes are\n // reported.\n if (ie && ie_version <= 11 && !this.view.state.selection.empty) {\n let sel = this.view.domSelectionRange();\n // Selection.isCollapsed isn't reliable on IE\n if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n return this.flushSoon();\n }\n this.flush();\n }\n setCurSelection() {\n this.currentSelection.set(this.view.domSelectionRange());\n }\n ignoreSelectionChange(sel) {\n if (!sel.focusNode)\n return true;\n let ancestors = new Set, container;\n for (let scan = sel.focusNode; scan; scan = parentNode(scan))\n ancestors.add(scan);\n for (let scan = sel.anchorNode; scan; scan = parentNode(scan))\n if (ancestors.has(scan)) {\n container = scan;\n break;\n }\n let desc = container && this.view.docView.nearestDesc(container);\n if (desc && desc.ignoreMutation({\n type: \"selection\",\n target: container.nodeType == 3 ? container.parentNode : container\n })) {\n this.setCurSelection();\n return true;\n }\n }\n pendingRecords() {\n if (this.observer)\n for (let mut of this.observer.takeRecords())\n this.queue.push(mut);\n return this.queue;\n }\n flush() {\n let { view } = this;\n if (!view.docView || this.flushingSoon > -1)\n return;\n let mutations = this.pendingRecords();\n if (mutations.length)\n this.queue = [];\n let sel = view.domSelectionRange();\n let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);\n let from = -1, to = -1, typeOver = false, added = [];\n if (view.editable) {\n for (let i = 0; i < mutations.length; i++) {\n let result = this.registerMutation(mutations[i], added);\n if (result) {\n from = from < 0 ? result.from : Math.min(result.from, from);\n to = to < 0 ? result.to : Math.max(result.to, to);\n if (result.typeOver)\n typeOver = true;\n }\n }\n }\n if (gecko && added.length) {\n let brs = added.filter(n => n.nodeName == \"BR\");\n if (brs.length == 2) {\n let [a, b] = brs;\n if (a.parentNode && a.parentNode.parentNode == b.parentNode)\n b.remove();\n else\n a.remove();\n }\n else {\n let { focusNode } = this.currentSelection;\n for (let br of brs) {\n let parent = br.parentNode;\n if (parent && parent.nodeName == \"LI\" && (!focusNode || blockParent(view, focusNode) != parent))\n br.remove();\n }\n }\n }\n let readSel = null;\n // If it looks like the browser has reset the selection to the\n // start of the document after focus, restore the selection from\n // the state\n if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 &&\n Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 &&\n selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) &&\n readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {\n view.input.lastFocus = 0;\n selectionToDOM(view);\n this.currentSelection.set(sel);\n view.scrollToSelection();\n }\n else if (from > -1 || newSel) {\n if (from > -1) {\n view.docView.markDirty(from, to);\n checkCSS(view);\n }\n this.handleDOMChange(from, to, typeOver, added);\n if (view.docView && view.docView.dirty)\n view.updateState(view.state);\n else if (!this.currentSelection.eq(sel))\n selectionToDOM(view);\n this.currentSelection.set(sel);\n }\n }\n registerMutation(mut, added) {\n // Ignore mutations inside nodes that were already noted as inserted\n if (added.indexOf(mut.target) > -1)\n return null;\n let desc = this.view.docView.nearestDesc(mut.target);\n if (mut.type == \"attributes\" &&\n (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n // Firefox sometimes fires spurious events for null/empty styles\n (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n return null;\n if (!desc || desc.ignoreMutation(mut))\n return null;\n if (mut.type == \"childList\") {\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let node = mut.addedNodes[i];\n added.push(node);\n if (node.nodeType == 3)\n this.lastChangedTextNode = node;\n }\n if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))\n return { from: desc.posBefore, to: desc.posAfter };\n let prev = mut.previousSibling, next = mut.nextSibling;\n if (ie && ie_version <= 11 && mut.addedNodes.length) {\n // IE11 gives us incorrect next/prev siblings for some\n // insertions, so if there are added nodes, recompute those\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let { previousSibling, nextSibling } = mut.addedNodes[i];\n if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)\n prev = previousSibling;\n if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)\n next = nextSibling;\n }\n }\n let fromOffset = prev && prev.parentNode == mut.target\n ? domIndex(prev) + 1 : 0;\n let from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n let toOffset = next && next.parentNode == mut.target\n ? domIndex(next) : mut.target.childNodes.length;\n let to = desc.localPosFromDOM(mut.target, toOffset, 1);\n return { from, to };\n }\n else if (mut.type == \"attributes\") {\n return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };\n }\n else { // \"characterData\"\n this.lastChangedTextNode = mut.target;\n return {\n from: desc.posAtStart,\n to: desc.posAtEnd,\n // An event was generated for a text change that didn't change\n // any text. Mark the dom change to fall back to assuming the\n // selection was typed over with an identical value if it can't\n // find another change.\n typeOver: mut.target.nodeValue == mut.oldValue\n };\n }\n }\n}\nlet cssChecked = new WeakMap();\nlet cssCheckWarned = false;\nfunction checkCSS(view) {\n if (cssChecked.has(view))\n return;\n cssChecked.set(view, null);\n if (['normal', 'nowrap', 'pre-line'].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {\n view.requiresGeckoHackNode = gecko;\n if (cssCheckWarned)\n return;\n console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\");\n cssCheckWarned = true;\n }\n}\nfunction rangeToSelectionRange(view, range) {\n let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n let focusNode = range.endContainer, focusOffset = range.endOffset;\n let currentAnchor = view.domAtPos(view.state.selection.anchor);\n // Since such a range doesn't distinguish between anchor and head,\n // use a heuristic that flips it around if its end matches the\n // current anchor.\n if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))\n [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n// Used to work around a Safari Selection/shadow DOM bug\n// Based on https://github.com/codemirror/dev/issues/414 fix\nfunction safariShadowSelectionRange(view, selection) {\n if (selection.getComposedRanges) {\n let range = selection.getComposedRanges(view.root)[0];\n if (range)\n return rangeToSelectionRange(view, range);\n }\n let found;\n function read(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n found = event.getTargetRanges()[0];\n }\n // Because Safari (at least in 2018-2022) doesn't provide regular\n // access to the selection inside a shadowRoot, we have to perform a\n // ridiculous hack to get at it—using `execCommand` to trigger a\n // `beforeInput` event so that we can read the target range from the\n // event.\n view.dom.addEventListener(\"beforeinput\", read, true);\n document.execCommand(\"indent\");\n view.dom.removeEventListener(\"beforeinput\", read, true);\n return found ? rangeToSelectionRange(view, found) : null;\n}\nfunction blockParent(view, node) {\n for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {\n let desc = view.docView.nearestDesc(p, true);\n if (desc && desc.node.isBlock)\n return p;\n }\n return null;\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\nfunction parseBetween(view, from_, to_) {\n let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);\n let domSel = view.domSelectionRange();\n let find;\n let anchor = domSel.anchorNode;\n if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {\n find = [{ node: anchor, offset: domSel.anchorOffset }];\n if (!selectionCollapsed(domSel))\n find.push({ node: domSel.focusNode, offset: domSel.focusOffset });\n }\n // Work around issue in Chrome where backspacing sometimes replaces\n // the deleted content with a random BR node (issues #799, #831)\n if (chrome && view.input.lastKeyCode === 8) {\n for (let off = toOffset; off > fromOffset; off--) {\n let node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n if (node.nodeName == \"BR\" && !desc) {\n toOffset = off;\n break;\n }\n if (!desc || desc.size)\n break;\n }\n }\n let startDoc = view.state.doc;\n let parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n let $from = startDoc.resolve(from);\n let sel = null, doc = parser.parse(parent, {\n topNode: $from.parent,\n topMatch: $from.parent.contentMatchAt($from.index()),\n topOpen: true,\n from: fromOffset,\n to: toOffset,\n preserveWhitespace: $from.parent.type.whitespace == \"pre\" ? \"full\" : true,\n findPositions: find,\n ruleFromNode,\n context: $from\n });\n if (find && find[0].pos != null) {\n let anchor = find[0].pos, head = find[1] && find[1].pos;\n if (head == null)\n head = anchor;\n sel = { anchor: anchor + from, head: head + from };\n }\n return { doc, sel, from, to };\n}\nfunction ruleFromNode(dom) {\n let desc = dom.pmViewDesc;\n if (desc) {\n return desc.parseRule();\n }\n else if (dom.nodeName == \"BR\" && dom.parentNode) {\n // Safari replaces the list item or table cell with a BR\n // directly in the list node (?!) if you delete the last\n // character in a list item or table cell (#708, #862)\n if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n let skip = document.createElement(\"div\");\n skip.appendChild(document.createElement(\"li\"));\n return { skip };\n }\n else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n return { ignore: true };\n }\n }\n else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n return { ignore: true };\n }\n return null;\n}\nconst isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);\n view.input.compositionPendingChanges = 0;\n if (from < 0) {\n let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;\n let newSel = selectionFromDOM(view, origin);\n if (newSel && !view.state.selection.eq(newSel)) {\n if (chrome && android &&\n view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\"))))\n return;\n let tr = view.state.tr.setSelection(newSel);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n else if (origin == \"key\")\n tr.scrollIntoView();\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n return;\n }\n let $before = view.state.doc.resolve(from);\n let shared = $before.sharedDepth(to);\n from = $before.before(shared + 1);\n to = view.state.doc.resolve(to).after(shared + 1);\n let sel = view.state.selection;\n let parse = parseBetween(view, from, to);\n let doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n let preferredPos, preferredSide;\n // Prefer anchoring to end when Backspace is pressed\n if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {\n preferredPos = view.state.selection.to;\n preferredSide = \"end\";\n }\n else {\n preferredPos = view.state.selection.from;\n preferredSide = \"start\";\n }\n view.input.lastKeyCode = null;\n let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n if (change)\n view.input.domChangeCount++;\n if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) &&\n addedNodes.some(n => n.nodeType == 1 && !isInline.test(n.nodeName)) &&\n (!change || change.endA >= change.endB) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n if (!change) {\n if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n change = { start: sel.from, endA: sel.to, endB: sel.to };\n }\n else {\n if (parse.sel) {\n let sel = resolveSelection(view, view.state.doc, parse.sel);\n if (sel && !sel.eq(view.state.selection)) {\n let tr = view.state.tr.setSelection(sel);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n }\n return;\n }\n }\n // Handle the case where overwriting a selection by typing matches\n // the start or end of the selected content, creating a change\n // that's smaller than what was actually overwritten.\n if (view.state.selection.from < view.state.selection.to &&\n change.start == change.endB &&\n view.state.selection instanceof TextSelection) {\n if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 &&\n view.state.selection.from >= parse.from) {\n change.start = view.state.selection.from;\n }\n else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 &&\n view.state.selection.to <= parse.to) {\n change.endB += (view.state.selection.to - change.endA);\n change.endA = view.state.selection.to;\n }\n }\n // IE11 will insert a non-breaking space _ahead_ of the space after\n // the cursor space when adding a space before another space. When\n // that happened, adjust the change to cover the space instead.\n if (ie && ie_version <= 11 && change.endB == change.start + 1 &&\n change.endA == change.start && change.start > parse.from &&\n parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == \" \\u00a0\") {\n change.start--;\n change.endA--;\n change.endB--;\n }\n let $from = parse.doc.resolveNoCache(change.start - parse.from);\n let $to = parse.doc.resolveNoCache(change.endB - parse.from);\n let $fromA = doc.resolve(change.start);\n let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;\n let nextSel;\n // If this looks like the effect of pressing Enter (or was recorded\n // as being an iOS enter press), just dispatch an Enter key instead.\n if (((ios && view.input.lastIOSEnter > Date.now() - 225 &&\n (!inlineChange || addedNodes.some(n => n.nodeName == \"DIV\" || n.nodeName == \"P\"))) ||\n (!inlineChange && $from.pos < parse.doc.content.size && !$from.sameParent($to) &&\n (nextSel = Selection.findFrom(parse.doc.resolve($from.pos + 1), 1, true)) &&\n nextSel.head == $to.pos)) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n // Same for backspace\n if (view.state.selection.anchor > change.start &&\n looksLikeBackspace(doc, change.start, change.endA, $from, $to) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\")))) {\n if (android && chrome)\n view.domObserver.suppressSelectionUpdates(); // #820\n return;\n }\n // Chrome will occasionally, during composition, delete the\n // entire composition and then immediately insert it again. This is\n // used to detect that situation.\n if (chrome && change.endB == change.start)\n view.input.lastChromeDelete = Date.now();\n // This tries to detect Android virtual keyboard\n // enter-and-pick-suggestion action. That sometimes (see issue\n // #1059) first fires a DOM mutation, before moving the selection to\n // the newly created block. And then, because ProseMirror cleans up\n // the DOM selection, it gives up moving the selection entirely,\n // leaving the cursor in the wrong place. When that happens, we drop\n // the new paragraph from the initial change, and fire a simulated\n // enter key afterwards.\n if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n change.endB -= 2;\n $to = parse.doc.resolveNoCache(change.endB - parse.from);\n setTimeout(() => {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n }, 20);\n }\n let chFrom = change.start, chTo = change.endA;\n let tr, storedMarks, markChange;\n if (inlineChange) {\n if ($from.pos == $to.pos) { // Deletion\n // IE11 sometimes weirdly moves the DOM selection around after\n // backspacing out the first element in a textblock\n if (ie && ie_version <= 11 && $from.parentOffset == 0) {\n view.domObserver.suppressSelectionUpdates();\n setTimeout(() => selectionToDOM(view), 20);\n }\n tr = view.state.tr.delete(chFrom, chTo);\n storedMarks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n }\n else if ( // Adding or removing a mark\n change.endA == change.endB &&\n (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) {\n tr = view.state.tr;\n if (markChange.type == \"add\")\n tr.addMark(chFrom, chTo, markChange.mark);\n else\n tr.removeMark(chFrom, chTo, markChange.mark);\n }\n else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n // Both positions in the same text node -- simply insert text\n let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n if (view.someProp(\"handleTextInput\", f => f(view, chFrom, chTo, text)))\n return;\n tr = view.state.tr.insertText(text, chFrom, chTo);\n }\n }\n if (!tr)\n tr = view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));\n if (parse.sel) {\n let sel = resolveSelection(view, tr.doc, parse.sel);\n // Chrome will sometimes, during composition, report the\n // selection in the wrong place. If it looks like that is\n // happening, don't update the selection.\n // Edge just doesn't move the cursor forward when you start typing\n // in an empty block or between br nodes.\n if (sel && !(chrome && view.composing && sel.empty &&\n (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) &&\n (sel.head == chFrom || sel.head == tr.mapping.map(chTo) - 1) ||\n ie && sel.empty && sel.head == chFrom))\n tr.setSelection(sel);\n }\n if (storedMarks)\n tr.ensureMarks(storedMarks);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr.scrollIntoView());\n}\nfunction resolveSelection(view, doc, parsedSel) {\n if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size)\n return null;\n return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));\n}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n let added = curMarks, removed = prevMarks, type, mark, update;\n for (let i = 0; i < prevMarks.length; i++)\n added = prevMarks[i].removeFromSet(added);\n for (let i = 0; i < curMarks.length; i++)\n removed = curMarks[i].removeFromSet(removed);\n if (added.length == 1 && removed.length == 0) {\n mark = added[0];\n type = \"add\";\n update = (node) => node.mark(mark.addToSet(node.marks));\n }\n else if (added.length == 0 && removed.length == 1) {\n mark = removed[0];\n type = \"remove\";\n update = (node) => node.mark(mark.removeFromSet(node.marks));\n }\n else {\n return null;\n }\n let updated = [];\n for (let i = 0; i < prev.childCount; i++)\n updated.push(update(prev.child(i)));\n if (Fragment.from(updated).eq(cur))\n return { mark, type };\n}\nfunction looksLikeBackspace(old, start, end, $newStart, $newEnd) {\n if ( // The content must have shrunk\n end - start <= $newEnd.pos - $newStart.pos ||\n // newEnd must point directly at or after the end of the block that newStart points into\n skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n return false;\n let $start = old.resolve(start);\n // Handle the case where, rather than joining blocks, the change just removed an entire block\n if (!$newStart.parent.isTextblock) {\n let after = $start.nodeAfter;\n return after != null && end == start + after.nodeSize;\n }\n // Start must be at the end of a block\n if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n return false;\n let $next = old.resolve(skipClosingAndOpening($start, true, true));\n // The next textblock must start before end and end near it\n if (!$next.parent.isTextblock || $next.pos > end ||\n skipClosingAndOpening($next, true, false) < end)\n return false;\n // The fragments after the join point must match\n return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);\n}\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n depth--;\n end++;\n fromEnd = false;\n }\n if (mayOpen) {\n let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n while (next && !next.isLeaf) {\n next = next.firstChild;\n end++;\n }\n }\n return end;\n}\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n let start = a.findDiffStart(b, pos);\n if (start == null)\n return null;\n let { a: endA, b: endB } = a.findDiffEnd(b, pos + a.size, pos + b.size);\n if (preferredSide == \"end\") {\n let adjust = Math.max(0, start - Math.min(endA, endB));\n preferredPos -= endA + adjust - start;\n }\n if (endA < start && a.size < b.size) {\n let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n start -= move;\n if (start && start < b.size && isSurrogatePair(b.textBetween(start - 1, start + 1)))\n start += move ? 1 : -1;\n endB = start + (endB - endA);\n endA = start;\n }\n else if (endB < start) {\n let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n start -= move;\n if (start && start < a.size && isSurrogatePair(a.textBetween(start - 1, start + 1)))\n start += move ? 1 : -1;\n endA = start + (endA - endB);\n endB = start;\n }\n return { start, endA, endB };\n}\nfunction isSurrogatePair(str) {\n if (str.length != 2)\n return false;\n let a = str.charCodeAt(0), b = str.charCodeAt(1);\n return a >= 0xDC00 && a <= 0xDFFF && b >= 0xD800 && b <= 0xDBFF;\n}\n\n/**\n@internal\n*/\nconst __serializeForClipboard = serializeForClipboard;\n/**\n@internal\n*/\nconst __parseFromClipboard = parseFromClipboard;\n/**\n@internal\n*/\nconst __endComposition = endComposition;\n/**\nAn editor view manages the DOM structure that represents an\neditable document. Its state and behavior are determined by its\n[props](https://prosemirror.net/docs/ref/#view.DirectEditorProps).\n*/\nclass EditorView {\n /**\n Create a view. `place` may be a DOM node that the editor should\n be appended to, a function that will place it into the document,\n or an object whose `mount` property holds the node to use as the\n document container. If it is `null`, the editor will not be\n added to the document.\n */\n constructor(place, props) {\n this._root = null;\n /**\n @internal\n */\n this.focused = false;\n /**\n Kludge used to work around a Chrome bug @internal\n */\n this.trackWrites = null;\n this.mounted = false;\n /**\n @internal\n */\n this.markCursor = null;\n /**\n @internal\n */\n this.cursorWrapper = null;\n /**\n @internal\n */\n this.lastSelectedViewDesc = undefined;\n /**\n @internal\n */\n this.input = new InputState;\n this.prevDirectPlugins = [];\n this.pluginViews = [];\n /**\n Holds `true` when a hack node is needed in Firefox to prevent the\n [space is eaten issue](https://github.com/ProseMirror/prosemirror/issues/651)\n @internal\n */\n this.requiresGeckoHackNode = false;\n /**\n When editor content is being dragged, this object contains\n information about the dragged slice and whether it is being\n copied or moved. At any other time, it is null.\n */\n this.dragging = null;\n this._props = props;\n this.state = props.state;\n this.directPlugins = props.plugins || [];\n this.directPlugins.forEach(checkStateComponent);\n this.dispatch = this.dispatch.bind(this);\n this.dom = (place && place.mount) || document.createElement(\"div\");\n if (place) {\n if (place.appendChild)\n place.appendChild(this.dom);\n else if (typeof place == \"function\")\n place(this.dom);\n else if (place.mount)\n this.mounted = true;\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n this.nodeViews = buildNodeViews(this);\n this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added));\n this.domObserver.start();\n initInput(this);\n this.updatePluginViews();\n }\n /**\n Holds `true` when a\n [composition](https://w3c.github.io/uievents/#events-compositionevents)\n is active.\n */\n get composing() { return this.input.composing; }\n /**\n The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).\n */\n get props() {\n if (this._props.state != this.state) {\n let prev = this._props;\n this._props = {};\n for (let name in prev)\n this._props[name] = prev[name];\n this._props.state = this.state;\n }\n return this._props;\n }\n /**\n Update the view's props. Will immediately cause an update to\n the DOM.\n */\n update(props) {\n if (props.handleDOMEvents != this._props.handleDOMEvents)\n ensureListeners(this);\n let prevProps = this._props;\n this._props = props;\n if (props.plugins) {\n props.plugins.forEach(checkStateComponent);\n this.directPlugins = props.plugins;\n }\n this.updateStateInner(props.state, prevProps);\n }\n /**\n Update the view by updating existing props object with the object\n given as argument. Equivalent to `view.update(Object.assign({},\n view.props, props))`.\n */\n setProps(props) {\n let updated = {};\n for (let name in this._props)\n updated[name] = this._props[name];\n updated.state = this.state;\n for (let name in props)\n updated[name] = props[name];\n this.update(updated);\n }\n /**\n Update the editor's `state` prop, without touching any of the\n other props.\n */\n updateState(state) {\n this.updateStateInner(state, this._props);\n }\n updateStateInner(state, prevProps) {\n var _a;\n let prev = this.state, redraw = false, updateSel = false;\n // When stored marks are added, stop composition, so that they can\n // be displayed.\n if (state.storedMarks && this.composing) {\n clearComposition(this);\n updateSel = true;\n }\n this.state = state;\n let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;\n if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {\n let nodeViews = buildNodeViews(this);\n if (changedNodeViews(nodeViews, this.nodeViews)) {\n this.nodeViews = nodeViews;\n redraw = true;\n }\n }\n if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {\n ensureListeners(this);\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? \"reset\"\n : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n if (updateDoc || !state.selection.eq(prev.selection))\n updateSel = true;\n let oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n if (updateSel) {\n this.domObserver.stop();\n // Work around an issue in Chrome, IE, and Edge where changing\n // the DOM around an active selection puts it into a broken\n // state where the thing the user sees differs from the\n // selection reported by the Selection object (#710, #973,\n // #1011, #1013, #1035).\n let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing &&\n !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n if (updateDoc) {\n // If the node that the selection points into is written to,\n // Chrome sometimes starts misreporting the selection, so this\n // tracks that and forces a selection reset when our update\n // did write to the node.\n let chromeKludge = chrome ? (this.trackWrites = this.domSelectionRange().focusNode) : null;\n if (this.composing)\n this.input.compositionNode = findCompositionNode(this);\n if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n this.docView.updateOuterDeco(outerDeco);\n this.docView.destroy();\n this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n }\n if (chromeKludge && !this.trackWrites)\n forceSelUpdate = true;\n }\n // Work around for an issue where an update arriving right between\n // a DOM selection change and the \"selectionchange\" event for it\n // can cause a spurious DOM selection update, disrupting mouse\n // drag selection.\n if (forceSelUpdate ||\n !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) &&\n anchorInRightPlace(this))) {\n selectionToDOM(this, forceSelUpdate);\n }\n else {\n syncNodeSelection(this, state.selection);\n this.domObserver.setCurSelection();\n }\n this.domObserver.start();\n }\n this.updatePluginViews(prev);\n if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))\n this.updateDraggedNode(this.dragging, prev);\n if (scroll == \"reset\") {\n this.dom.scrollTop = 0;\n }\n else if (scroll == \"to selection\") {\n this.scrollToSelection();\n }\n else if (oldScrollPos) {\n resetScrollPos(oldScrollPos);\n }\n }\n /**\n @internal\n */\n scrollToSelection() {\n let startDOM = this.domSelectionRange().focusNode;\n if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ;\n else if (this.someProp(\"handleScrollToSelection\", f => f(this))) ;\n else if (this.state.selection instanceof NodeSelection) {\n let target = this.docView.domAfterPos(this.state.selection.from);\n if (target.nodeType == 1)\n scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);\n }\n else {\n scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);\n }\n }\n destroyPluginViews() {\n let view;\n while (view = this.pluginViews.pop())\n if (view.destroy)\n view.destroy();\n }\n updatePluginViews(prevState) {\n if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {\n this.prevDirectPlugins = this.directPlugins;\n this.destroyPluginViews();\n for (let i = 0; i < this.directPlugins.length; i++) {\n let plugin = this.directPlugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n for (let i = 0; i < this.state.plugins.length; i++) {\n let plugin = this.state.plugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n }\n else {\n for (let i = 0; i < this.pluginViews.length; i++) {\n let pluginView = this.pluginViews[i];\n if (pluginView.update)\n pluginView.update(this, prevState);\n }\n }\n }\n updateDraggedNode(dragging, prev) {\n let sel = dragging.node, found = -1;\n if (this.state.doc.nodeAt(sel.from) == sel.node) {\n found = sel.from;\n }\n else {\n let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);\n let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos);\n if (moved == sel.node)\n found = movedPos;\n }\n this.dragging = new Dragging(dragging.slice, dragging.move, found < 0 ? undefined : NodeSelection.create(this.state.doc, found));\n }\n someProp(propName, f) {\n let prop = this._props && this._props[propName], value;\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n for (let i = 0; i < this.directPlugins.length; i++) {\n let prop = this.directPlugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n let plugins = this.state.plugins;\n if (plugins)\n for (let i = 0; i < plugins.length; i++) {\n let prop = plugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n }\n /**\n Query whether the view has focus.\n */\n hasFocus() {\n // Work around IE not handling focus correctly if resize handles are shown.\n // If the cursor is inside an element with resize handles, activeElement\n // will be that element instead of this.dom.\n if (ie) {\n // If activeElement is within this.dom, and there are no other elements\n // setting `contenteditable` to false in between, treat it as focused.\n let node = this.root.activeElement;\n if (node == this.dom)\n return true;\n if (!node || !this.dom.contains(node))\n return false;\n while (node && this.dom != node && this.dom.contains(node)) {\n if (node.contentEditable == 'false')\n return false;\n node = node.parentElement;\n }\n return true;\n }\n return this.root.activeElement == this.dom;\n }\n /**\n Focus the editor.\n */\n focus() {\n this.domObserver.stop();\n if (this.editable)\n focusPreventScroll(this.dom);\n selectionToDOM(this);\n this.domObserver.start();\n }\n /**\n Get the document root in which the editor exists. This will\n usually be the top-level `document`, but might be a [shadow\n DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n root if the editor is inside one.\n */\n get root() {\n let cached = this._root;\n if (cached == null)\n for (let search = this.dom.parentNode; search; search = search.parentNode) {\n if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n if (!search.getSelection)\n Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();\n return this._root = search;\n }\n }\n return cached || document;\n }\n /**\n When an existing editor view is moved to a new document or\n shadow tree, call this to make it recompute its root.\n */\n updateRoot() {\n this._root = null;\n }\n /**\n Given a pair of viewport coordinates, return the document\n position that corresponds to them. May return null if the given\n coordinates aren't inside of the editor. When an object is\n returned, its `pos` property is the position nearest to the\n coordinates, and its `inside` property holds the position of the\n inner node that the position falls inside of, or -1 if it is at\n the top level, not in any node.\n */\n posAtCoords(coords) {\n return posAtCoords(this, coords);\n }\n /**\n Returns the viewport rectangle at a given document position.\n `left` and `right` will be the same number, as this returns a\n flat cursor-ish rectangle. If the position is between two things\n that aren't directly adjacent, `side` determines which element\n is used. When < 0, the element before the position is used,\n otherwise the element after.\n */\n coordsAtPos(pos, side = 1) {\n return coordsAtPos(this, pos, side);\n }\n /**\n Find the DOM position that corresponds to the given document\n position. When `side` is negative, find the position as close as\n possible to the content before the position. When positive,\n prefer positions close to the content after the position. When\n zero, prefer as shallow a position as possible.\n \n Note that you should **not** mutate the editor's internal DOM,\n only inspect it (and even that is usually not necessary).\n */\n domAtPos(pos, side = 0) {\n return this.docView.domFromPos(pos, side);\n }\n /**\n Find the DOM node that represents the document node after the\n given position. May return `null` when the position doesn't point\n in front of a node or if the node is inside an opaque node view.\n \n This is intended to be able to call things like\n `getBoundingClientRect` on that DOM node. Do **not** mutate the\n editor DOM directly, or add styling this way, since that will be\n immediately overriden by the editor as it redraws the node.\n */\n nodeDOM(pos) {\n let desc = this.docView.descAt(pos);\n return desc ? desc.nodeDOM : null;\n }\n /**\n Find the document position that corresponds to a given DOM\n position. (Whenever possible, it is preferable to inspect the\n document structure directly, rather than poking around in the\n DOM, but sometimes—for example when interpreting an event\n target—you don't have a choice.)\n \n The `bias` parameter can be used to influence which side of a DOM\n node to use when the position is inside a leaf node.\n */\n posAtDOM(node, offset, bias = -1) {\n let pos = this.docView.posFromDOM(node, offset, bias);\n if (pos == null)\n throw new RangeError(\"DOM position not inside the editor\");\n return pos;\n }\n /**\n Find out whether the selection is at the end of a textblock when\n moving in a given direction. When, for example, given `\"left\"`,\n it will return true if moving left from the current cursor\n position would leave that position's parent textblock. Will apply\n to the view's current state by default, but it is possible to\n pass a different state.\n */\n endOfTextblock(dir, state) {\n return endOfTextblock(this, state || this.state, dir);\n }\n /**\n Run the editor's paste logic with the given HTML string. The\n `event`, if given, will be passed to the\n [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.\n */\n pasteHTML(html, event) {\n return doPaste(this, \"\", html, false, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Run the editor's paste logic with the given plain-text input.\n */\n pasteText(text, event) {\n return doPaste(this, text, null, true, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Removes the editor from the DOM and destroys all [node\n views](https://prosemirror.net/docs/ref/#view.NodeView).\n */\n destroy() {\n if (!this.docView)\n return;\n destroyInput(this);\n this.destroyPluginViews();\n if (this.mounted) {\n this.docView.update(this.state.doc, [], viewDecorations(this), this);\n this.dom.textContent = \"\";\n }\n else if (this.dom.parentNode) {\n this.dom.parentNode.removeChild(this.dom);\n }\n this.docView.destroy();\n this.docView = null;\n clearReusedRange();\n }\n /**\n This is true when the view has been\n [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be\n used anymore).\n */\n get isDestroyed() {\n return this.docView == null;\n }\n /**\n Used for testing.\n */\n dispatchEvent(event) {\n return dispatchEvent(this, event);\n }\n /**\n Dispatch a transaction. Will call\n [`dispatchTransaction`](https://prosemirror.net/docs/ref/#view.DirectEditorProps.dispatchTransaction)\n when given, and otherwise defaults to applying the transaction to\n the current state and calling\n [`updateState`](https://prosemirror.net/docs/ref/#view.EditorView.updateState) with the result.\n This method is bound to the view instance, so that it can be\n easily passed around.\n */\n dispatch(tr) {\n let dispatchTransaction = this._props.dispatchTransaction;\n if (dispatchTransaction)\n dispatchTransaction.call(this, tr);\n else\n this.updateState(this.state.apply(tr));\n }\n /**\n @internal\n */\n domSelectionRange() {\n let sel = this.domSelection();\n if (!sel)\n return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };\n return safari && this.root.nodeType === 11 &&\n deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;\n }\n /**\n @internal\n */\n domSelection() {\n return this.root.getSelection();\n }\n}\nfunction computeDocDeco(view) {\n let attrs = Object.create(null);\n attrs.class = \"ProseMirror\";\n attrs.contenteditable = String(view.editable);\n view.someProp(\"attributes\", value => {\n if (typeof value == \"function\")\n value = value(view.state);\n if (value)\n for (let attr in value) {\n if (attr == \"class\")\n attrs.class += \" \" + value[attr];\n else if (attr == \"style\")\n attrs.style = (attrs.style ? attrs.style + \";\" : \"\") + value[attr];\n else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n attrs[attr] = String(value[attr]);\n }\n });\n if (!attrs.translate)\n attrs.translate = \"no\";\n return [Decoration.node(0, view.state.doc.content.size, attrs)];\n}\nfunction updateCursorWrapper(view) {\n if (view.markCursor) {\n let dom = document.createElement(\"img\");\n dom.className = \"ProseMirror-separator\";\n dom.setAttribute(\"mark-placeholder\", \"true\");\n dom.setAttribute(\"alt\", \"\");\n view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };\n }\n else {\n view.cursorWrapper = null;\n }\n}\nfunction getEditable(view) {\n return !view.someProp(\"editable\", value => value(view.state) === false);\n}\nfunction selectionContextChanged(sel1, sel2) {\n let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);\n}\nfunction buildNodeViews(view) {\n let result = Object.create(null);\n function add(obj) {\n for (let prop in obj)\n if (!Object.prototype.hasOwnProperty.call(result, prop))\n result[prop] = obj[prop];\n }\n view.someProp(\"nodeViews\", add);\n view.someProp(\"markViews\", add);\n return result;\n}\nfunction changedNodeViews(a, b) {\n let nA = 0, nB = 0;\n for (let prop in a) {\n if (a[prop] != b[prop])\n return true;\n nA++;\n }\n for (let _ in b)\n nB++;\n return nA != nB;\n}\nfunction checkStateComponent(plugin) {\n if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)\n throw new RangeError(\"Plugins passed directly to the view must not have a state component\");\n}\n\nexport { Decoration, DecorationSet, EditorView, __endComposition, __parseFromClipboard, __serializeForClipboard };\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) : false;\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.shiftKey || event.altKey || event.metaKey || name.charCodeAt(0) > 127) &&\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\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","import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection, SelectionRange } from 'prosemirror-state';\n\n/**\nDelete the selection, if there is one.\n*/\nconst deleteSelection = (state, dispatch) => {\n if (state.selection.empty)\n return false;\n if (dispatch)\n dispatch(state.tr.deleteSelection().scrollIntoView());\n return true;\n};\nfunction atBlockStart(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state)\n : $cursor.parentOffset > 0))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and at the start of a textblock, try to\nreduce the distance between that block and the one before it—if\nthere's a block directly before it that can be joined, join them.\nIf not, try to move the selected block closer to the next one in\nthe document structure by lifting it out of its parent or moving it\ninto a parent of the previous block. Will use the view for accurate\n(bidi-aware) start-of-textblock detection if given.\n*/\nconst joinBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n // If there is no node before this, try to lift\n if (!$cut) {\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n let before = $cut.nodeBefore;\n // Apply the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, -1))\n return true;\n // If the node below has no content and the node above is\n // selectable, delete the node below and select the one above.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n for (let depth = $cursor.depth;; depth--) {\n let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(before, \"end\")\n ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)\n : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n if (depth == 1 || $cursor.node(depth - 1).childCount > 1)\n break;\n }\n }\n // If the node before is an atom, delete it\n if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nA more limited form of [`joinBackward`]($commands.joinBackward)\nthat only tries to join the current textblock to the one before\nit, if the cursor is at the start of a textblock.\n*/\nconst joinTextblockBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\n/**\nA more limited form of [`joinForward`]($commands.joinForward)\nthat only tries to join the current textblock to the one after\nit, if the cursor is at the end of a textblock.\n*/\nconst joinTextblockForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\nfunction joinTextblocksAround(state, $cut, dispatch) {\n let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;\n for (; !beforeText.isTextblock; beforePos--) {\n if (beforeText.type.spec.isolating)\n return false;\n let child = beforeText.lastChild;\n if (!child)\n return false;\n beforeText = child;\n }\n let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;\n for (; !afterText.isTextblock; afterPos++) {\n if (afterText.type.spec.isolating)\n return false;\n let child = afterText.firstChild;\n if (!child)\n return false;\n afterText = child;\n }\n let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);\n if (!step || step.from != beforePos ||\n step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)\n return false;\n if (dispatch) {\n let tr = state.tr.step(step);\n tr.setSelection(TextSelection.create(tr.doc, beforePos));\n dispatch(tr.scrollIntoView());\n }\n return true;\n}\nfunction textblockAt(node, side, only = false) {\n for (let scan = node; scan; scan = (side == \"start\" ? scan.firstChild : scan.lastChild)) {\n if (scan.isTextblock)\n return true;\n if (only && scan.childCount != 1)\n return false;\n }\n return false;\n}\n/**\nWhen the selection is empty and at the start of a textblock, select\nthe node before that textblock, if possible. This is intended to be\nbound to keys like backspace, after\n[`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting\ncommands, as a fall-back behavior when the schema doesn't allow\ndeletion at the selected point.\n*/\nconst selectNodeBackward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0)\n return false;\n $cut = findCutBefore($head);\n }\n let node = $cut && $cut.nodeBefore;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());\n return true;\n};\nfunction findCutBefore($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n if ($pos.index(i) > 0)\n return $pos.doc.resolve($pos.before(i + 1));\n if ($pos.node(i).type.spec.isolating)\n break;\n }\n return null;\n}\nfunction atBlockEnd(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state)\n : $cursor.parentOffset < $cursor.parent.content.size))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and the cursor is at the end of a\ntextblock, try to reduce or remove the boundary between that block\nand the one after it, either by joining them or by moving the other\nblock closer to this one in the tree structure. Will use the view\nfor accurate start-of-textblock detection if given.\n*/\nconst joinForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n // If there is no node after this, there's nothing to do\n if (!$cut)\n return false;\n let after = $cut.nodeAfter;\n // Try the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, 1))\n return true;\n // If the node above has no content and the node below is\n // selectable, delete the node above and select the one below.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)\n : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n // If the next node is an atom, delete it\n if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nWhen the selection is empty and at the end of a textblock, select\nthe node coming after that textblock, if possible. This is intended\nto be bound to keys like delete, after\n[`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting\ncommands, to provide a fall-back behavior when the schema doesn't\nallow deletion at the selected point.\n*/\nconst selectNodeForward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size)\n return false;\n $cut = findCutAfter($head);\n }\n let node = $cut && $cut.nodeAfter;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());\n return true;\n};\nfunction findCutAfter($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n let parent = $pos.node(i);\n if ($pos.index(i) + 1 < parent.childCount)\n return $pos.doc.resolve($pos.after(i + 1));\n if (parent.type.spec.isolating)\n break;\n }\n return null;\n}\n/**\nJoin the selected block or, if there is a text selection, the\nclosest ancestor block of the selection that can be joined, with\nthe sibling above it.\n*/\nconst joinUp = (state, dispatch) => {\n let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;\n if (nodeSel) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.from))\n return false;\n point = sel.from;\n }\n else {\n point = joinPoint(state.doc, sel.from, -1);\n if (point == null)\n return false;\n }\n if (dispatch) {\n let tr = state.tr.join(point);\n if (nodeSel)\n tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nJoin the selected block, or the closest ancestor of the selection\nthat can be joined, with the sibling after it.\n*/\nconst joinDown = (state, dispatch) => {\n let sel = state.selection, point;\n if (sel instanceof NodeSelection) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.to))\n return false;\n point = sel.to;\n }\n else {\n point = joinPoint(state.doc, sel.to, 1);\n if (point == null)\n return false;\n }\n if (dispatch)\n dispatch(state.tr.join(point).scrollIntoView());\n return true;\n};\n/**\nLift the selected block, or the closest ancestor block of the\nselection that can be lifted, out of its parent node.\n*/\nconst lift = (state, dispatch) => {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nIf the selection is in a node whose type has a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the\nselection with a newline character.\n*/\nconst newlineInCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n if (dispatch)\n dispatch(state.tr.insertText(\"\\n\").scrollIntoView());\n return true;\n};\nfunction defaultBlockAt(match) {\n for (let i = 0; i < match.edgeCount; i++) {\n let { type } = match.edge(i);\n if (type.isTextblock && !type.hasRequiredAttrs())\n return type;\n }\n return null;\n}\n/**\nWhen the selection is in a node with a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a\ndefault block after the code block, and move the cursor there.\n*/\nconst exitCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));\n if (!type || !above.canReplaceWith(after, after, type))\n return false;\n if (dispatch) {\n let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf a block node is selected, create an empty paragraph before (if\nit is its parent's first child) or after it.\n*/\nconst createParagraphNear = (state, dispatch) => {\n let sel = state.selection, { $from, $to } = sel;\n if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)\n return false;\n let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));\n if (!type || !type.isTextblock)\n return false;\n if (dispatch) {\n let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n let tr = state.tr.insert(side, type.createAndFill());\n tr.setSelection(TextSelection.create(tr.doc, side + 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf the cursor is in an empty textblock that can be lifted, lift the\nblock.\n*/\nconst liftEmptyBlock = (state, dispatch) => {\n let { $cursor } = state.selection;\n if (!$cursor || $cursor.parent.content.size)\n return false;\n if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n let before = $cursor.before();\n if (canSplit(state.doc, before)) {\n if (dispatch)\n dispatch(state.tr.split(before).scrollIntoView());\n return true;\n }\n }\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nCreate a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses\na custom function to determine the type of the newly split off block.\n*/\nfunction splitBlockAs(splitNode) {\n return (state, dispatch) => {\n let { $from, $to } = state.selection;\n if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(state.doc, $from.pos))\n return false;\n if (dispatch)\n dispatch(state.tr.split($from.pos).scrollIntoView());\n return true;\n }\n if (!$from.depth)\n return false;\n let types = [];\n let splitDepth, deflt, atEnd = false, atStart = false;\n for (let d = $from.depth;; d--) {\n let node = $from.node(d);\n if (node.isBlock) {\n atEnd = $from.end(d) == $from.pos + ($from.depth - d);\n atStart = $from.start(d) == $from.pos - ($from.depth - d);\n deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));\n let splitType = splitNode && splitNode($to.parent, atEnd, $from);\n types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));\n splitDepth = d;\n break;\n }\n else {\n if (d == 1)\n return false;\n types.unshift(null);\n }\n }\n let tr = state.tr;\n if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)\n tr.deleteSelection();\n let splitPos = tr.mapping.map($from.pos);\n let can = canSplit(tr.doc, splitPos, types.length, types);\n if (!can) {\n types[0] = deflt ? { type: deflt } : null;\n can = canSplit(tr.doc, splitPos, types.length, types);\n }\n tr.split(splitPos, types.length, types);\n if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {\n let first = tr.mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);\n if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))\n tr.setNodeMarkup(tr.mapping.map($from.before(splitDepth)), deflt);\n }\n if (dispatch)\n dispatch(tr.scrollIntoView());\n return true;\n };\n}\n/**\nSplit the parent block of the selection. If the selection is a text\nselection, also delete its content.\n*/\nconst splitBlock = splitBlockAs();\n/**\nActs like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without\nresetting the set of active marks at the cursor.\n*/\nconst splitBlockKeepMarks = (state, dispatch) => {\n return splitBlock(state, dispatch && (tr => {\n let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks)\n tr.ensureMarks(marks);\n dispatch(tr);\n }));\n};\n/**\nMove the selection to the node wrapping the current selection, if\nany. (Will not select the document node.)\n*/\nconst selectParentNode = (state, dispatch) => {\n let { $from, to } = state.selection, pos;\n let same = $from.sharedDepth(to);\n if (same == 0)\n return false;\n pos = $from.before(same);\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));\n return true;\n};\n/**\nSelect the whole document.\n*/\nconst selectAll = (state, dispatch) => {\n if (dispatch)\n dispatch(state.tr.setSelection(new AllSelection(state.doc)));\n return true;\n};\nfunction joinMaybeClear(state, $pos, dispatch) {\n let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();\n if (!before || !after || !before.type.compatibleContent(after.type))\n return false;\n if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n if (dispatch)\n dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());\n return true;\n }\n if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))\n return false;\n if (dispatch)\n dispatch(state.tr.join($pos.pos).scrollIntoView());\n return true;\n}\nfunction deleteBarrier(state, $cut, dispatch, dir) {\n let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;\n let isolated = before.type.spec.isolating || after.type.spec.isolating;\n if (!isolated && joinMaybeClear(state, $cut, dispatch))\n return true;\n let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);\n if (canDelAfter &&\n (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&\n match.matchType(conn[0] || after.type).validEnd) {\n if (dispatch) {\n let end = $cut.pos + after.nodeSize, wrap = Fragment.empty;\n for (let i = conn.length - 1; i >= 0; i--)\n wrap = Fragment.from(conn[i].create(null, wrap));\n wrap = Fragment.from(before.copy(wrap));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n let $joinAt = tr.doc.resolve(end + 2 * conn.length);\n if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type &&\n canJoin(tr.doc, $joinAt.pos))\n tr.join($joinAt.pos);\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let selAfter = after.type.spec.isolating || (dir > 0 && isolated) ? null : Selection.findFrom($cut, 1);\n let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);\n if (target != null && target >= $cut.depth) {\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n if (canDelAfter && textblockAt(after, \"start\", true) && textblockAt(before, \"end\")) {\n let at = before, wrap = [];\n for (;;) {\n wrap.push(at);\n if (at.isTextblock)\n break;\n at = at.lastChild;\n }\n let afterText = after, afterDepth = 1;\n for (; !afterText.isTextblock; afterText = afterText.firstChild)\n afterDepth++;\n if (at.canReplace(at.childCount, at.childCount, afterText.content)) {\n if (dispatch) {\n let end = Fragment.empty;\n for (let i = wrap.length - 1; i >= 0; i--)\n end = Fragment.from(wrap[i].copy(end));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n return false;\n}\nfunction selectTextblockSide(side) {\n return function (state, dispatch) {\n let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;\n let depth = $pos.depth;\n while ($pos.node(depth).isInline) {\n if (!depth)\n return false;\n depth--;\n }\n if (!$pos.node(depth).isTextblock)\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));\n return true;\n };\n}\n/**\nMoves the cursor to the start of current text block.\n*/\nconst selectTextblockStart = selectTextblockSide(-1);\n/**\nMoves the cursor to the end of current text block.\n*/\nconst selectTextblockEnd = selectTextblockSide(1);\n// Parameterized commands\n/**\nWrap the selection in a node of the given type with the given\nattributes.\n*/\nfunction wrapIn(nodeType, attrs = null) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);\n if (!wrapping)\n return false;\n if (dispatch)\n dispatch(state.tr.wrap(range, wrapping).scrollIntoView());\n return true;\n };\n}\n/**\nReturns a command that tries to set the selected textblocks to the\ngiven node type with the given attributes.\n*/\nfunction setBlockType(nodeType, attrs = null) {\n return function (state, dispatch) {\n let applicable = false;\n for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (applicable)\n return false;\n if (!node.isTextblock || node.hasMarkup(nodeType, attrs))\n return;\n if (node.type == nodeType) {\n applicable = true;\n }\n else {\n let $pos = state.doc.resolve(pos), index = $pos.index();\n applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n }\n });\n }\n if (!applicable)\n return false;\n if (dispatch) {\n let tr = state.tr;\n for (let i = 0; i < state.selection.ranges.length; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n tr.setBlockType(from, to, nodeType, attrs);\n }\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\nfunction markApplies(doc, ranges, type, enterAtoms) {\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;\n doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)\n return false;\n can = node.inlineContent && node.type.allowsMarkType(type);\n });\n if (can)\n return true;\n }\n return false;\n}\nfunction removeInlineAtoms(ranges) {\n let result = [];\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {\n if (pos + 1 > $from.pos)\n result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));\n $from = $from.doc.resolve(pos + 1 + node.content.size);\n return false;\n }\n });\n if ($from.pos < $to.pos)\n result.push(new SelectionRange($from, $to));\n }\n return result;\n}\n/**\nCreate a command function that toggles the given mark with the\ngiven attributes. Will return `false` when the current selection\ndoesn't support that mark. This will remove the mark if any marks\nof that type exist in the selection, or add it otherwise. If the\nselection is empty, this applies to the [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the\ndocument.\n*/\nfunction toggleMark(markType, attrs = null, options) {\n let removeWhenPresent = (options && options.removeWhenPresent) !== false;\n let enterAtoms = (options && options.enterInlineAtoms) !== false;\n return function (state, dispatch) {\n let { empty, $cursor, ranges } = state.selection;\n if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType, enterAtoms))\n return false;\n if (dispatch) {\n if ($cursor) {\n if (markType.isInSet(state.storedMarks || $cursor.marks()))\n dispatch(state.tr.removeStoredMark(markType));\n else\n dispatch(state.tr.addStoredMark(markType.create(attrs)));\n }\n else {\n let add, tr = state.tr;\n if (!enterAtoms)\n ranges = removeInlineAtoms(ranges);\n if (removeWhenPresent) {\n add = !ranges.some(r => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));\n }\n else {\n add = !ranges.every(r => {\n let missing = false;\n tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {\n if (missing)\n return false;\n missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) &&\n !(node.isText && /^\\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));\n });\n return !missing;\n });\n }\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n if (!add) {\n tr.removeMark($from.pos, $to.pos, markType);\n }\n else {\n let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;\n let spaceStart = start && start.isText ? /^\\s*/.exec(start.text)[0].length : 0;\n let spaceEnd = end && end.isText ? /\\s*$/.exec(end.text)[0].length : 0;\n if (from + spaceStart < to) {\n from += spaceStart;\n to -= spaceEnd;\n }\n tr.addMark(from, to, markType.create(attrs));\n }\n }\n dispatch(tr.scrollIntoView());\n }\n }\n return true;\n };\n}\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n return (tr) => {\n if (!tr.isGeneric)\n return dispatch(tr);\n let ranges = [];\n for (let i = 0; i < tr.mapping.maps.length; i++) {\n let map = tr.mapping.maps[i];\n for (let j = 0; j < ranges.length; j++)\n ranges[j] = map.map(ranges[j]);\n map.forEach((_s, _e, from, to) => ranges.push(from, to));\n }\n // Figure out which joinable points exist inside those ranges,\n // by checking all node boundaries in their parent nodes.\n let joinable = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = ranges[i], to = ranges[i + 1];\n let $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);\n for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n let after = parent.maybeChild(index);\n if (!after)\n break;\n if (index && joinable.indexOf(pos) == -1) {\n let before = parent.child(index - 1);\n if (before.type == after.type && isJoinable(before, after))\n joinable.push(pos);\n }\n pos += after.nodeSize;\n }\n }\n // Join the joinable points\n joinable.sort((a, b) => a - b);\n for (let i = joinable.length - 1; i >= 0; i--) {\n if (canJoin(tr.doc, joinable[i]))\n tr.join(joinable[i]);\n }\n dispatch(tr);\n };\n}\n/**\nWrap a command so that, when it produces a transform that causes\ntwo joinable nodes to end up next to each other, those are joined.\nNodes are considered joinable when they are of the same type and\nwhen the `isJoinable` predicate returns true for them or, if an\narray of strings was passed, if their node type name is in that\narray.\n*/\nfunction autoJoin(command, isJoinable) {\n let canJoin = Array.isArray(isJoinable) ? (node) => isJoinable.indexOf(node.type.name) > -1\n : isJoinable;\n return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);\n}\n/**\nCombine a number of command functions into a single function (which\ncalls them one by one until one returns true).\n*/\nfunction chainCommands(...commands) {\n return function (state, dispatch, view) {\n for (let i = 0; i < commands.length; i++)\n if (commands[i](state, dispatch, view))\n return true;\n return false;\n };\n}\nlet backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nlet del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n/**\nA basic keymap containing bindings not specific to any schema.\nBinds the following keys (when multiple commands are listed, they\nare chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):\n\n* **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n* **Mod-Enter** to `exitCode`\n* **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n* **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-a** to `selectAll`\n*/\nconst pcBaseKeymap = {\n \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n \"Mod-Enter\": exitCode,\n \"Backspace\": backspace,\n \"Mod-Backspace\": backspace,\n \"Shift-Backspace\": backspace,\n \"Delete\": del,\n \"Mod-Delete\": del,\n \"Mod-a\": selectAll\n};\n/**\nA copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n**Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n**Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\nCtrl-Delete.\n*/\nconst macBaseKeymap = {\n \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"],\n \"Ctrl-a\": selectTextblockStart,\n \"Ctrl-e\": selectTextblockEnd\n};\nfor (let key in pcBaseKeymap)\n macBaseKeymap[key] = pcBaseKeymap[key];\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)\n // @ts-ignore\n : typeof os != \"undefined\" && os.platform ? os.platform() == \"darwin\" : false;\n/**\nDepending on the detected platform, this will hold\n[`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or\n[`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).\n*/\nconst baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\n\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };\n","import { findWrapping, ReplaceAroundStep, canSplit, liftTarget, canJoin } from 'prosemirror-transform';\nimport { NodeRange, Fragment, Slice } from 'prosemirror-model';\nimport { Selection } from 'prosemirror-state';\n\nconst olDOM = [\"ol\", 0], ulDOM = [\"ul\", 0], liDOM = [\"li\", 0];\n/**\nAn ordered list [node spec](https://prosemirror.net/docs/ref/#model.NodeSpec). Has a single\nattribute, `order`, which determines the number at which the list\nstarts counting, and defaults to 1. Represented as an `
    `\nelement.\n*/\nconst orderedList = {\n attrs: { order: { default: 1, validate: \"number\" } },\n parseDOM: [{ tag: \"ol\", getAttrs(dom) {\n return { order: dom.hasAttribute(\"start\") ? +dom.getAttribute(\"start\") : 1 };\n } }],\n toDOM(node) {\n return node.attrs.order == 1 ? olDOM : [\"ol\", { start: node.attrs.order }, 0];\n }\n};\n/**\nA bullet list node spec, represented in the DOM as `
      `.\n*/\nconst bulletList = {\n parseDOM: [{ tag: \"ul\" }],\n toDOM() { return ulDOM; }\n};\n/**\nA list item (`
    • `) spec.\n*/\nconst listItem = {\n parseDOM: [{ tag: \"li\" }],\n toDOM() { return liDOM; },\n defining: true\n};\nfunction add(obj, props) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n for (let prop in props)\n copy[prop] = props[prop];\n return copy;\n}\n/**\nConvenience function for adding list-related node types to a map\nspecifying the nodes for a schema. Adds\n[`orderedList`](https://prosemirror.net/docs/ref/#schema-list.orderedList) as `\"ordered_list\"`,\n[`bulletList`](https://prosemirror.net/docs/ref/#schema-list.bulletList) as `\"bullet_list\"`, and\n[`listItem`](https://prosemirror.net/docs/ref/#schema-list.listItem) as `\"list_item\"`.\n\n`itemContent` determines the content expression for the list items.\nIf you want the commands defined in this module to apply to your\nlist structure, it should have a shape like `\"paragraph block*\"` or\n`\"paragraph (ordered_list | bullet_list)*\"`. `listGroup` can be\ngiven to assign a group name to the list node types, for example\n`\"block\"`.\n*/\nfunction addListNodes(nodes, itemContent, listGroup) {\n return nodes.append({\n ordered_list: add(orderedList, { content: \"list_item+\", group: listGroup }),\n bullet_list: add(bulletList, { content: \"list_item+\", group: listGroup }),\n list_item: add(listItem, { content: itemContent })\n });\n}\n/**\nReturns a command function that wraps the selection in a list with\nthe given type an attributes. If `dispatch` is null, only return a\nvalue to indicate whether this is possible, but don't actually\nperform the change.\n*/\nfunction wrapInList(listType, attrs = null) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to);\n if (!range)\n return false;\n let tr = dispatch ? state.tr : null;\n if (!wrapRangeInList(tr, range, listType, attrs))\n return false;\n if (dispatch)\n dispatch(tr.scrollIntoView());\n return true;\n };\n}\n/**\nTry to wrap the given node range in a list of the given type.\nReturn `true` when this is possible, `false` otherwise. When `tr`\nis non-null, the wrapping is added to that transaction. When it is\n`null`, the function only queries whether the wrapping is\npossible.\n*/\nfunction wrapRangeInList(tr, range, listType, attrs = null) {\n let doJoin = false, outerRange = range, doc = range.$from.doc;\n // This is at the top of an existing list item\n if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {\n // Don't do anything if this is the top of the list\n if (range.$from.index(range.depth - 1) == 0)\n return false;\n let $insert = doc.resolve(range.start - 2);\n outerRange = new NodeRange($insert, $insert, range.depth);\n if (range.endIndex < range.parent.childCount)\n range = new NodeRange(range.$from, doc.resolve(range.$to.end(range.depth)), range.depth);\n doJoin = true;\n }\n let wrap = findWrapping(outerRange, listType, attrs, range);\n if (!wrap)\n return false;\n if (tr)\n doWrapInList(tr, range, wrap, doJoin, listType);\n return true;\n}\nfunction doWrapInList(tr, range, wrappers, joinBefore, listType) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--)\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));\n let found = 0;\n for (let i = 0; i < wrappers.length; i++)\n if (wrappers[i].type == listType)\n found = i + 1;\n let splitDepth = wrappers.length - found;\n let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent;\n for (let i = range.startIndex, e = range.endIndex, first = true; i < e; i++, first = false) {\n if (!first && canSplit(tr.doc, splitPos, splitDepth)) {\n tr.split(splitPos, splitDepth);\n splitPos += 2 * splitDepth;\n }\n splitPos += parent.child(i).nodeSize;\n }\n return tr;\n}\n/**\nBuild a command that splits a non-empty textblock at the top level\nof a list item by also splitting that list item.\n*/\nfunction splitListItem(itemType, itemAttrs) {\n return function (state, dispatch) {\n let { $from, $to, node } = state.selection;\n if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to))\n return false;\n let grandParent = $from.node(-1);\n if (grandParent.type != itemType)\n return false;\n if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {\n // In an empty block. If this is a nested list, the wrapping\n // list item should be split. Otherwise, bail out and let next\n // command handle lifting.\n if ($from.depth == 3 || $from.node(-3).type != itemType ||\n $from.index(-2) != $from.node(-2).childCount - 1)\n return false;\n if (dispatch) {\n let wrap = Fragment.empty;\n let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;\n // Build a fragment containing empty versions of the structure\n // from the outer list item to the parent node of the cursor\n for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d--)\n wrap = Fragment.from($from.node(d).copy(wrap));\n let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1\n : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;\n // Add a second list item with an empty default start node\n wrap = wrap.append(Fragment.from(itemType.createAndFill()));\n let start = $from.before($from.depth - (depthBefore - 1));\n let tr = state.tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));\n let sel = -1;\n tr.doc.nodesBetween(start, tr.doc.content.size, (node, pos) => {\n if (sel > -1)\n return false;\n if (node.isTextblock && node.content.size == 0)\n sel = pos + 1;\n });\n if (sel > -1)\n tr.setSelection(Selection.near(tr.doc.resolve(sel)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;\n let tr = state.tr.delete($from.pos, $to.pos);\n let types = nextType ? [itemAttrs ? { type: itemType, attrs: itemAttrs } : null, { type: nextType }] : undefined;\n if (!canSplit(tr.doc, $from.pos, 2, types))\n return false;\n if (dispatch)\n dispatch(tr.split($from.pos, 2, types).scrollIntoView());\n return true;\n };\n}\n/**\nActs like [`splitListItem`](https://prosemirror.net/docs/ref/#schema-list.splitListItem), but\nwithout resetting the set of active marks at the cursor.\n*/\nfunction splitListItemKeepMarks(itemType, itemAttrs) {\n let split = splitListItem(itemType, itemAttrs);\n return (state, dispatch) => {\n return split(state, dispatch && (tr => {\n let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks)\n tr.ensureMarks(marks);\n dispatch(tr);\n }));\n };\n}\n/**\nCreate a command to lift the list item around the selection up into\na wrapping list.\n*/\nfunction liftListItem(itemType) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to, node => node.childCount > 0 && node.firstChild.type == itemType);\n if (!range)\n return false;\n if (!dispatch)\n return true;\n if ($from.node(range.depth - 1).type == itemType) // Inside a parent list\n return liftToOuterList(state, dispatch, itemType, range);\n else // Outer list node\n return liftOutOfList(state, dispatch, range);\n };\n}\nfunction liftToOuterList(state, dispatch, itemType, range) {\n let tr = state.tr, end = range.end, endOfList = range.$to.end(range.depth);\n if (end < endOfList) {\n // There are siblings after the lifted items, which must become\n // children of the last item\n tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));\n range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);\n }\n const target = liftTarget(range);\n if (target == null)\n return false;\n tr.lift(range, target);\n let after = tr.mapping.map(end, -1) - 1;\n if (canJoin(tr.doc, after))\n tr.join(after);\n dispatch(tr.scrollIntoView());\n return true;\n}\nfunction liftOutOfList(state, dispatch, range) {\n let tr = state.tr, list = range.parent;\n // Merge the list items into a single big item\n for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {\n pos -= list.child(i).nodeSize;\n tr.delete(pos - 1, pos + 1);\n }\n let $start = tr.doc.resolve(range.start), item = $start.nodeAfter;\n if (tr.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize)\n return false;\n let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount;\n let parent = $start.node(-1), indexBefore = $start.index(-1);\n if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list))))\n return false;\n let start = $start.pos, end = start + item.nodeSize;\n // Strip off the surrounding list. At the sides where we're not at\n // the end of the list, the existing list is closed. At sides where\n // this is the end, it is overwritten to its end.\n tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty)))\n .append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));\n dispatch(tr.scrollIntoView());\n return true;\n}\n/**\nCreate a command to sink the list item around the selection down\ninto an inner list.\n*/\nfunction sinkListItem(itemType) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to, node => node.childCount > 0 && node.firstChild.type == itemType);\n if (!range)\n return false;\n let startIndex = range.startIndex;\n if (startIndex == 0)\n return false;\n let parent = range.parent, nodeBefore = parent.child(startIndex - 1);\n if (nodeBefore.type != itemType)\n return false;\n if (dispatch) {\n let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;\n let inner = Fragment.from(nestedBefore ? itemType.create() : null);\n let slice = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);\n let before = range.start, after = range.end;\n dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true))\n .scrollIntoView());\n }\n return true;\n };\n}\n\nexport { addListNodes, bulletList, liftListItem, listItem, orderedList, sinkListItem, splitListItem, splitListItemKeepMarks, wrapInList, wrapRangeInList };\n","import { Plugin, PluginKey, TextSelection, Selection, AllSelection, NodeSelection, EditorState } from '@tiptap/pm/state';\nimport { EditorView } from '@tiptap/pm/view';\nimport { keymap } from '@tiptap/pm/keymap';\nimport { Schema, DOMSerializer, Fragment, Node as Node$1, DOMParser, Slice } from '@tiptap/pm/model';\nimport { liftTarget, ReplaceStep, ReplaceAroundStep, joinPoint, Transform, canSplit, canJoin, findWrapping } from '@tiptap/pm/transform';\nimport { createParagraphNear as createParagraphNear$1, deleteSelection as deleteSelection$1, exitCode as exitCode$1, joinUp as joinUp$1, joinDown as joinDown$1, joinBackward as joinBackward$1, joinForward as joinForward$1, joinTextblockBackward as joinTextblockBackward$1, joinTextblockForward as joinTextblockForward$1, lift as lift$1, liftEmptyBlock as liftEmptyBlock$1, newlineInCode as newlineInCode$1, selectNodeBackward as selectNodeBackward$1, selectNodeForward as selectNodeForward$1, selectParentNode as selectParentNode$1, selectTextblockEnd as selectTextblockEnd$1, selectTextblockStart as selectTextblockStart$1, setBlockType, wrapIn as wrapIn$1 } from '@tiptap/pm/commands';\nimport { liftListItem as liftListItem$1, sinkListItem as sinkListItem$1, wrapInList as wrapInList$1 } from '@tiptap/pm/schema-list';\n\n/**\n * Takes a Transaction & Editor State and turns it into a chainable state object\n * @param config The transaction and state to create the chainable state from\n * @returns A chainable Editor state object\n */\nfunction createChainableState(config) {\n const { state, transaction } = config;\n let { selection } = transaction;\n let { doc } = transaction;\n let { storedMarks } = transaction;\n return {\n ...state,\n apply: state.apply.bind(state),\n applyTransaction: state.applyTransaction.bind(state),\n plugins: state.plugins,\n schema: state.schema,\n reconfigure: state.reconfigure.bind(state),\n toJSON: state.toJSON.bind(state),\n get storedMarks() {\n return storedMarks;\n },\n get selection() {\n return selection;\n },\n get doc() {\n return doc;\n },\n get tr() {\n selection = transaction.selection;\n doc = transaction.doc;\n storedMarks = transaction.storedMarks;\n return transaction;\n },\n };\n}\n\nclass CommandManager {\n constructor(props) {\n this.editor = props.editor;\n this.rawCommands = this.editor.extensionManager.commands;\n this.customState = props.state;\n }\n get hasCustomState() {\n return !!this.customState;\n }\n get state() {\n return this.customState || this.editor.state;\n }\n get commands() {\n const { rawCommands, editor, state } = this;\n const { view } = editor;\n const { tr } = state;\n const props = this.buildProps(tr);\n return Object.fromEntries(Object.entries(rawCommands).map(([name, command]) => {\n const method = (...args) => {\n const callback = command(...args)(props);\n if (!tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr);\n }\n return callback;\n };\n return [name, method];\n }));\n }\n get chain() {\n return () => this.createChain();\n }\n get can() {\n return () => this.createCan();\n }\n createChain(startTr, shouldDispatch = true) {\n const { rawCommands, editor, state } = this;\n const { view } = editor;\n const callbacks = [];\n const hasStartTransaction = !!startTr;\n const tr = startTr || state.tr;\n const run = () => {\n if (!hasStartTransaction\n && shouldDispatch\n && !tr.getMeta('preventDispatch')\n && !this.hasCustomState) {\n view.dispatch(tr);\n }\n return callbacks.every(callback => callback === true);\n };\n const chain = {\n ...Object.fromEntries(Object.entries(rawCommands).map(([name, command]) => {\n const chainedCommand = (...args) => {\n const props = this.buildProps(tr, shouldDispatch);\n const callback = command(...args)(props);\n callbacks.push(callback);\n return chain;\n };\n return [name, chainedCommand];\n })),\n run,\n };\n return chain;\n }\n createCan(startTr) {\n const { rawCommands, state } = this;\n const dispatch = false;\n const tr = startTr || state.tr;\n const props = this.buildProps(tr, dispatch);\n const formattedCommands = Object.fromEntries(Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args) => command(...args)({ ...props, dispatch: undefined })];\n }));\n return {\n ...formattedCommands,\n chain: () => this.createChain(tr, dispatch),\n };\n }\n buildProps(tr, shouldDispatch = true) {\n const { rawCommands, editor, state } = this;\n const { view } = editor;\n const props = {\n tr,\n editor,\n view,\n state: createChainableState({\n state,\n transaction: tr,\n }),\n dispatch: shouldDispatch ? () => undefined : undefined,\n chain: () => this.createChain(tr, shouldDispatch),\n can: () => this.createCan(tr),\n get commands() {\n return Object.fromEntries(Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args) => command(...args)(props)];\n }));\n },\n };\n return props;\n }\n}\n\nclass EventEmitter {\n constructor() {\n this.callbacks = {};\n }\n on(event, fn) {\n if (!this.callbacks[event]) {\n this.callbacks[event] = [];\n }\n this.callbacks[event].push(fn);\n return this;\n }\n emit(event, ...args) {\n const callbacks = this.callbacks[event];\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args));\n }\n return this;\n }\n off(event, fn) {\n const callbacks = this.callbacks[event];\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn);\n }\n else {\n delete this.callbacks[event];\n }\n }\n return this;\n }\n once(event, fn) {\n const onceFn = (...args) => {\n this.off(event, onceFn);\n fn.apply(this, args);\n };\n return this.on(event, onceFn);\n }\n removeAllListeners() {\n this.callbacks = {};\n }\n}\n\n/**\n * Returns a field from an extension\n * @param extension The Tiptap extension\n * @param field The field, for example `renderHTML` or `priority`\n * @param context The context object that should be passed as `this` into the function\n * @returns The field value\n */\nfunction getExtensionField(extension, field, context) {\n if (extension.config[field] === undefined && extension.parent) {\n return getExtensionField(extension.parent, field, context);\n }\n if (typeof extension.config[field] === 'function') {\n const value = extension.config[field].bind({\n ...context,\n parent: extension.parent\n ? getExtensionField(extension.parent, field, context)\n : null,\n });\n return value;\n }\n return extension.config[field];\n}\n\nfunction splitExtensions(extensions) {\n const baseExtensions = extensions.filter(extension => extension.type === 'extension');\n const nodeExtensions = extensions.filter(extension => extension.type === 'node');\n const markExtensions = extensions.filter(extension => extension.type === 'mark');\n return {\n baseExtensions,\n nodeExtensions,\n markExtensions,\n };\n}\n\n/**\n * Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.\n * @param extensions List of extensions\n */\nfunction getAttributesFromExtensions(extensions) {\n const extensionAttributes = [];\n const { nodeExtensions, markExtensions } = splitExtensions(extensions);\n const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions];\n const defaultAttribute = {\n default: null,\n rendered: true,\n renderHTML: null,\n parseHTML: null,\n keepOnSplit: true,\n isRequired: false,\n };\n extensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n extensions: nodeAndMarkExtensions,\n };\n const addGlobalAttributes = getExtensionField(extension, 'addGlobalAttributes', context);\n if (!addGlobalAttributes) {\n return;\n }\n const globalAttributes = addGlobalAttributes();\n globalAttributes.forEach(globalAttribute => {\n globalAttribute.types.forEach(type => {\n Object\n .entries(globalAttribute.attributes)\n .forEach(([name, attribute]) => {\n extensionAttributes.push({\n type,\n name,\n attribute: {\n ...defaultAttribute,\n ...attribute,\n },\n });\n });\n });\n });\n });\n nodeAndMarkExtensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n };\n const addAttributes = getExtensionField(extension, 'addAttributes', context);\n if (!addAttributes) {\n return;\n }\n // TODO: remove `as Attributes`\n const attributes = addAttributes();\n Object\n .entries(attributes)\n .forEach(([name, attribute]) => {\n const mergedAttr = {\n ...defaultAttribute,\n ...attribute,\n };\n if (typeof (mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.default) === 'function') {\n mergedAttr.default = mergedAttr.default();\n }\n if ((mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.isRequired) && (mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.default) === undefined) {\n delete mergedAttr.default;\n }\n extensionAttributes.push({\n type: extension.name,\n name,\n attribute: mergedAttr,\n });\n });\n });\n return extensionAttributes;\n}\n\nfunction getNodeType(nameOrType, schema) {\n if (typeof nameOrType === 'string') {\n if (!schema.nodes[nameOrType]) {\n throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`);\n }\n return schema.nodes[nameOrType];\n }\n return nameOrType;\n}\n\nfunction mergeAttributes(...objects) {\n return objects\n .filter(item => !!item)\n .reduce((items, item) => {\n const mergedAttributes = { ...items };\n Object.entries(item).forEach(([key, value]) => {\n const exists = mergedAttributes[key];\n if (!exists) {\n mergedAttributes[key] = value;\n return;\n }\n if (key === 'class') {\n const valueClasses = value ? String(value).split(' ') : [];\n const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(' ') : [];\n const insertClasses = valueClasses.filter(valueClass => !existingClasses.includes(valueClass));\n mergedAttributes[key] = [...existingClasses, ...insertClasses].join(' ');\n }\n else if (key === 'style') {\n const newStyles = value ? value.split(';').map((style) => style.trim()).filter(Boolean) : [];\n const existingStyles = mergedAttributes[key] ? mergedAttributes[key].split(';').map((style) => style.trim()).filter(Boolean) : [];\n const styleMap = new Map();\n existingStyles.forEach(style => {\n const [property, val] = style.split(':').map(part => part.trim());\n styleMap.set(property, val);\n });\n newStyles.forEach(style => {\n const [property, val] = style.split(':').map(part => part.trim());\n styleMap.set(property, val);\n });\n mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join('; ');\n }\n else {\n mergedAttributes[key] = value;\n }\n });\n return mergedAttributes;\n }, {});\n}\n\nfunction getRenderedAttributes(nodeOrMark, extensionAttributes) {\n return extensionAttributes\n .filter(attribute => attribute.type === nodeOrMark.type.name)\n .filter(item => item.attribute.rendered)\n .map(item => {\n if (!item.attribute.renderHTML) {\n return {\n [item.name]: nodeOrMark.attrs[item.name],\n };\n }\n return item.attribute.renderHTML(nodeOrMark.attrs) || {};\n })\n .reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {});\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction isFunction(value) {\n return typeof value === 'function';\n}\n\n/**\n * Optionally calls `value` as a function.\n * Otherwise it is returned directly.\n * @param value Function or any value.\n * @param context Optional context to bind to function.\n * @param props Optional props to pass to function.\n */\nfunction callOrReturn(value, context = undefined, ...props) {\n if (isFunction(value)) {\n if (context) {\n return value.bind(context)(...props);\n }\n return value(...props);\n }\n return value;\n}\n\nfunction isEmptyObject(value = {}) {\n return Object.keys(value).length === 0 && value.constructor === Object;\n}\n\nfunction fromString(value) {\n if (typeof value !== 'string') {\n return value;\n }\n if (value.match(/^[+-]?(?:\\d*\\.)?\\d+$/)) {\n return Number(value);\n }\n if (value === 'true') {\n return true;\n }\n if (value === 'false') {\n return false;\n }\n return value;\n}\n\n/**\n * This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).\n * Cancels when `getAttrs` returned `false`.\n * @param parseRule ProseMirror ParseRule\n * @param extensionAttributes List of attributes to inject\n */\nfunction injectExtensionAttributesToParseRule(parseRule, extensionAttributes) {\n if ('style' in parseRule) {\n return parseRule;\n }\n return {\n ...parseRule,\n getAttrs: (node) => {\n const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs;\n if (oldAttributes === false) {\n return false;\n }\n const newAttributes = extensionAttributes.reduce((items, item) => {\n const value = item.attribute.parseHTML\n ? item.attribute.parseHTML(node)\n : fromString((node).getAttribute(item.name));\n if (value === null || value === undefined) {\n return items;\n }\n return {\n ...items,\n [item.name]: value,\n };\n }, {});\n return { ...oldAttributes, ...newAttributes };\n },\n };\n}\n\nfunction cleanUpSchemaItem(data) {\n return Object.fromEntries(\n // @ts-ignore\n Object.entries(data).filter(([key, value]) => {\n if (key === 'attrs' && isEmptyObject(value)) {\n return false;\n }\n return value !== null && value !== undefined;\n }));\n}\n/**\n * Creates a new Prosemirror schema based on the given extensions.\n * @param extensions An array of Tiptap extensions\n * @param editor The editor instance\n * @returns A Prosemirror schema\n */\nfunction getSchemaByResolvedExtensions(extensions, editor) {\n var _a;\n const allAttributes = getAttributesFromExtensions(extensions);\n const { nodeExtensions, markExtensions } = splitExtensions(extensions);\n const topNode = (_a = nodeExtensions.find(extension => getExtensionField(extension, 'topNode'))) === null || _a === void 0 ? void 0 : _a.name;\n const nodes = Object.fromEntries(nodeExtensions.map(extension => {\n const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name);\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n };\n const extraNodeFields = extensions.reduce((fields, e) => {\n const extendNodeSchema = getExtensionField(e, 'extendNodeSchema', context);\n return {\n ...fields,\n ...(extendNodeSchema ? extendNodeSchema(extension) : {}),\n };\n }, {});\n const schema = cleanUpSchemaItem({\n ...extraNodeFields,\n content: callOrReturn(getExtensionField(extension, 'content', context)),\n marks: callOrReturn(getExtensionField(extension, 'marks', context)),\n group: callOrReturn(getExtensionField(extension, 'group', context)),\n inline: callOrReturn(getExtensionField(extension, 'inline', context)),\n atom: callOrReturn(getExtensionField(extension, 'atom', context)),\n selectable: callOrReturn(getExtensionField(extension, 'selectable', context)),\n draggable: callOrReturn(getExtensionField(extension, 'draggable', context)),\n code: callOrReturn(getExtensionField(extension, 'code', context)),\n whitespace: callOrReturn(getExtensionField(extension, 'whitespace', context)),\n linebreakReplacement: callOrReturn(getExtensionField(extension, 'linebreakReplacement', context)),\n defining: callOrReturn(getExtensionField(extension, 'defining', context)),\n isolating: callOrReturn(getExtensionField(extension, 'isolating', context)),\n attrs: Object.fromEntries(extensionAttributes.map(extensionAttribute => {\n var _a;\n return [extensionAttribute.name, { default: (_a = extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) === null || _a === void 0 ? void 0 : _a.default }];\n })),\n });\n const parseHTML = callOrReturn(getExtensionField(extension, 'parseHTML', context));\n if (parseHTML) {\n schema.parseDOM = parseHTML.map(parseRule => injectExtensionAttributesToParseRule(parseRule, extensionAttributes));\n }\n const renderHTML = getExtensionField(extension, 'renderHTML', context);\n if (renderHTML) {\n schema.toDOM = node => renderHTML({\n node,\n HTMLAttributes: getRenderedAttributes(node, extensionAttributes),\n });\n }\n const renderText = getExtensionField(extension, 'renderText', context);\n if (renderText) {\n schema.toText = renderText;\n }\n return [extension.name, schema];\n }));\n const marks = Object.fromEntries(markExtensions.map(extension => {\n const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name);\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n };\n const extraMarkFields = extensions.reduce((fields, e) => {\n const extendMarkSchema = getExtensionField(e, 'extendMarkSchema', context);\n return {\n ...fields,\n ...(extendMarkSchema ? extendMarkSchema(extension) : {}),\n };\n }, {});\n const schema = cleanUpSchemaItem({\n ...extraMarkFields,\n inclusive: callOrReturn(getExtensionField(extension, 'inclusive', context)),\n excludes: callOrReturn(getExtensionField(extension, 'excludes', context)),\n group: callOrReturn(getExtensionField(extension, 'group', context)),\n spanning: callOrReturn(getExtensionField(extension, 'spanning', context)),\n code: callOrReturn(getExtensionField(extension, 'code', context)),\n attrs: Object.fromEntries(extensionAttributes.map(extensionAttribute => {\n var _a;\n return [extensionAttribute.name, { default: (_a = extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) === null || _a === void 0 ? void 0 : _a.default }];\n })),\n });\n const parseHTML = callOrReturn(getExtensionField(extension, 'parseHTML', context));\n if (parseHTML) {\n schema.parseDOM = parseHTML.map(parseRule => injectExtensionAttributesToParseRule(parseRule, extensionAttributes));\n }\n const renderHTML = getExtensionField(extension, 'renderHTML', context);\n if (renderHTML) {\n schema.toDOM = mark => renderHTML({\n mark,\n HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),\n });\n }\n return [extension.name, schema];\n }));\n return new Schema({\n topNode,\n nodes,\n marks,\n });\n}\n\n/**\n * Tries to get a node or mark type by its name.\n * @param name The name of the node or mark type\n * @param schema The Prosemiror schema to search in\n * @returns The node or mark type, or null if it doesn't exist\n */\nfunction getSchemaTypeByName(name, schema) {\n return schema.nodes[name] || schema.marks[name] || null;\n}\n\nfunction isExtensionRulesEnabled(extension, enabled) {\n if (Array.isArray(enabled)) {\n return enabled.some(enabledExtension => {\n const name = typeof enabledExtension === 'string'\n ? enabledExtension\n : enabledExtension.name;\n return name === extension.name;\n });\n }\n return enabled;\n}\n\nfunction getHTMLFromFragment(fragment, schema) {\n const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment);\n const temporaryDocument = document.implementation.createHTMLDocument();\n const container = temporaryDocument.createElement('div');\n container.appendChild(documentFragment);\n return container.innerHTML;\n}\n\n/**\n * Returns the text content of a resolved prosemirror position\n * @param $from The resolved position to get the text content from\n * @param maxMatch The maximum number of characters to match\n * @returns The text content\n */\nconst getTextContentFromNodes = ($from, maxMatch = 500) => {\n let textBefore = '';\n const sliceEndPos = $from.parentOffset;\n $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => {\n var _a, _b;\n const chunk = ((_b = (_a = node.type.spec).toText) === null || _b === void 0 ? void 0 : _b.call(_a, {\n node,\n pos,\n parent,\n index,\n }))\n || node.textContent\n || '%leaf%';\n textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos));\n });\n return textBefore;\n};\n\nfunction isRegExp(value) {\n return Object.prototype.toString.call(value) === '[object RegExp]';\n}\n\nclass InputRule {\n constructor(config) {\n this.find = config.find;\n this.handler = config.handler;\n }\n}\nconst inputRuleMatcherHandler = (text, find) => {\n if (isRegExp(find)) {\n return find.exec(text);\n }\n const inputRuleMatch = find(text);\n if (!inputRuleMatch) {\n return null;\n }\n const result = [inputRuleMatch.text];\n result.index = inputRuleMatch.index;\n result.input = text;\n result.data = inputRuleMatch.data;\n if (inputRuleMatch.replaceWith) {\n if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {\n console.warn('[tiptap warn]: \"inputRuleMatch.replaceWith\" must be part of \"inputRuleMatch.text\".');\n }\n result.push(inputRuleMatch.replaceWith);\n }\n return result;\n};\nfunction run$1(config) {\n var _a;\n const { editor, from, to, text, rules, plugin, } = config;\n const { view } = editor;\n if (view.composing) {\n return false;\n }\n const $from = view.state.doc.resolve(from);\n if (\n // check for code node\n $from.parent.type.spec.code\n // check for code mark\n || !!((_a = ($from.nodeBefore || $from.nodeAfter)) === null || _a === void 0 ? void 0 : _a.marks.find(mark => mark.type.spec.code))) {\n return false;\n }\n let matched = false;\n const textBefore = getTextContentFromNodes($from) + text;\n rules.forEach(rule => {\n if (matched) {\n return;\n }\n const match = inputRuleMatcherHandler(textBefore, rule.find);\n if (!match) {\n return;\n }\n const tr = view.state.tr;\n const state = createChainableState({\n state: view.state,\n transaction: tr,\n });\n const range = {\n from: from - (match[0].length - text.length),\n to,\n };\n const { commands, chain, can } = new CommandManager({\n editor,\n state,\n });\n const handler = rule.handler({\n state,\n range,\n match,\n commands,\n chain,\n can,\n });\n // stop if there are no changes\n if (handler === null || !tr.steps.length) {\n return;\n }\n // store transform as meta data\n // so we can undo input rules within the `undoInputRules` command\n tr.setMeta(plugin, {\n transform: tr,\n from,\n to,\n text,\n });\n view.dispatch(tr);\n matched = true;\n });\n return matched;\n}\n/**\n * Create an input rules plugin. When enabled, it will cause text\n * input that matches any of the given rules to trigger the rule’s\n * action.\n */\nfunction inputRulesPlugin(props) {\n const { editor, rules } = props;\n const plugin = new Plugin({\n state: {\n init() {\n return null;\n },\n apply(tr, prev, state) {\n const stored = tr.getMeta(plugin);\n if (stored) {\n return stored;\n }\n // if InputRule is triggered by insertContent()\n const simulatedInputMeta = tr.getMeta('applyInputRules');\n const isSimulatedInput = !!simulatedInputMeta;\n if (isSimulatedInput) {\n setTimeout(() => {\n let { text } = simulatedInputMeta;\n if (typeof text === 'string') {\n text = text;\n }\n else {\n text = getHTMLFromFragment(Fragment.from(text), state.schema);\n }\n const { from } = simulatedInputMeta;\n const to = from + text.length;\n run$1({\n editor,\n from,\n to,\n text,\n rules,\n plugin,\n });\n });\n }\n return tr.selectionSet || tr.docChanged ? null : prev;\n },\n },\n props: {\n handleTextInput(view, from, to, text) {\n return run$1({\n editor,\n from,\n to,\n text,\n rules,\n plugin,\n });\n },\n handleDOMEvents: {\n compositionend: view => {\n setTimeout(() => {\n const { $cursor } = view.state.selection;\n if ($cursor) {\n run$1({\n editor,\n from: $cursor.pos,\n to: $cursor.pos,\n text: '',\n rules,\n plugin,\n });\n }\n });\n return false;\n },\n },\n // add support for input rules to trigger on enter\n // this is useful for example for code blocks\n handleKeyDown(view, event) {\n if (event.key !== 'Enter') {\n return false;\n }\n const { $cursor } = view.state.selection;\n if ($cursor) {\n return run$1({\n editor,\n from: $cursor.pos,\n to: $cursor.pos,\n text: '\\n',\n rules,\n plugin,\n });\n }\n return false;\n },\n },\n // @ts-ignore\n isInputRules: true,\n });\n return plugin;\n}\n\n// see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts\nfunction getType(value) {\n return Object.prototype.toString.call(value).slice(8, -1);\n}\nfunction isPlainObject(value) {\n if (getType(value) !== 'Object') {\n return false;\n }\n return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;\n}\n\nfunction mergeDeep(target, source) {\n const output = { ...target };\n if (isPlainObject(target) && isPlainObject(source)) {\n Object.keys(source).forEach(key => {\n if (isPlainObject(source[key]) && isPlainObject(target[key])) {\n output[key] = mergeDeep(target[key], source[key]);\n }\n else {\n output[key] = source[key];\n }\n });\n }\n return output;\n}\n\n/**\n * The Mark class is used to create custom mark extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nclass Mark {\n constructor(config = {}) {\n this.type = 'mark';\n this.name = 'mark';\n this.parent = null;\n this.child = null;\n this.config = {\n name: this.name,\n defaultOptions: {},\n };\n this.config = {\n ...this.config,\n ...config,\n };\n this.name = this.config.name;\n if (config.defaultOptions && Object.keys(config.defaultOptions).length > 0) {\n console.warn(`[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${this.name}\".`);\n }\n // TODO: remove `addOptions` fallback\n this.options = this.config.defaultOptions;\n if (this.config.addOptions) {\n this.options = callOrReturn(getExtensionField(this, 'addOptions', {\n name: this.name,\n }));\n }\n this.storage = callOrReturn(getExtensionField(this, 'addStorage', {\n name: this.name,\n options: this.options,\n })) || {};\n }\n static create(config = {}) {\n return new Mark(config);\n }\n configure(options = {}) {\n // return a new instance so we can use the same extension\n // with different calls of `configure`\n const extension = this.extend({\n ...this.config,\n addOptions: () => {\n return mergeDeep(this.options, options);\n },\n });\n // Always preserve the current name\n extension.name = this.name;\n // Set the parent to be our parent\n extension.parent = this.parent;\n return extension;\n }\n extend(extendedConfig = {}) {\n const extension = new Mark(extendedConfig);\n extension.parent = this;\n this.child = extension;\n extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name;\n if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {\n console.warn(`[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${extension.name}\".`);\n }\n extension.options = callOrReturn(getExtensionField(extension, 'addOptions', {\n name: extension.name,\n }));\n extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {\n name: extension.name,\n options: extension.options,\n }));\n return extension;\n }\n static handleExit({ editor, mark }) {\n const { tr } = editor.state;\n const currentPos = editor.state.selection.$from;\n const isAtEnd = currentPos.pos === currentPos.end();\n if (isAtEnd) {\n const currentMarks = currentPos.marks();\n const isInMark = !!currentMarks.find(m => (m === null || m === void 0 ? void 0 : m.type.name) === mark.name);\n if (!isInMark) {\n return false;\n }\n const removeMark = currentMarks.find(m => (m === null || m === void 0 ? void 0 : m.type.name) === mark.name);\n if (removeMark) {\n tr.removeStoredMark(removeMark);\n }\n tr.insertText(' ', currentPos.pos);\n editor.view.dispatch(tr);\n return true;\n }\n return false;\n }\n}\n\nfunction isNumber(value) {\n return typeof value === 'number';\n}\n\n/**\n * Paste rules are used to react to pasted content.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nclass PasteRule {\n constructor(config) {\n this.find = config.find;\n this.handler = config.handler;\n }\n}\nconst pasteRuleMatcherHandler = (text, find, event) => {\n if (isRegExp(find)) {\n return [...text.matchAll(find)];\n }\n const matches = find(text, event);\n if (!matches) {\n return [];\n }\n return matches.map(pasteRuleMatch => {\n const result = [pasteRuleMatch.text];\n result.index = pasteRuleMatch.index;\n result.input = text;\n result.data = pasteRuleMatch.data;\n if (pasteRuleMatch.replaceWith) {\n if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {\n console.warn('[tiptap warn]: \"pasteRuleMatch.replaceWith\" must be part of \"pasteRuleMatch.text\".');\n }\n result.push(pasteRuleMatch.replaceWith);\n }\n return result;\n });\n};\nfunction run(config) {\n const { editor, state, from, to, rule, pasteEvent, dropEvent, } = config;\n const { commands, chain, can } = new CommandManager({\n editor,\n state,\n });\n const handlers = [];\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isTextblock || node.type.spec.code) {\n return;\n }\n const resolvedFrom = Math.max(from, pos);\n const resolvedTo = Math.min(to, pos + node.content.size);\n const textToMatch = node.textBetween(resolvedFrom - pos, resolvedTo - pos, undefined, '\\ufffc');\n const matches = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent);\n matches.forEach(match => {\n if (match.index === undefined) {\n return;\n }\n const start = resolvedFrom + match.index + 1;\n const end = start + match[0].length;\n const range = {\n from: state.tr.mapping.map(start),\n to: state.tr.mapping.map(end),\n };\n const handler = rule.handler({\n state,\n range,\n match,\n commands,\n chain,\n can,\n pasteEvent,\n dropEvent,\n });\n handlers.push(handler);\n });\n });\n const success = handlers.every(handler => handler !== null);\n return success;\n}\n// When dragging across editors, must get another editor instance to delete selection content.\nlet tiptapDragFromOtherEditor = null;\nconst createClipboardPasteEvent = (text) => {\n var _a;\n const event = new ClipboardEvent('paste', {\n clipboardData: new DataTransfer(),\n });\n (_a = event.clipboardData) === null || _a === void 0 ? void 0 : _a.setData('text/html', text);\n return event;\n};\n/**\n * Create an paste rules plugin. When enabled, it will cause pasted\n * text that matches any of the given rules to trigger the rule’s\n * action.\n */\nfunction pasteRulesPlugin(props) {\n const { editor, rules } = props;\n let dragSourceElement = null;\n let isPastedFromProseMirror = false;\n let isDroppedFromProseMirror = false;\n let pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null;\n let dropEvent;\n try {\n dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null;\n }\n catch {\n dropEvent = null;\n }\n const processEvent = ({ state, from, to, rule, pasteEvt, }) => {\n const tr = state.tr;\n const chainableState = createChainableState({\n state,\n transaction: tr,\n });\n const handler = run({\n editor,\n state: chainableState,\n from: Math.max(from - 1, 0),\n to: to.b - 1,\n rule,\n pasteEvent: pasteEvt,\n dropEvent,\n });\n if (!handler || !tr.steps.length) {\n return;\n }\n try {\n dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null;\n }\n catch {\n dropEvent = null;\n }\n pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null;\n return tr;\n };\n const plugins = rules.map(rule => {\n return new Plugin({\n // we register a global drag handler to track the current drag source element\n view(view) {\n const handleDragstart = (event) => {\n var _a;\n dragSourceElement = ((_a = view.dom.parentElement) === null || _a === void 0 ? void 0 : _a.contains(event.target))\n ? view.dom.parentElement\n : null;\n if (dragSourceElement) {\n tiptapDragFromOtherEditor = editor;\n }\n };\n const handleDragend = () => {\n if (tiptapDragFromOtherEditor) {\n tiptapDragFromOtherEditor = null;\n }\n };\n window.addEventListener('dragstart', handleDragstart);\n window.addEventListener('dragend', handleDragend);\n return {\n destroy() {\n window.removeEventListener('dragstart', handleDragstart);\n window.removeEventListener('dragend', handleDragend);\n },\n };\n },\n props: {\n handleDOMEvents: {\n drop: (view, event) => {\n isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement;\n dropEvent = event;\n if (!isDroppedFromProseMirror) {\n const dragFromOtherEditor = tiptapDragFromOtherEditor;\n if (dragFromOtherEditor) {\n // setTimeout to avoid the wrong content after drop, timeout arg can't be empty or 0\n setTimeout(() => {\n const selection = dragFromOtherEditor.state.selection;\n if (selection) {\n dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to });\n }\n }, 10);\n }\n }\n return false;\n },\n paste: (_view, event) => {\n var _a;\n const html = (_a = event.clipboardData) === null || _a === void 0 ? void 0 : _a.getData('text/html');\n pasteEvent = event;\n isPastedFromProseMirror = !!(html === null || html === void 0 ? void 0 : html.includes('data-pm-slice'));\n return false;\n },\n },\n },\n appendTransaction: (transactions, oldState, state) => {\n const transaction = transactions[0];\n const isPaste = transaction.getMeta('uiEvent') === 'paste' && !isPastedFromProseMirror;\n const isDrop = transaction.getMeta('uiEvent') === 'drop' && !isDroppedFromProseMirror;\n // if PasteRule is triggered by insertContent()\n const simulatedPasteMeta = transaction.getMeta('applyPasteRules');\n const isSimulatedPaste = !!simulatedPasteMeta;\n if (!isPaste && !isDrop && !isSimulatedPaste) {\n return;\n }\n // Handle simulated paste\n if (isSimulatedPaste) {\n let { text } = simulatedPasteMeta;\n if (typeof text === 'string') {\n text = text;\n }\n else {\n text = getHTMLFromFragment(Fragment.from(text), state.schema);\n }\n const { from } = simulatedPasteMeta;\n const to = from + text.length;\n const pasteEvt = createClipboardPasteEvent(text);\n return processEvent({\n rule,\n state,\n from,\n to: { b: to },\n pasteEvt,\n });\n }\n // handle actual paste/drop\n const from = oldState.doc.content.findDiffStart(state.doc.content);\n const to = oldState.doc.content.findDiffEnd(state.doc.content);\n // stop if there is no changed range\n if (!isNumber(from) || !to || from === to.b) {\n return;\n }\n return processEvent({\n rule,\n state,\n from,\n to,\n pasteEvt: pasteEvent,\n });\n },\n });\n });\n return plugins;\n}\n\nfunction findDuplicates(items) {\n const filtered = items.filter((el, index) => items.indexOf(el) !== index);\n return Array.from(new Set(filtered));\n}\n\nclass ExtensionManager {\n constructor(extensions, editor) {\n this.splittableMarks = [];\n this.editor = editor;\n this.extensions = ExtensionManager.resolve(extensions);\n this.schema = getSchemaByResolvedExtensions(this.extensions, editor);\n this.setupExtensions();\n }\n /**\n * Returns a flattened and sorted extension list while\n * also checking for duplicated extensions and warns the user.\n * @param extensions An array of Tiptap extensions\n * @returns An flattened and sorted array of Tiptap extensions\n */\n static resolve(extensions) {\n const resolvedExtensions = ExtensionManager.sort(ExtensionManager.flatten(extensions));\n const duplicatedNames = findDuplicates(resolvedExtensions.map(extension => extension.name));\n if (duplicatedNames.length) {\n console.warn(`[tiptap warn]: Duplicate extension names found: [${duplicatedNames\n .map(item => `'${item}'`)\n .join(', ')}]. This can lead to issues.`);\n }\n return resolvedExtensions;\n }\n /**\n * Create a flattened array of extensions by traversing the `addExtensions` field.\n * @param extensions An array of Tiptap extensions\n * @returns A flattened array of Tiptap extensions\n */\n static flatten(extensions) {\n return (extensions\n .map(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n };\n const addExtensions = getExtensionField(extension, 'addExtensions', context);\n if (addExtensions) {\n return [extension, ...this.flatten(addExtensions())];\n }\n return extension;\n })\n // `Infinity` will break TypeScript so we set a number that is probably high enough\n .flat(10));\n }\n /**\n * Sort extensions by priority.\n * @param extensions An array of Tiptap extensions\n * @returns A sorted array of Tiptap extensions by priority\n */\n static sort(extensions) {\n const defaultPriority = 100;\n return extensions.sort((a, b) => {\n const priorityA = getExtensionField(a, 'priority') || defaultPriority;\n const priorityB = getExtensionField(b, 'priority') || defaultPriority;\n if (priorityA > priorityB) {\n return -1;\n }\n if (priorityA < priorityB) {\n return 1;\n }\n return 0;\n });\n }\n /**\n * Get all commands from the extensions.\n * @returns An object with all commands where the key is the command name and the value is the command function\n */\n get commands() {\n return this.extensions.reduce((commands, extension) => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n };\n const addCommands = getExtensionField(extension, 'addCommands', context);\n if (!addCommands) {\n return commands;\n }\n return {\n ...commands,\n ...addCommands(),\n };\n }, {});\n }\n /**\n * Get all registered Prosemirror plugins from the extensions.\n * @returns An array of Prosemirror plugins\n */\n get plugins() {\n const { editor } = this;\n // With ProseMirror, first plugins within an array are executed first.\n // In Tiptap, we provide the ability to override plugins,\n // so it feels more natural to run plugins at the end of an array first.\n // That’s why we have to reverse the `extensions` array and sort again\n // based on the `priority` option.\n const extensions = ExtensionManager.sort([...this.extensions].reverse());\n const inputRules = [];\n const pasteRules = [];\n const allPlugins = extensions\n .map(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n };\n const plugins = [];\n const addKeyboardShortcuts = getExtensionField(extension, 'addKeyboardShortcuts', context);\n let defaultBindings = {};\n // bind exit handling\n if (extension.type === 'mark' && getExtensionField(extension, 'exitable', context)) {\n defaultBindings.ArrowRight = () => Mark.handleExit({ editor, mark: extension });\n }\n if (addKeyboardShortcuts) {\n const bindings = Object.fromEntries(Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {\n return [shortcut, () => method({ editor })];\n }));\n defaultBindings = { ...defaultBindings, ...bindings };\n }\n const keyMapPlugin = keymap(defaultBindings);\n plugins.push(keyMapPlugin);\n const addInputRules = getExtensionField(extension, 'addInputRules', context);\n if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {\n inputRules.push(...addInputRules());\n }\n const addPasteRules = getExtensionField(extension, 'addPasteRules', context);\n if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {\n pasteRules.push(...addPasteRules());\n }\n const addProseMirrorPlugins = getExtensionField(extension, 'addProseMirrorPlugins', context);\n if (addProseMirrorPlugins) {\n const proseMirrorPlugins = addProseMirrorPlugins();\n plugins.push(...proseMirrorPlugins);\n }\n return plugins;\n })\n .flat();\n return [\n inputRulesPlugin({\n editor,\n rules: inputRules,\n }),\n ...pasteRulesPlugin({\n editor,\n rules: pasteRules,\n }),\n ...allPlugins,\n ];\n }\n /**\n * Get all attributes from the extensions.\n * @returns An array of attributes\n */\n get attributes() {\n return getAttributesFromExtensions(this.extensions);\n }\n /**\n * Get all node views from the extensions.\n * @returns An object with all node views where the key is the node name and the value is the node view function\n */\n get nodeViews() {\n const { editor } = this;\n const { nodeExtensions } = splitExtensions(this.extensions);\n return Object.fromEntries(nodeExtensions\n .filter(extension => !!getExtensionField(extension, 'addNodeView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name);\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n type: getNodeType(extension.name, this.schema),\n };\n const addNodeView = getExtensionField(extension, 'addNodeView', context);\n if (!addNodeView) {\n return [];\n }\n const nodeview = (node, view, getPos, decorations, innerDecorations) => {\n const HTMLAttributes = getRenderedAttributes(node, extensionAttributes);\n return addNodeView()({\n // pass-through\n node,\n view,\n getPos: getPos,\n decorations,\n innerDecorations,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n });\n };\n return [extension.name, nodeview];\n }));\n }\n /**\n * Go through all extensions, create extension storages & setup marks\n * & bind editor event listener.\n */\n setupExtensions() {\n this.extensions.forEach(extension => {\n var _a;\n // store extension storage in editor\n this.editor.extensionStorage[extension.name] = extension.storage;\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n };\n if (extension.type === 'mark') {\n const keepOnSplit = (_a = callOrReturn(getExtensionField(extension, 'keepOnSplit', context))) !== null && _a !== void 0 ? _a : true;\n if (keepOnSplit) {\n this.splittableMarks.push(extension.name);\n }\n }\n const onBeforeCreate = getExtensionField(extension, 'onBeforeCreate', context);\n const onCreate = getExtensionField(extension, 'onCreate', context);\n const onUpdate = getExtensionField(extension, 'onUpdate', context);\n const onSelectionUpdate = getExtensionField(extension, 'onSelectionUpdate', context);\n const onTransaction = getExtensionField(extension, 'onTransaction', context);\n const onFocus = getExtensionField(extension, 'onFocus', context);\n const onBlur = getExtensionField(extension, 'onBlur', context);\n const onDestroy = getExtensionField(extension, 'onDestroy', context);\n if (onBeforeCreate) {\n this.editor.on('beforeCreate', onBeforeCreate);\n }\n if (onCreate) {\n this.editor.on('create', onCreate);\n }\n if (onUpdate) {\n this.editor.on('update', onUpdate);\n }\n if (onSelectionUpdate) {\n this.editor.on('selectionUpdate', onSelectionUpdate);\n }\n if (onTransaction) {\n this.editor.on('transaction', onTransaction);\n }\n if (onFocus) {\n this.editor.on('focus', onFocus);\n }\n if (onBlur) {\n this.editor.on('blur', onBlur);\n }\n if (onDestroy) {\n this.editor.on('destroy', onDestroy);\n }\n });\n }\n}\n\n/**\n * The Extension class is the base class for all extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nclass Extension {\n constructor(config = {}) {\n this.type = 'extension';\n this.name = 'extension';\n this.parent = null;\n this.child = null;\n this.config = {\n name: this.name,\n defaultOptions: {},\n };\n this.config = {\n ...this.config,\n ...config,\n };\n this.name = this.config.name;\n if (config.defaultOptions && Object.keys(config.defaultOptions).length > 0) {\n console.warn(`[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${this.name}\".`);\n }\n // TODO: remove `addOptions` fallback\n this.options = this.config.defaultOptions;\n if (this.config.addOptions) {\n this.options = callOrReturn(getExtensionField(this, 'addOptions', {\n name: this.name,\n }));\n }\n this.storage = callOrReturn(getExtensionField(this, 'addStorage', {\n name: this.name,\n options: this.options,\n })) || {};\n }\n static create(config = {}) {\n return new Extension(config);\n }\n configure(options = {}) {\n // return a new instance so we can use the same extension\n // with different calls of `configure`\n const extension = this.extend({\n ...this.config,\n addOptions: () => {\n return mergeDeep(this.options, options);\n },\n });\n // Always preserve the current name\n extension.name = this.name;\n // Set the parent to be our parent\n extension.parent = this.parent;\n return extension;\n }\n extend(extendedConfig = {}) {\n const extension = new Extension({ ...this.config, ...extendedConfig });\n extension.parent = this;\n this.child = extension;\n extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name;\n if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {\n console.warn(`[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${extension.name}\".`);\n }\n extension.options = callOrReturn(getExtensionField(extension, 'addOptions', {\n name: extension.name,\n }));\n extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {\n name: extension.name,\n options: extension.options,\n }));\n return extension;\n }\n}\n\n/**\n * Gets the text between two positions in a Prosemirror node\n * and serializes it using the given text serializers and block separator (see getText)\n * @param startNode The Prosemirror node to start from\n * @param range The range of the text to get\n * @param options Options for the text serializer & block separator\n * @returns The text between the two positions\n */\nfunction getTextBetween(startNode, range, options) {\n const { from, to } = range;\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {};\n let text = '';\n startNode.nodesBetween(from, to, (node, pos, parent, index) => {\n var _a;\n if (node.isBlock && pos > from) {\n text += blockSeparator;\n }\n const textSerializer = textSerializers === null || textSerializers === void 0 ? void 0 : textSerializers[node.type.name];\n if (textSerializer) {\n if (parent) {\n text += textSerializer({\n node,\n pos,\n parent,\n index,\n range,\n });\n }\n // do not descend into child nodes when there exists a serializer\n return false;\n }\n if (node.isText) {\n text += (_a = node === null || node === void 0 ? void 0 : node.text) === null || _a === void 0 ? void 0 : _a.slice(Math.max(from, pos) - pos, to - pos); // eslint-disable-line\n }\n });\n return text;\n}\n\n/**\n * Find text serializers `toText` in a Prosemirror schema\n * @param schema The Prosemirror schema to search in\n * @returns A record of text serializers by node name\n */\nfunction getTextSerializersFromSchema(schema) {\n return Object.fromEntries(Object.entries(schema.nodes)\n .filter(([, node]) => node.spec.toText)\n .map(([name, node]) => [name, node.spec.toText]));\n}\n\nconst ClipboardTextSerializer = Extension.create({\n name: 'clipboardTextSerializer',\n addOptions() {\n return {\n blockSeparator: undefined,\n };\n },\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('clipboardTextSerializer'),\n props: {\n clipboardTextSerializer: () => {\n const { editor } = this;\n const { state, schema } = editor;\n const { doc, selection } = state;\n const { ranges } = selection;\n const from = Math.min(...ranges.map(range => range.$from.pos));\n const to = Math.max(...ranges.map(range => range.$to.pos));\n const textSerializers = getTextSerializersFromSchema(schema);\n const range = { from, to };\n return getTextBetween(doc, range, {\n ...(this.options.blockSeparator !== undefined\n ? { blockSeparator: this.options.blockSeparator }\n : {}),\n textSerializers,\n });\n },\n },\n }),\n ];\n },\n});\n\nconst blur = () => ({ editor, view }) => {\n requestAnimationFrame(() => {\n var _a;\n if (!editor.isDestroyed) {\n view.dom.blur();\n // Browsers should remove the caret on blur but safari does not.\n // See: https://github.com/ueberdosis/tiptap/issues/2405\n (_a = window === null || window === void 0 ? void 0 : window.getSelection()) === null || _a === void 0 ? void 0 : _a.removeAllRanges();\n }\n });\n return true;\n};\n\nconst clearContent = (emitUpdate = false) => ({ commands }) => {\n return commands.setContent('', emitUpdate);\n};\n\nconst clearNodes = () => ({ state, tr, dispatch }) => {\n const { selection } = tr;\n const { ranges } = selection;\n if (!dispatch) {\n return true;\n }\n ranges.forEach(({ $from, $to }) => {\n state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.type.isText) {\n return;\n }\n const { doc, mapping } = tr;\n const $mappedFrom = doc.resolve(mapping.map(pos));\n const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize));\n const nodeRange = $mappedFrom.blockRange($mappedTo);\n if (!nodeRange) {\n return;\n }\n const targetLiftDepth = liftTarget(nodeRange);\n if (node.type.isTextblock) {\n const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index());\n tr.setNodeMarkup(nodeRange.start, defaultType);\n }\n if (targetLiftDepth || targetLiftDepth === 0) {\n tr.lift(nodeRange, targetLiftDepth);\n }\n });\n });\n return true;\n};\n\nconst command = fn => props => {\n return fn(props);\n};\n\nconst createParagraphNear = () => ({ state, dispatch }) => {\n return createParagraphNear$1(state, dispatch);\n};\n\nconst cut = (originRange, targetPos) => ({ editor, tr }) => {\n const { state } = editor;\n const contentSlice = state.doc.slice(originRange.from, originRange.to);\n tr.deleteRange(originRange.from, originRange.to);\n const newPos = tr.mapping.map(targetPos);\n tr.insert(newPos, contentSlice.content);\n tr.setSelection(new TextSelection(tr.doc.resolve(newPos - 1)));\n return true;\n};\n\nconst deleteCurrentNode = () => ({ tr, dispatch }) => {\n const { selection } = tr;\n const currentNode = selection.$anchor.node();\n // if there is content inside the current node, break out of this command\n if (currentNode.content.size > 0) {\n return false;\n }\n const $pos = tr.selection.$anchor;\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth);\n if (node.type === currentNode.type) {\n if (dispatch) {\n const from = $pos.before(depth);\n const to = $pos.after(depth);\n tr.delete(from, to).scrollIntoView();\n }\n return true;\n }\n }\n return false;\n};\n\nconst deleteNode = typeOrName => ({ tr, state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema);\n const $pos = tr.selection.$anchor;\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth);\n if (node.type === type) {\n if (dispatch) {\n const from = $pos.before(depth);\n const to = $pos.after(depth);\n tr.delete(from, to).scrollIntoView();\n }\n return true;\n }\n }\n return false;\n};\n\nconst deleteRange = range => ({ tr, dispatch }) => {\n const { from, to } = range;\n if (dispatch) {\n tr.delete(from, to);\n }\n return true;\n};\n\nconst deleteSelection = () => ({ state, dispatch }) => {\n return deleteSelection$1(state, dispatch);\n};\n\nconst enter = () => ({ commands }) => {\n return commands.keyboardShortcut('Enter');\n};\n\nconst exitCode = () => ({ state, dispatch }) => {\n return exitCode$1(state, dispatch);\n};\n\n/**\n * Check if object1 includes object2\n * @param object1 Object\n * @param object2 Object\n */\nfunction objectIncludes(object1, object2, options = { strict: true }) {\n const keys = Object.keys(object2);\n if (!keys.length) {\n return true;\n }\n return keys.every(key => {\n if (options.strict) {\n return object2[key] === object1[key];\n }\n if (isRegExp(object2[key])) {\n return object2[key].test(object1[key]);\n }\n return object2[key] === object1[key];\n });\n}\n\nfunction findMarkInSet(marks, type, attributes = {}) {\n return marks.find(item => {\n return (item.type === type\n && objectIncludes(\n // Only check equality for the attributes that are provided\n Object.fromEntries(Object.keys(attributes).map(k => [k, item.attrs[k]])), attributes));\n });\n}\nfunction isMarkInSet(marks, type, attributes = {}) {\n return !!findMarkInSet(marks, type, attributes);\n}\n/**\n * Get the range of a mark at a resolved position.\n */\nfunction getMarkRange(\n/**\n * The position to get the mark range for.\n */\n$pos, \n/**\n * The mark type to get the range for.\n */\ntype, \n/**\n * The attributes to match against.\n * If not provided, only the first mark at the position will be matched.\n */\nattributes) {\n var _a;\n if (!$pos || !type) {\n return;\n }\n let start = $pos.parent.childAfter($pos.parentOffset);\n // If the cursor is at the start of a text node that does not have the mark, look backward\n if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n start = $pos.parent.childBefore($pos.parentOffset);\n }\n // If there is no text node with the mark even backward, return undefined\n if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n return;\n }\n // Default to only matching against the first mark's attributes\n attributes = attributes || ((_a = start.node.marks[0]) === null || _a === void 0 ? void 0 : _a.attrs);\n // We now know that the cursor is either at the start, middle or end of a text node with the specified mark\n // so we can look it up on the targeted mark\n const mark = findMarkInSet([...start.node.marks], type, attributes);\n if (!mark) {\n return;\n }\n let startIndex = start.index;\n let startPos = $pos.start() + start.offset;\n let endIndex = startIndex + 1;\n let endPos = startPos + start.node.nodeSize;\n while (startIndex > 0\n && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {\n startIndex -= 1;\n startPos -= $pos.parent.child(startIndex).nodeSize;\n }\n while (endIndex < $pos.parent.childCount\n && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {\n endPos += $pos.parent.child(endIndex).nodeSize;\n endIndex += 1;\n }\n return {\n from: startPos,\n to: endPos,\n };\n}\n\nfunction getMarkType(nameOrType, schema) {\n if (typeof nameOrType === 'string') {\n if (!schema.marks[nameOrType]) {\n throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`);\n }\n return schema.marks[nameOrType];\n }\n return nameOrType;\n}\n\nconst extendMarkRange = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {\n const type = getMarkType(typeOrName, state.schema);\n const { doc, selection } = tr;\n const { $from, from, to } = selection;\n if (dispatch) {\n const range = getMarkRange($from, type, attributes);\n if (range && range.from <= from && range.to >= to) {\n const newSelection = TextSelection.create(doc, range.from, range.to);\n tr.setSelection(newSelection);\n }\n }\n return true;\n};\n\nconst first = commands => props => {\n const items = typeof commands === 'function'\n ? commands(props)\n : commands;\n for (let i = 0; i < items.length; i += 1) {\n if (items[i](props)) {\n return true;\n }\n }\n return false;\n};\n\nfunction isTextSelection(value) {\n return value instanceof TextSelection;\n}\n\nfunction minMax(value = 0, min = 0, max = 0) {\n return Math.min(Math.max(value, min), max);\n}\n\nfunction resolveFocusPosition(doc, position = null) {\n if (!position) {\n return null;\n }\n const selectionAtStart = Selection.atStart(doc);\n const selectionAtEnd = Selection.atEnd(doc);\n if (position === 'start' || position === true) {\n return selectionAtStart;\n }\n if (position === 'end') {\n return selectionAtEnd;\n }\n const minPos = selectionAtStart.from;\n const maxPos = selectionAtEnd.to;\n if (position === 'all') {\n return TextSelection.create(doc, minMax(0, minPos, maxPos), minMax(doc.content.size, minPos, maxPos));\n }\n return TextSelection.create(doc, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos));\n}\n\nfunction isAndroid() {\n return navigator.platform === 'Android' || /android/i.test(navigator.userAgent);\n}\n\nfunction isiOS() {\n return [\n 'iPad Simulator',\n 'iPhone Simulator',\n 'iPod Simulator',\n 'iPad',\n 'iPhone',\n 'iPod',\n ].includes(navigator.platform)\n // iPad on iOS 13 detection\n || (navigator.userAgent.includes('Mac') && 'ontouchend' in document);\n}\n\nconst focus = (position = null, options = {}) => ({ editor, view, tr, dispatch, }) => {\n options = {\n scrollIntoView: true,\n ...options,\n };\n const delayedFocus = () => {\n // focus within `requestAnimationFrame` breaks focus on iOS and Android\n // so we have to call this\n if (isiOS() || isAndroid()) {\n view.dom.focus();\n }\n // For React we have to focus asynchronously. Otherwise wild things happen.\n // see: https://github.com/ueberdosis/tiptap/issues/1520\n requestAnimationFrame(() => {\n if (!editor.isDestroyed) {\n view.focus();\n if (options === null || options === void 0 ? void 0 : options.scrollIntoView) {\n editor.commands.scrollIntoView();\n }\n }\n });\n };\n if ((view.hasFocus() && position === null) || position === false) {\n return true;\n }\n // we don’t try to resolve a NodeSelection or CellSelection\n if (dispatch && position === null && !isTextSelection(editor.state.selection)) {\n delayedFocus();\n return true;\n }\n // pass through tr.doc instead of editor.state.doc\n // since transactions could change the editors state before this command has been run\n const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection;\n const isSameSelection = editor.state.selection.eq(selection);\n if (dispatch) {\n if (!isSameSelection) {\n tr.setSelection(selection);\n }\n // `tr.setSelection` resets the stored marks\n // so we’ll restore them if the selection is the same as before\n if (isSameSelection && tr.storedMarks) {\n tr.setStoredMarks(tr.storedMarks);\n }\n delayedFocus();\n }\n return true;\n};\n\nconst forEach = (items, fn) => props => {\n return items.every((item, index) => fn(item, { ...props, index }));\n};\n\nconst insertContent = (value, options) => ({ tr, commands }) => {\n return commands.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options);\n};\n\nconst removeWhitespaces = (node) => {\n const children = node.childNodes;\n for (let i = children.length - 1; i >= 0; i -= 1) {\n const child = children[i];\n if (child.nodeType === 3 && child.nodeValue && /^(\\n\\s\\s|\\n)$/.test(child.nodeValue)) {\n node.removeChild(child);\n }\n else if (child.nodeType === 1) {\n removeWhitespaces(child);\n }\n }\n return node;\n};\nfunction elementFromString(value) {\n // add a wrapper to preserve leading and trailing whitespace\n const wrappedValue = `${value}`;\n const html = new window.DOMParser().parseFromString(wrappedValue, 'text/html').body;\n return removeWhitespaces(html);\n}\n\n/**\n * Takes a JSON or HTML content and creates a Prosemirror node or fragment from it.\n * @param content The JSON or HTML content to create the node from\n * @param schema The Prosemirror schema to use for the node\n * @param options Options for the parser\n * @returns The created Prosemirror node or fragment\n */\nfunction createNodeFromContent(content, schema, options) {\n if (content instanceof Node$1 || content instanceof Fragment) {\n return content;\n }\n options = {\n slice: true,\n parseOptions: {},\n ...options,\n };\n const isJSONContent = typeof content === 'object' && content !== null;\n const isTextContent = typeof content === 'string';\n if (isJSONContent) {\n try {\n const isArrayContent = Array.isArray(content) && content.length > 0;\n // if the JSON Content is an array of nodes, create a fragment for each node\n if (isArrayContent) {\n return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)));\n }\n const node = schema.nodeFromJSON(content);\n if (options.errorOnInvalidContent) {\n node.check();\n }\n return node;\n }\n catch (error) {\n if (options.errorOnInvalidContent) {\n throw new Error('[tiptap error]: Invalid JSON content', { cause: error });\n }\n console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error);\n return createNodeFromContent('', schema, options);\n }\n }\n if (isTextContent) {\n // Check for invalid content\n if (options.errorOnInvalidContent) {\n let hasInvalidContent = false;\n let invalidContent = '';\n // A copy of the current schema with a catch-all node at the end\n const contentCheckSchema = new Schema({\n topNode: schema.spec.topNode,\n marks: schema.spec.marks,\n // Prosemirror's schemas are executed such that: the last to execute, matches last\n // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle\n nodes: schema.spec.nodes.append({\n __tiptap__private__unknown__catch__all__node: {\n content: 'inline*',\n group: 'block',\n parseDOM: [\n {\n tag: '*',\n getAttrs: e => {\n // If this is ever called, we know that the content has something that we don't know how to handle in the schema\n hasInvalidContent = true;\n // Try to stringify the element for a more helpful error message\n invalidContent = typeof e === 'string' ? e : e.outerHTML;\n return null;\n },\n },\n ],\n },\n }),\n });\n if (options.slice) {\n DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions);\n }\n else {\n DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions);\n }\n if (options.errorOnInvalidContent && hasInvalidContent) {\n throw new Error('[tiptap error]: Invalid HTML content', { cause: new Error(`Invalid element found: ${invalidContent}`) });\n }\n }\n const parser = DOMParser.fromSchema(schema);\n if (options.slice) {\n return parser.parseSlice(elementFromString(content), options.parseOptions).content;\n }\n return parser.parse(elementFromString(content), options.parseOptions);\n }\n return createNodeFromContent('', schema, options);\n}\n\n// source: https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.js#L466\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n const last = tr.steps.length - 1;\n if (last < startLen) {\n return;\n }\n const step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {\n return;\n }\n const map = tr.mapping.maps[last];\n let end = 0;\n map.forEach((_from, _to, _newFrom, newTo) => {\n if (end === 0) {\n end = newTo;\n }\n });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst isFragment = (nodeOrFragment) => {\n return !('type' in nodeOrFragment);\n};\nconst insertContentAt = (position, value, options) => ({ tr, dispatch, editor }) => {\n var _a;\n if (dispatch) {\n options = {\n parseOptions: editor.options.parseOptions,\n updateSelection: true,\n applyInputRules: false,\n applyPasteRules: false,\n ...options,\n };\n let content;\n try {\n content = createNodeFromContent(value, editor.schema, {\n parseOptions: {\n preserveWhitespace: 'full',\n ...options.parseOptions,\n },\n errorOnInvalidContent: (_a = options.errorOnInvalidContent) !== null && _a !== void 0 ? _a : editor.options.enableContentCheck,\n });\n }\n catch (e) {\n editor.emit('contentError', {\n editor,\n error: e,\n disableCollaboration: () => {\n if (editor.storage.collaboration) {\n editor.storage.collaboration.isDisabled = true;\n }\n },\n });\n return false;\n }\n let { from, to } = typeof position === 'number' ? { from: position, to: position } : { from: position.from, to: position.to };\n let isOnlyTextContent = true;\n let isOnlyBlockContent = true;\n const nodes = isFragment(content) ? content : [content];\n nodes.forEach(node => {\n // check if added node is valid\n node.check();\n isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false;\n isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false;\n });\n // check if we can replace the wrapping node by\n // the newly inserted content\n // example:\n // replace an empty paragraph by an inserted image\n // instead of inserting the image below the paragraph\n if (from === to && isOnlyBlockContent) {\n const { parent } = tr.doc.resolve(from);\n const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount;\n if (isEmptyTextBlock) {\n from -= 1;\n to += 1;\n }\n }\n let newContent;\n // if there is only plain text we have to use `insertText`\n // because this will keep the current marks\n if (isOnlyTextContent) {\n // if value is string, we can use it directly\n // otherwise if it is an array, we have to join it\n if (Array.isArray(value)) {\n newContent = value.map(v => v.text || '').join('');\n }\n else if (value instanceof Fragment) {\n let text = '';\n value.forEach(node => {\n if (node.text) {\n text += node.text;\n }\n });\n newContent = text;\n }\n else if (typeof value === 'object' && !!value && !!value.text) {\n newContent = value.text;\n }\n else {\n newContent = value;\n }\n tr.insertText(newContent, from, to);\n }\n else {\n newContent = content;\n tr.replaceWith(from, to, newContent);\n }\n // set cursor at end of inserted content\n if (options.updateSelection) {\n selectionToInsertionEnd(tr, tr.steps.length - 1, -1);\n }\n if (options.applyInputRules) {\n tr.setMeta('applyInputRules', { from, text: newContent });\n }\n if (options.applyPasteRules) {\n tr.setMeta('applyPasteRules', { from, text: newContent });\n }\n }\n return true;\n};\n\nconst joinUp = () => ({ state, dispatch }) => {\n return joinUp$1(state, dispatch);\n};\nconst joinDown = () => ({ state, dispatch }) => {\n return joinDown$1(state, dispatch);\n};\nconst joinBackward = () => ({ state, dispatch }) => {\n return joinBackward$1(state, dispatch);\n};\nconst joinForward = () => ({ state, dispatch }) => {\n return joinForward$1(state, dispatch);\n};\n\nconst joinItemBackward = () => ({ state, dispatch, tr, }) => {\n try {\n const point = joinPoint(state.doc, state.selection.$from.pos, -1);\n if (point === null || point === undefined) {\n return false;\n }\n tr.join(point, 2);\n if (dispatch) {\n dispatch(tr);\n }\n return true;\n }\n catch {\n return false;\n }\n};\n\nconst joinItemForward = () => ({ state, dispatch, tr, }) => {\n try {\n const point = joinPoint(state.doc, state.selection.$from.pos, +1);\n if (point === null || point === undefined) {\n return false;\n }\n tr.join(point, 2);\n if (dispatch) {\n dispatch(tr);\n }\n return true;\n }\n catch {\n return false;\n }\n};\n\nconst joinTextblockBackward = () => ({ state, dispatch }) => {\n return joinTextblockBackward$1(state, dispatch);\n};\n\nconst joinTextblockForward = () => ({ state, dispatch }) => {\n return joinTextblockForward$1(state, dispatch);\n};\n\nfunction isMacOS() {\n return typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false;\n}\n\nfunction normalizeKeyName(name) {\n const parts = name.split(/-(?!$)/);\n let result = parts[parts.length - 1];\n if (result === 'Space') {\n result = ' ';\n }\n let alt;\n let ctrl;\n let shift;\n let meta;\n for (let i = 0; i < parts.length - 1; i += 1) {\n const mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod)) {\n meta = true;\n }\n else if (/^a(lt)?$/i.test(mod)) {\n alt = true;\n }\n else if (/^(c|ctrl|control)$/i.test(mod)) {\n ctrl = true;\n }\n else if (/^s(hift)?$/i.test(mod)) {\n shift = true;\n }\n else if (/^mod$/i.test(mod)) {\n if (isiOS() || isMacOS()) {\n meta = true;\n }\n else {\n ctrl = true;\n }\n }\n else {\n throw new Error(`Unrecognized modifier name: ${mod}`);\n }\n }\n if (alt) {\n result = `Alt-${result}`;\n }\n if (ctrl) {\n result = `Ctrl-${result}`;\n }\n if (meta) {\n result = `Meta-${result}`;\n }\n if (shift) {\n result = `Shift-${result}`;\n }\n return result;\n}\nconst keyboardShortcut = name => ({ editor, view, tr, dispatch, }) => {\n const keys = normalizeKeyName(name).split(/-(?!$)/);\n const key = keys.find(item => !['Alt', 'Ctrl', 'Meta', 'Shift'].includes(item));\n const event = new KeyboardEvent('keydown', {\n key: key === 'Space'\n ? ' '\n : key,\n altKey: keys.includes('Alt'),\n ctrlKey: keys.includes('Ctrl'),\n metaKey: keys.includes('Meta'),\n shiftKey: keys.includes('Shift'),\n bubbles: true,\n cancelable: true,\n });\n const capturedTransaction = editor.captureTransaction(() => {\n view.someProp('handleKeyDown', f => f(view, event));\n });\n capturedTransaction === null || capturedTransaction === void 0 ? void 0 : capturedTransaction.steps.forEach(step => {\n const newStep = step.map(tr.mapping);\n if (newStep && dispatch) {\n tr.maybeStep(newStep);\n }\n });\n return true;\n};\n\nfunction isNodeActive(state, typeOrName, attributes = {}) {\n const { from, to, empty } = state.selection;\n const type = typeOrName ? getNodeType(typeOrName, state.schema) : null;\n const nodeRanges = [];\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (node.isText) {\n return;\n }\n const relativeFrom = Math.max(from, pos);\n const relativeTo = Math.min(to, pos + node.nodeSize);\n nodeRanges.push({\n node,\n from: relativeFrom,\n to: relativeTo,\n });\n });\n const selectionRange = to - from;\n const matchedNodeRanges = nodeRanges\n .filter(nodeRange => {\n if (!type) {\n return true;\n }\n return type.name === nodeRange.node.type.name;\n })\n .filter(nodeRange => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));\n if (empty) {\n return !!matchedNodeRanges.length;\n }\n const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0);\n return range >= selectionRange;\n}\n\nconst lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema);\n const isActive = isNodeActive(state, type, attributes);\n if (!isActive) {\n return false;\n }\n return lift$1(state, dispatch);\n};\n\nconst liftEmptyBlock = () => ({ state, dispatch }) => {\n return liftEmptyBlock$1(state, dispatch);\n};\n\nconst liftListItem = typeOrName => ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema);\n return liftListItem$1(type)(state, dispatch);\n};\n\nconst newlineInCode = () => ({ state, dispatch }) => {\n return newlineInCode$1(state, dispatch);\n};\n\n/**\n * Get the type of a schema item by its name.\n * @param name The name of the schema item\n * @param schema The Prosemiror schema to search in\n * @returns The type of the schema item (`node` or `mark`), or null if it doesn't exist\n */\nfunction getSchemaTypeNameByName(name, schema) {\n if (schema.nodes[name]) {\n return 'node';\n }\n if (schema.marks[name]) {\n return 'mark';\n }\n return null;\n}\n\n/**\n * Remove a property or an array of properties from an object\n * @param obj Object\n * @param key Key to remove\n */\nfunction deleteProps(obj, propOrProps) {\n const props = typeof propOrProps === 'string'\n ? [propOrProps]\n : propOrProps;\n return Object\n .keys(obj)\n .reduce((newObj, prop) => {\n if (!props.includes(prop)) {\n newObj[prop] = obj[prop];\n }\n return newObj;\n }, {});\n}\n\nconst resetAttributes = (typeOrName, attributes) => ({ tr, state, dispatch }) => {\n let nodeType = null;\n let markType = null;\n const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string' ? typeOrName : typeOrName.name, state.schema);\n if (!schemaType) {\n return false;\n }\n if (schemaType === 'node') {\n nodeType = getNodeType(typeOrName, state.schema);\n }\n if (schemaType === 'mark') {\n markType = getMarkType(typeOrName, state.schema);\n }\n if (dispatch) {\n tr.selection.ranges.forEach(range => {\n state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {\n if (nodeType && nodeType === node.type) {\n tr.setNodeMarkup(pos, undefined, deleteProps(node.attrs, attributes));\n }\n if (markType && node.marks.length) {\n node.marks.forEach(mark => {\n if (markType === mark.type) {\n tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)));\n }\n });\n }\n });\n });\n }\n return true;\n};\n\nconst scrollIntoView = () => ({ tr, dispatch }) => {\n if (dispatch) {\n tr.scrollIntoView();\n }\n return true;\n};\n\nconst selectAll = () => ({ tr, dispatch }) => {\n if (dispatch) {\n const selection = new AllSelection(tr.doc);\n tr.setSelection(selection);\n }\n return true;\n};\n\nconst selectNodeBackward = () => ({ state, dispatch }) => {\n return selectNodeBackward$1(state, dispatch);\n};\n\nconst selectNodeForward = () => ({ state, dispatch }) => {\n return selectNodeForward$1(state, dispatch);\n};\n\nconst selectParentNode = () => ({ state, dispatch }) => {\n return selectParentNode$1(state, dispatch);\n};\n\n// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nconst selectTextblockEnd = () => ({ state, dispatch }) => {\n return selectTextblockEnd$1(state, dispatch);\n};\n\n// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nconst selectTextblockStart = () => ({ state, dispatch }) => {\n return selectTextblockStart$1(state, dispatch);\n};\n\n/**\n * Create a new Prosemirror document node from content.\n * @param content The JSON or HTML content to create the document from\n * @param schema The Prosemirror schema to use for the document\n * @param parseOptions Options for the parser\n * @returns The created Prosemirror document node\n */\nfunction createDocument(content, schema, parseOptions = {}, options = {}) {\n return createNodeFromContent(content, schema, {\n slice: false,\n parseOptions,\n errorOnInvalidContent: options.errorOnInvalidContent,\n });\n}\n\nconst setContent = (content, emitUpdate = false, parseOptions = {}, options = {}) => ({ editor, tr, dispatch, commands, }) => {\n var _a, _b;\n const { doc } = tr;\n // This is to keep backward compatibility with the previous behavior\n // TODO remove this in the next major version\n if (parseOptions.preserveWhitespace !== 'full') {\n const document = createDocument(content, editor.schema, parseOptions, {\n errorOnInvalidContent: (_a = options.errorOnInvalidContent) !== null && _a !== void 0 ? _a : editor.options.enableContentCheck,\n });\n if (dispatch) {\n tr.replaceWith(0, doc.content.size, document).setMeta('preventUpdate', !emitUpdate);\n }\n return true;\n }\n if (dispatch) {\n tr.setMeta('preventUpdate', !emitUpdate);\n }\n return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {\n parseOptions,\n errorOnInvalidContent: (_b = options.errorOnInvalidContent) !== null && _b !== void 0 ? _b : editor.options.enableContentCheck,\n });\n};\n\nfunction getMarkAttributes(state, typeOrName) {\n const type = getMarkType(typeOrName, state.schema);\n const { from, to, empty } = state.selection;\n const marks = [];\n if (empty) {\n if (state.storedMarks) {\n marks.push(...state.storedMarks);\n }\n marks.push(...state.selection.$head.marks());\n }\n else {\n state.doc.nodesBetween(from, to, node => {\n marks.push(...node.marks);\n });\n }\n const mark = marks.find(markItem => markItem.type.name === type.name);\n if (!mark) {\n return {};\n }\n return { ...mark.attrs };\n}\n\n/**\n * Returns a new `Transform` based on all steps of the passed transactions.\n * @param oldDoc The Prosemirror node to start from\n * @param transactions The transactions to combine\n * @returns A new `Transform` with all steps of the passed transactions\n */\nfunction combineTransactionSteps(oldDoc, transactions) {\n const transform = new Transform(oldDoc);\n transactions.forEach(transaction => {\n transaction.steps.forEach(step => {\n transform.step(step);\n });\n });\n return transform;\n}\n\n/**\n * Gets the default block type at a given match\n * @param match The content match to get the default block type from\n * @returns The default block type or null\n */\nfunction defaultBlockAt(match) {\n for (let i = 0; i < match.edgeCount; i += 1) {\n const { type } = match.edge(i);\n if (type.isTextblock && !type.hasRequiredAttrs()) {\n return type;\n }\n }\n return null;\n}\n\n/**\n * Find children inside a Prosemirror node that match a predicate.\n * @param node The Prosemirror node to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nfunction findChildren(node, predicate) {\n const nodesWithPos = [];\n node.descendants((child, pos) => {\n if (predicate(child)) {\n nodesWithPos.push({\n node: child,\n pos,\n });\n }\n });\n return nodesWithPos;\n}\n\n/**\n * Same as `findChildren` but searches only within a `range`.\n * @param node The Prosemirror node to search in\n * @param range The range to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nfunction findChildrenInRange(node, range, predicate) {\n const nodesWithPos = [];\n // if (range.from === range.to) {\n // const nodeAt = node.nodeAt(range.from)\n // if (nodeAt) {\n // nodesWithPos.push({\n // node: nodeAt,\n // pos: range.from,\n // })\n // }\n // }\n node.nodesBetween(range.from, range.to, (child, pos) => {\n if (predicate(child)) {\n nodesWithPos.push({\n node: child,\n pos,\n });\n }\n });\n return nodesWithPos;\n}\n\n/**\n * Finds the closest parent node to a resolved position that matches a predicate.\n * @param $pos The resolved position to search from\n * @param predicate The predicate to match\n * @returns The closest parent node to the resolved position that matches the predicate\n * @example ```js\n * findParentNodeClosestToPos($from, node => node.type.name === 'paragraph')\n * ```\n */\nfunction findParentNodeClosestToPos($pos, predicate) {\n for (let i = $pos.depth; i > 0; i -= 1) {\n const node = $pos.node(i);\n if (predicate(node)) {\n return {\n pos: i > 0 ? $pos.before(i) : 0,\n start: $pos.start(i),\n depth: i,\n node,\n };\n }\n }\n}\n\n/**\n * Finds the closest parent node to the current selection that matches a predicate.\n * @param predicate The predicate to match\n * @returns A command that finds the closest parent node to the current selection that matches the predicate\n * @example ```js\n * findParentNode(node => node.type.name === 'paragraph')\n * ```\n */\nfunction findParentNode(predicate) {\n return (selection) => findParentNodeClosestToPos(selection.$from, predicate);\n}\n\nfunction getSchema(extensions, editor) {\n const resolvedExtensions = ExtensionManager.resolve(extensions);\n return getSchemaByResolvedExtensions(resolvedExtensions, editor);\n}\n\n/**\n * Generate HTML from a JSONContent\n * @param doc The JSONContent to generate HTML from\n * @param extensions The extensions to use for the schema\n * @returns The generated HTML\n */\nfunction generateHTML(doc, extensions) {\n const schema = getSchema(extensions);\n const contentNode = Node$1.fromJSON(schema, doc);\n return getHTMLFromFragment(contentNode.content, schema);\n}\n\n/**\n * Generate JSONContent from HTML\n * @param html The HTML to generate JSONContent from\n * @param extensions The extensions to use for the schema\n * @returns The generated JSONContent\n */\nfunction generateJSON(html, extensions) {\n const schema = getSchema(extensions);\n const dom = elementFromString(html);\n return DOMParser.fromSchema(schema).parse(dom).toJSON();\n}\n\n/**\n * Gets the text of a Prosemirror node\n * @param node The Prosemirror node\n * @param options Options for the text serializer & block separator\n * @returns The text of the node\n * @example ```js\n * const text = getText(node, { blockSeparator: '\\n' })\n * ```\n */\nfunction getText(node, options) {\n const range = {\n from: 0,\n to: node.content.size,\n };\n return getTextBetween(node, range, options);\n}\n\n/**\n * Generate raw text from a JSONContent\n * @param doc The JSONContent to generate text from\n * @param extensions The extensions to use for the schema\n * @param options Options for the text generation f.e. blockSeparator or textSerializers\n * @returns The generated text\n */\nfunction generateText(doc, extensions, options) {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {};\n const schema = getSchema(extensions);\n const contentNode = Node$1.fromJSON(schema, doc);\n return getText(contentNode, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(schema),\n ...textSerializers,\n },\n });\n}\n\nfunction getNodeAttributes(state, typeOrName) {\n const type = getNodeType(typeOrName, state.schema);\n const { from, to } = state.selection;\n const nodes = [];\n state.doc.nodesBetween(from, to, node => {\n nodes.push(node);\n });\n const node = nodes.reverse().find(nodeItem => nodeItem.type.name === type.name);\n if (!node) {\n return {};\n }\n return { ...node.attrs };\n}\n\n/**\n * Get node or mark attributes by type or name on the current editor state\n * @param state The current editor state\n * @param typeOrName The node or mark type or name\n * @returns The attributes of the node or mark or an empty object\n */\nfunction getAttributes(state, typeOrName) {\n const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string' ? typeOrName : typeOrName.name, state.schema);\n if (schemaType === 'node') {\n return getNodeAttributes(state, typeOrName);\n }\n if (schemaType === 'mark') {\n return getMarkAttributes(state, typeOrName);\n }\n return {};\n}\n\n/**\n * Removes duplicated values within an array.\n * Supports numbers, strings and objects.\n */\nfunction removeDuplicates(array, by = JSON.stringify) {\n const seen = {};\n return array.filter(item => {\n const key = by(item);\n return Object.prototype.hasOwnProperty.call(seen, key)\n ? false\n : (seen[key] = true);\n });\n}\n\n/**\n * Removes duplicated ranges and ranges that are\n * fully captured by other ranges.\n */\nfunction simplifyChangedRanges(changes) {\n const uniqueChanges = removeDuplicates(changes);\n return uniqueChanges.length === 1\n ? uniqueChanges\n : uniqueChanges.filter((change, index) => {\n const rest = uniqueChanges.filter((_, i) => i !== index);\n return !rest.some(otherChange => {\n return change.oldRange.from >= otherChange.oldRange.from\n && change.oldRange.to <= otherChange.oldRange.to\n && change.newRange.from >= otherChange.newRange.from\n && change.newRange.to <= otherChange.newRange.to;\n });\n });\n}\n/**\n * Returns a list of changed ranges\n * based on the first and last state of all steps.\n */\nfunction getChangedRanges(transform) {\n const { mapping, steps } = transform;\n const changes = [];\n mapping.maps.forEach((stepMap, index) => {\n const ranges = [];\n // This accounts for step changes where no range was actually altered\n // e.g. when setting a mark, node attribute, etc.\n // @ts-ignore\n if (!stepMap.ranges.length) {\n const { from, to } = steps[index];\n if (from === undefined || to === undefined) {\n return;\n }\n ranges.push({ from, to });\n }\n else {\n stepMap.forEach((from, to) => {\n ranges.push({ from, to });\n });\n }\n ranges.forEach(({ from, to }) => {\n const newStart = mapping.slice(index).map(from, -1);\n const newEnd = mapping.slice(index).map(to);\n const oldStart = mapping.invert().map(newStart, -1);\n const oldEnd = mapping.invert().map(newEnd);\n changes.push({\n oldRange: {\n from: oldStart,\n to: oldEnd,\n },\n newRange: {\n from: newStart,\n to: newEnd,\n },\n });\n });\n });\n return simplifyChangedRanges(changes);\n}\n\nfunction getDebugJSON(node, startOffset = 0) {\n const isTopNode = node.type === node.type.schema.topNodeType;\n const increment = isTopNode ? 0 : 1;\n const from = startOffset;\n const to = from + node.nodeSize;\n const marks = node.marks.map(mark => {\n const output = {\n type: mark.type.name,\n };\n if (Object.keys(mark.attrs).length) {\n output.attrs = { ...mark.attrs };\n }\n return output;\n });\n const attrs = { ...node.attrs };\n const output = {\n type: node.type.name,\n from,\n to,\n };\n if (Object.keys(attrs).length) {\n output.attrs = attrs;\n }\n if (marks.length) {\n output.marks = marks;\n }\n if (node.content.childCount) {\n output.content = [];\n node.forEach((child, offset) => {\n var _a;\n (_a = output.content) === null || _a === void 0 ? void 0 : _a.push(getDebugJSON(child, startOffset + offset + increment));\n });\n }\n if (node.text) {\n output.text = node.text;\n }\n return output;\n}\n\nfunction getMarksBetween(from, to, doc) {\n const marks = [];\n // get all inclusive marks on empty selection\n if (from === to) {\n doc\n .resolve(from)\n .marks()\n .forEach(mark => {\n const $pos = doc.resolve(from);\n const range = getMarkRange($pos, mark.type);\n if (!range) {\n return;\n }\n marks.push({\n mark,\n ...range,\n });\n });\n }\n else {\n doc.nodesBetween(from, to, (node, pos) => {\n if (!node || (node === null || node === void 0 ? void 0 : node.nodeSize) === undefined) {\n return;\n }\n marks.push(...node.marks.map(mark => ({\n from: pos,\n to: pos + node.nodeSize,\n mark,\n })));\n });\n }\n return marks;\n}\n\n/**\n * Finds the first node of a given type or name in the current selection.\n * @param state The editor state.\n * @param typeOrName The node type or name.\n * @param pos The position to start searching from.\n * @param maxDepth The maximum depth to search.\n * @returns The node and the depth as an array.\n */\nconst getNodeAtPosition = (state, typeOrName, pos, maxDepth = 20) => {\n const $pos = state.doc.resolve(pos);\n let currentDepth = maxDepth;\n let node = null;\n while (currentDepth > 0 && node === null) {\n const currentNode = $pos.node(currentDepth);\n if ((currentNode === null || currentNode === void 0 ? void 0 : currentNode.type.name) === typeOrName) {\n node = currentNode;\n }\n else {\n currentDepth -= 1;\n }\n }\n return [node, currentDepth];\n};\n\n/**\n * Return attributes of an extension that should be splitted by keepOnSplit flag\n * @param extensionAttributes Array of extension attributes\n * @param typeName The type of the extension\n * @param attributes The attributes of the extension\n * @returns The splitted attributes\n */\nfunction getSplittedAttributes(extensionAttributes, typeName, attributes) {\n return Object.fromEntries(Object\n .entries(attributes)\n .filter(([name]) => {\n const extensionAttribute = extensionAttributes.find(item => {\n return item.type === typeName && item.name === name;\n });\n if (!extensionAttribute) {\n return false;\n }\n return extensionAttribute.attribute.keepOnSplit;\n }));\n}\n\nfunction isMarkActive(state, typeOrName, attributes = {}) {\n const { empty, ranges } = state.selection;\n const type = typeOrName ? getMarkType(typeOrName, state.schema) : null;\n if (empty) {\n return !!(state.storedMarks || state.selection.$from.marks())\n .filter(mark => {\n if (!type) {\n return true;\n }\n return type.name === mark.type.name;\n })\n .find(mark => objectIncludes(mark.attrs, attributes, { strict: false }));\n }\n let selectionRange = 0;\n const markRanges = [];\n ranges.forEach(({ $from, $to }) => {\n const from = $from.pos;\n const to = $to.pos;\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isText && !node.marks.length) {\n return;\n }\n const relativeFrom = Math.max(from, pos);\n const relativeTo = Math.min(to, pos + node.nodeSize);\n const range = relativeTo - relativeFrom;\n selectionRange += range;\n markRanges.push(...node.marks.map(mark => ({\n mark,\n from: relativeFrom,\n to: relativeTo,\n })));\n });\n });\n if (selectionRange === 0) {\n return false;\n }\n // calculate range of matched mark\n const matchedRange = markRanges\n .filter(markRange => {\n if (!type) {\n return true;\n }\n return type.name === markRange.mark.type.name;\n })\n .filter(markRange => objectIncludes(markRange.mark.attrs, attributes, { strict: false }))\n .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);\n // calculate range of marks that excludes the searched mark\n // for example `code` doesn’t allow any other marks\n const excludedRange = markRanges\n .filter(markRange => {\n if (!type) {\n return true;\n }\n return markRange.mark.type !== type && markRange.mark.type.excludes(type);\n })\n .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);\n // we only include the result of `excludedRange`\n // if there is a match at all\n const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange;\n return range >= selectionRange;\n}\n\nfunction isActive(state, name, attributes = {}) {\n if (!name) {\n return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes);\n }\n const schemaType = getSchemaTypeNameByName(name, state.schema);\n if (schemaType === 'node') {\n return isNodeActive(state, name, attributes);\n }\n if (schemaType === 'mark') {\n return isMarkActive(state, name, attributes);\n }\n return false;\n}\n\nconst isAtEndOfNode = (state, nodeType) => {\n const { $from, $to, $anchor } = state.selection;\n if (nodeType) {\n const parentNode = findParentNode(node => node.type.name === nodeType)(state.selection);\n if (!parentNode) {\n return false;\n }\n const $parentPos = state.doc.resolve(parentNode.pos + 1);\n if ($anchor.pos + 1 === $parentPos.end()) {\n return true;\n }\n return false;\n }\n if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) {\n return false;\n }\n return true;\n};\n\nconst isAtStartOfNode = (state) => {\n const { $from, $to } = state.selection;\n if ($from.parentOffset > 0 || $from.pos !== $to.pos) {\n return false;\n }\n return true;\n};\n\nfunction isList(name, extensions) {\n const { nodeExtensions } = splitExtensions(extensions);\n const extension = nodeExtensions.find(item => item.name === name);\n if (!extension) {\n return false;\n }\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n };\n const group = callOrReturn(getExtensionField(extension, 'group', context));\n if (typeof group !== 'string') {\n return false;\n }\n return group.split(' ').includes('list');\n}\n\n/**\n * Returns true if the given prosemirror node is empty.\n */\nfunction isNodeEmpty(node, { checkChildren = true, ignoreWhitespace = false, } = {}) {\n var _a;\n if (ignoreWhitespace) {\n if (node.type.name === 'hardBreak') {\n // Hard breaks are considered empty\n return true;\n }\n if (node.isText) {\n return /^\\s*$/m.test((_a = node.text) !== null && _a !== void 0 ? _a : '');\n }\n }\n if (node.isText) {\n return !node.text;\n }\n if (node.isAtom || node.isLeaf) {\n return false;\n }\n if (node.content.childCount === 0) {\n return true;\n }\n if (checkChildren) {\n let isContentEmpty = true;\n node.content.forEach(childNode => {\n if (isContentEmpty === false) {\n // Exit early for perf\n return;\n }\n if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {\n isContentEmpty = false;\n }\n });\n return isContentEmpty;\n }\n return false;\n}\n\nfunction isNodeSelection(value) {\n return value instanceof NodeSelection;\n}\n\nfunction posToDOMRect(view, from, to) {\n const minPos = 0;\n const maxPos = view.state.doc.content.size;\n const resolvedFrom = minMax(from, minPos, maxPos);\n const resolvedEnd = minMax(to, minPos, maxPos);\n const start = view.coordsAtPos(resolvedFrom);\n const end = view.coordsAtPos(resolvedEnd, -1);\n const top = Math.min(start.top, end.top);\n const bottom = Math.max(start.bottom, end.bottom);\n const left = Math.min(start.left, end.left);\n const right = Math.max(start.right, end.right);\n const width = right - left;\n const height = bottom - top;\n const x = left;\n const y = top;\n const data = {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x,\n y,\n };\n return {\n ...data,\n toJSON: () => data,\n };\n}\n\n/**\n * The actual implementation of the rewriteUnknownContent function\n */\nfunction rewriteUnknownContentInner({ json, validMarks, validNodes, options, rewrittenContent = [], }) {\n if (json.marks && Array.isArray(json.marks)) {\n json.marks = json.marks.filter(mark => {\n const name = typeof mark === 'string' ? mark : mark.type;\n if (validMarks.has(name)) {\n return true;\n }\n rewrittenContent.push({\n original: JSON.parse(JSON.stringify(mark)),\n unsupported: name,\n });\n // Just ignore any unknown marks\n return false;\n });\n }\n if (json.content && Array.isArray(json.content)) {\n json.content = json.content\n .map(value => rewriteUnknownContentInner({\n json: value,\n validMarks,\n validNodes,\n options,\n rewrittenContent,\n }).json)\n .filter(a => a !== null && a !== undefined);\n }\n if (json.type && !validNodes.has(json.type)) {\n rewrittenContent.push({\n original: JSON.parse(JSON.stringify(json)),\n unsupported: json.type,\n });\n if (json.content && Array.isArray(json.content) && ((options === null || options === void 0 ? void 0 : options.fallbackToParagraph) !== false)) {\n // Just treat it like a paragraph and hope for the best\n json.type = 'paragraph';\n return {\n json,\n rewrittenContent,\n };\n }\n // or just omit it entirely\n return {\n json: null,\n rewrittenContent,\n };\n }\n return { json, rewrittenContent };\n}\n/**\n * Rewrite unknown nodes and marks within JSON content\n * Allowing for user within the editor\n */\nfunction rewriteUnknownContent(\n/**\n * The JSON content to clean of unknown nodes and marks\n */\njson, \n/**\n * The schema to use for validation\n */\nschema, \n/**\n * Options for the cleaning process\n */\noptions) {\n return rewriteUnknownContentInner({\n json,\n validNodes: new Set(Object.keys(schema.nodes)),\n validMarks: new Set(Object.keys(schema.marks)),\n options,\n });\n}\n\nfunction canSetMark(state, tr, newMarkType) {\n var _a;\n const { selection } = tr;\n let cursor = null;\n if (isTextSelection(selection)) {\n cursor = selection.$cursor;\n }\n if (cursor) {\n const currentMarks = (_a = state.storedMarks) !== null && _a !== void 0 ? _a : cursor.marks();\n // There can be no current marks that exclude the new mark\n return (!!newMarkType.isInSet(currentMarks)\n || !currentMarks.some(mark => mark.type.excludes(newMarkType)));\n }\n const { ranges } = selection;\n return ranges.some(({ $from, $to }) => {\n let someNodeSupportsMark = $from.depth === 0\n ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType)\n : false;\n state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {\n // If we already found a mark that we can enable, return false to bypass the remaining search\n if (someNodeSupportsMark) {\n return false;\n }\n if (node.isInline) {\n const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType);\n const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks)\n || !node.marks.some(otherMark => otherMark.type.excludes(newMarkType));\n someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType;\n }\n return !someNodeSupportsMark;\n });\n return someNodeSupportsMark;\n });\n}\nconst setMark = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {\n const { selection } = tr;\n const { empty, ranges } = selection;\n const type = getMarkType(typeOrName, state.schema);\n if (dispatch) {\n if (empty) {\n const oldAttributes = getMarkAttributes(state, type);\n tr.addStoredMark(type.create({\n ...oldAttributes,\n ...attributes,\n }));\n }\n else {\n ranges.forEach(range => {\n const from = range.$from.pos;\n const to = range.$to.pos;\n state.doc.nodesBetween(from, to, (node, pos) => {\n const trimmedFrom = Math.max(pos, from);\n const trimmedTo = Math.min(pos + node.nodeSize, to);\n const someHasMark = node.marks.find(mark => mark.type === type);\n // if there is already a mark of this type\n // we know that we have to merge its attributes\n // otherwise we add a fresh new mark\n if (someHasMark) {\n node.marks.forEach(mark => {\n if (type === mark.type) {\n tr.addMark(trimmedFrom, trimmedTo, type.create({\n ...mark.attrs,\n ...attributes,\n }));\n }\n });\n }\n else {\n tr.addMark(trimmedFrom, trimmedTo, type.create(attributes));\n }\n });\n });\n }\n }\n return canSetMark(state, tr, type);\n};\n\nconst setMeta = (key, value) => ({ tr }) => {\n tr.setMeta(key, value);\n return true;\n};\n\nconst setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {\n const type = getNodeType(typeOrName, state.schema);\n let attributesToCopy;\n if (state.selection.$anchor.sameParent(state.selection.$head)) {\n // only copy attributes if the selection is pointing to a node of the same type\n attributesToCopy = state.selection.$anchor.parent.attrs;\n }\n // TODO: use a fallback like insertContent?\n if (!type.isTextblock) {\n console.warn('[tiptap warn]: Currently \"setNode()\" only supports text block nodes.');\n return false;\n }\n return (chain()\n // try to convert node to default node if needed\n .command(({ commands }) => {\n const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state);\n if (canSetBlock) {\n return true;\n }\n return commands.clearNodes();\n })\n .command(({ state: updatedState }) => {\n return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch);\n })\n .run());\n};\n\nconst setNodeSelection = position => ({ tr, dispatch }) => {\n if (dispatch) {\n const { doc } = tr;\n const from = minMax(position, 0, doc.content.size);\n const selection = NodeSelection.create(doc, from);\n tr.setSelection(selection);\n }\n return true;\n};\n\nconst setTextSelection = position => ({ tr, dispatch }) => {\n if (dispatch) {\n const { doc } = tr;\n const { from, to } = typeof position === 'number' ? { from: position, to: position } : position;\n const minPos = TextSelection.atStart(doc).from;\n const maxPos = TextSelection.atEnd(doc).to;\n const resolvedFrom = minMax(from, minPos, maxPos);\n const resolvedEnd = minMax(to, minPos, maxPos);\n const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd);\n tr.setSelection(selection);\n }\n return true;\n};\n\nconst sinkListItem = typeOrName => ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema);\n return sinkListItem$1(type)(state, dispatch);\n};\n\nfunction ensureMarks(state, splittableMarks) {\n const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks) {\n const filteredMarks = marks.filter(mark => splittableMarks === null || splittableMarks === void 0 ? void 0 : splittableMarks.includes(mark.type.name));\n state.tr.ensureMarks(filteredMarks);\n }\n}\nconst splitBlock = ({ keepMarks = true } = {}) => ({ tr, state, dispatch, editor, }) => {\n const { selection, doc } = tr;\n const { $from, $to } = selection;\n const extensionAttributes = editor.extensionManager.attributes;\n const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);\n if (selection instanceof NodeSelection && selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(doc, $from.pos)) {\n return false;\n }\n if (dispatch) {\n if (keepMarks) {\n ensureMarks(state, editor.extensionManager.splittableMarks);\n }\n tr.split($from.pos).scrollIntoView();\n }\n return true;\n }\n if (!$from.parent.isBlock) {\n return false;\n }\n const atEnd = $to.parentOffset === $to.parent.content.size;\n const deflt = $from.depth === 0\n ? undefined\n : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));\n let types = atEnd && deflt\n ? [\n {\n type: deflt,\n attrs: newAttributes,\n },\n ]\n : undefined;\n let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);\n if (!types\n && !can\n && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : undefined)) {\n can = true;\n types = deflt\n ? [\n {\n type: deflt,\n attrs: newAttributes,\n },\n ]\n : undefined;\n }\n if (dispatch) {\n if (can) {\n if (selection instanceof TextSelection) {\n tr.deleteSelection();\n }\n tr.split(tr.mapping.map($from.pos), 1, types);\n if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {\n const first = tr.mapping.map($from.before());\n const $first = tr.doc.resolve(first);\n if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {\n tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);\n }\n }\n }\n if (keepMarks) {\n ensureMarks(state, editor.extensionManager.splittableMarks);\n }\n tr.scrollIntoView();\n }\n return can;\n};\n\nconst splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr, state, dispatch, editor, }) => {\n var _a;\n const type = getNodeType(typeOrName, state.schema);\n const { $from, $to } = state.selection;\n // @ts-ignore\n // eslint-disable-next-line\n const node = state.selection.node;\n if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {\n return false;\n }\n const grandParent = $from.node(-1);\n if (grandParent.type !== type) {\n return false;\n }\n const extensionAttributes = editor.extensionManager.attributes;\n if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {\n // In an empty block. If this is a nested list, the wrapping\n // list item should be split. Otherwise, bail out and let next\n // command handle lifting.\n if ($from.depth === 2\n || $from.node(-3).type !== type\n || $from.index(-2) !== $from.node(-2).childCount - 1) {\n return false;\n }\n if (dispatch) {\n let wrap = Fragment.empty;\n // eslint-disable-next-line\n const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;\n // Build a fragment containing empty versions of the structure\n // from the outer list item to the parent node of the cursor\n for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {\n wrap = Fragment.from($from.node(d).copy(wrap));\n }\n // eslint-disable-next-line\n const depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;\n // Add a second list item with an empty default start node\n const newNextTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n ...overrideAttrs,\n };\n const nextType = ((_a = type.contentMatch.defaultType) === null || _a === void 0 ? void 0 : _a.createAndFill(newNextTypeAttributes)) || undefined;\n wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType) || undefined));\n const start = $from.before($from.depth - (depthBefore - 1));\n tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));\n let sel = -1;\n tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {\n if (sel > -1) {\n return false;\n }\n if (n.isTextblock && n.content.size === 0) {\n sel = pos + 1;\n }\n });\n if (sel > -1) {\n tr.setSelection(TextSelection.near(tr.doc.resolve(sel)));\n }\n tr.scrollIntoView();\n }\n return true;\n }\n const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;\n const newTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),\n ...overrideAttrs,\n };\n const newNextTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n ...overrideAttrs,\n };\n tr.delete($from.pos, $to.pos);\n const types = nextType\n ? [\n { type, attrs: newTypeAttributes },\n { type: nextType, attrs: newNextTypeAttributes },\n ]\n : [{ type, attrs: newTypeAttributes }];\n if (!canSplit(tr.doc, $from.pos, 2)) {\n return false;\n }\n if (dispatch) {\n const { selection, storedMarks } = state;\n const { splittableMarks } = editor.extensionManager;\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks());\n tr.split($from.pos, 2, types).scrollIntoView();\n if (!marks || !dispatch) {\n return true;\n }\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name));\n tr.ensureMarks(filteredMarks);\n }\n return true;\n};\n\nconst joinListBackwards = (tr, listType) => {\n const list = findParentNode(node => node.type === listType)(tr.selection);\n if (!list) {\n return true;\n }\n const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth);\n if (before === undefined) {\n return true;\n }\n const nodeBefore = tr.doc.nodeAt(before);\n const canJoinBackwards = list.node.type === (nodeBefore === null || nodeBefore === void 0 ? void 0 : nodeBefore.type) && canJoin(tr.doc, list.pos);\n if (!canJoinBackwards) {\n return true;\n }\n tr.join(list.pos);\n return true;\n};\nconst joinListForwards = (tr, listType) => {\n const list = findParentNode(node => node.type === listType)(tr.selection);\n if (!list) {\n return true;\n }\n const after = tr.doc.resolve(list.start).after(list.depth);\n if (after === undefined) {\n return true;\n }\n const nodeAfter = tr.doc.nodeAt(after);\n const canJoinForwards = list.node.type === (nodeAfter === null || nodeAfter === void 0 ? void 0 : nodeAfter.type) && canJoin(tr.doc, after);\n if (!canJoinForwards) {\n return true;\n }\n tr.join(after);\n return true;\n};\nconst toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr, state, dispatch, chain, commands, can, }) => {\n const { extensions, splittableMarks } = editor.extensionManager;\n const listType = getNodeType(listTypeOrName, state.schema);\n const itemType = getNodeType(itemTypeOrName, state.schema);\n const { selection, storedMarks } = state;\n const { $from, $to } = selection;\n const range = $from.blockRange($to);\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks());\n if (!range) {\n return false;\n }\n const parentList = findParentNode(node => isList(node.type.name, extensions))(selection);\n if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {\n // remove list\n if (parentList.node.type === listType) {\n return commands.liftListItem(itemType);\n }\n // change list type\n if (isList(parentList.node.type.name, extensions)\n && listType.validContent(parentList.node.content)\n && dispatch) {\n return chain()\n .command(() => {\n tr.setNodeMarkup(parentList.pos, listType);\n return true;\n })\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run();\n }\n }\n if (!keepMarks || !marks || !dispatch) {\n return chain()\n // try to convert node to default node if needed\n .command(() => {\n const canWrapInList = can().wrapInList(listType, attributes);\n if (canWrapInList) {\n return true;\n }\n return commands.clearNodes();\n })\n .wrapInList(listType, attributes)\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run();\n }\n return (chain()\n // try to convert node to default node if needed\n .command(() => {\n const canWrapInList = can().wrapInList(listType, attributes);\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name));\n tr.ensureMarks(filteredMarks);\n if (canWrapInList) {\n return true;\n }\n return commands.clearNodes();\n })\n .wrapInList(listType, attributes)\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run());\n};\n\nconst toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => {\n const { extendEmptyMarkRange = false } = options;\n const type = getMarkType(typeOrName, state.schema);\n const isActive = isMarkActive(state, type, attributes);\n if (isActive) {\n return commands.unsetMark(type, { extendEmptyMarkRange });\n }\n return commands.setMark(type, attributes);\n};\n\nconst toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {\n const type = getNodeType(typeOrName, state.schema);\n const toggleType = getNodeType(toggleTypeOrName, state.schema);\n const isActive = isNodeActive(state, type, attributes);\n let attributesToCopy;\n if (state.selection.$anchor.sameParent(state.selection.$head)) {\n // only copy attributes if the selection is pointing to a node of the same type\n attributesToCopy = state.selection.$anchor.parent.attrs;\n }\n if (isActive) {\n return commands.setNode(toggleType, attributesToCopy);\n }\n // If the node is not active, we want to set the new node type with the given attributes\n // Copying over the attributes from the current node if the selection is pointing to a node of the same type\n return commands.setNode(type, { ...attributesToCopy, ...attributes });\n};\n\nconst toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => {\n const type = getNodeType(typeOrName, state.schema);\n const isActive = isNodeActive(state, type, attributes);\n if (isActive) {\n return commands.lift(type);\n }\n return commands.wrapIn(type, attributes);\n};\n\nconst undoInputRule = () => ({ state, dispatch }) => {\n const plugins = state.plugins;\n for (let i = 0; i < plugins.length; i += 1) {\n const plugin = plugins[i];\n let undoable;\n // @ts-ignore\n // eslint-disable-next-line\n if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {\n if (dispatch) {\n const tr = state.tr;\n const toUndo = undoable.transform;\n for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {\n tr.step(toUndo.steps[j].invert(toUndo.docs[j]));\n }\n if (undoable.text) {\n const marks = tr.doc.resolve(undoable.from).marks();\n tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));\n }\n else {\n tr.delete(undoable.from, undoable.to);\n }\n }\n return true;\n }\n }\n return false;\n};\n\nconst unsetAllMarks = () => ({ tr, dispatch }) => {\n const { selection } = tr;\n const { empty, ranges } = selection;\n if (empty) {\n return true;\n }\n if (dispatch) {\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos);\n });\n }\n return true;\n};\n\nconst unsetMark = (typeOrName, options = {}) => ({ tr, state, dispatch }) => {\n var _a;\n const { extendEmptyMarkRange = false } = options;\n const { selection } = tr;\n const type = getMarkType(typeOrName, state.schema);\n const { $from, empty, ranges } = selection;\n if (!dispatch) {\n return true;\n }\n if (empty && extendEmptyMarkRange) {\n let { from, to } = selection;\n const attrs = (_a = $from.marks().find(mark => mark.type === type)) === null || _a === void 0 ? void 0 : _a.attrs;\n const range = getMarkRange($from, type, attrs);\n if (range) {\n from = range.from;\n to = range.to;\n }\n tr.removeMark(from, to, type);\n }\n else {\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos, type);\n });\n }\n tr.removeStoredMark(type);\n return true;\n};\n\nconst updateAttributes = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {\n let nodeType = null;\n let markType = null;\n const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string' ? typeOrName : typeOrName.name, state.schema);\n if (!schemaType) {\n return false;\n }\n if (schemaType === 'node') {\n nodeType = getNodeType(typeOrName, state.schema);\n }\n if (schemaType === 'mark') {\n markType = getMarkType(typeOrName, state.schema);\n }\n if (dispatch) {\n tr.selection.ranges.forEach((range) => {\n const from = range.$from.pos;\n const to = range.$to.pos;\n let lastPos;\n let lastNode;\n let trimmedFrom;\n let trimmedTo;\n if (tr.selection.empty) {\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (nodeType && nodeType === node.type) {\n trimmedFrom = Math.max(pos, from);\n trimmedTo = Math.min(pos + node.nodeSize, to);\n lastPos = pos;\n lastNode = node;\n }\n });\n }\n else {\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (pos < from && nodeType && nodeType === node.type) {\n trimmedFrom = Math.max(pos, from);\n trimmedTo = Math.min(pos + node.nodeSize, to);\n lastPos = pos;\n lastNode = node;\n }\n if (pos >= from && pos <= to) {\n if (nodeType && nodeType === node.type) {\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n ...attributes,\n });\n }\n if (markType && node.marks.length) {\n node.marks.forEach((mark) => {\n if (markType === mark.type) {\n const trimmedFrom2 = Math.max(pos, from);\n const trimmedTo2 = Math.min(pos + node.nodeSize, to);\n tr.addMark(trimmedFrom2, trimmedTo2, markType.create({\n ...mark.attrs,\n ...attributes,\n }));\n }\n });\n }\n }\n });\n }\n if (lastNode) {\n if (lastPos !== undefined) {\n tr.setNodeMarkup(lastPos, undefined, {\n ...lastNode.attrs,\n ...attributes,\n });\n }\n if (markType && lastNode.marks.length) {\n lastNode.marks.forEach((mark) => {\n if (markType === mark.type) {\n tr.addMark(trimmedFrom, trimmedTo, markType.create({\n ...mark.attrs,\n ...attributes,\n }));\n }\n });\n }\n }\n });\n }\n return true;\n};\n\nconst wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema);\n return wrapIn$1(type, attributes)(state, dispatch);\n};\n\nconst wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema);\n return wrapInList$1(type, attributes)(state, dispatch);\n};\n\nvar commands = /*#__PURE__*/Object.freeze({\n __proto__: null,\n blur: blur,\n clearContent: clearContent,\n clearNodes: clearNodes,\n command: command,\n createParagraphNear: createParagraphNear,\n cut: cut,\n deleteCurrentNode: deleteCurrentNode,\n deleteNode: deleteNode,\n deleteRange: deleteRange,\n deleteSelection: deleteSelection,\n enter: enter,\n exitCode: exitCode,\n extendMarkRange: extendMarkRange,\n first: first,\n focus: focus,\n forEach: forEach,\n insertContent: insertContent,\n insertContentAt: insertContentAt,\n joinBackward: joinBackward,\n joinDown: joinDown,\n joinForward: joinForward,\n joinItemBackward: joinItemBackward,\n joinItemForward: joinItemForward,\n joinTextblockBackward: joinTextblockBackward,\n joinTextblockForward: joinTextblockForward,\n joinUp: joinUp,\n keyboardShortcut: keyboardShortcut,\n lift: lift,\n liftEmptyBlock: liftEmptyBlock,\n liftListItem: liftListItem,\n newlineInCode: newlineInCode,\n resetAttributes: resetAttributes,\n scrollIntoView: scrollIntoView,\n selectAll: selectAll,\n selectNodeBackward: selectNodeBackward,\n selectNodeForward: selectNodeForward,\n selectParentNode: selectParentNode,\n selectTextblockEnd: selectTextblockEnd,\n selectTextblockStart: selectTextblockStart,\n setContent: setContent,\n setMark: setMark,\n setMeta: setMeta,\n setNode: setNode,\n setNodeSelection: setNodeSelection,\n setTextSelection: setTextSelection,\n sinkListItem: sinkListItem,\n splitBlock: splitBlock,\n splitListItem: splitListItem,\n toggleList: toggleList,\n toggleMark: toggleMark,\n toggleNode: toggleNode,\n toggleWrap: toggleWrap,\n undoInputRule: undoInputRule,\n unsetAllMarks: unsetAllMarks,\n unsetMark: unsetMark,\n updateAttributes: updateAttributes,\n wrapIn: wrapIn,\n wrapInList: wrapInList\n});\n\nconst Commands = Extension.create({\n name: 'commands',\n addCommands() {\n return {\n ...commands,\n };\n },\n});\n\nconst Drop = Extension.create({\n name: 'drop',\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tiptapDrop'),\n props: {\n handleDrop: (_, e, slice, moved) => {\n this.editor.emit('drop', {\n editor: this.editor,\n event: e,\n slice,\n moved,\n });\n },\n },\n }),\n ];\n },\n});\n\nconst Editable = Extension.create({\n name: 'editable',\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('editable'),\n props: {\n editable: () => this.editor.options.editable,\n },\n }),\n ];\n },\n});\n\nconst FocusEvents = Extension.create({\n name: 'focusEvents',\n addProseMirrorPlugins() {\n const { editor } = this;\n return [\n new Plugin({\n key: new PluginKey('focusEvents'),\n props: {\n handleDOMEvents: {\n focus: (view, event) => {\n editor.isFocused = true;\n const transaction = editor.state.tr\n .setMeta('focus', { event })\n .setMeta('addToHistory', false);\n view.dispatch(transaction);\n return false;\n },\n blur: (view, event) => {\n editor.isFocused = false;\n const transaction = editor.state.tr\n .setMeta('blur', { event })\n .setMeta('addToHistory', false);\n view.dispatch(transaction);\n return false;\n },\n },\n },\n }),\n ];\n },\n});\n\nconst Keymap = Extension.create({\n name: 'keymap',\n addKeyboardShortcuts() {\n const handleBackspace = () => this.editor.commands.first(({ commands }) => [\n () => commands.undoInputRule(),\n // maybe convert first text block node to default node\n () => commands.command(({ tr }) => {\n const { selection, doc } = tr;\n const { empty, $anchor } = selection;\n const { pos, parent } = $anchor;\n const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor;\n const parentIsIsolating = $parentPos.parent.type.spec.isolating;\n const parentPos = $anchor.pos - $anchor.parentOffset;\n const isAtStart = (parentIsIsolating && $parentPos.parent.childCount === 1)\n ? parentPos === $anchor.pos\n : Selection.atStart(doc).from === pos;\n if (!empty\n || !parent.type.isTextblock\n || parent.textContent.length\n || !isAtStart\n || (isAtStart && $anchor.parent.type.name === 'paragraph') // prevent clearNodes when no nodes to clear, otherwise history stack is appended\n ) {\n return false;\n }\n return commands.clearNodes();\n }),\n () => commands.deleteSelection(),\n () => commands.joinBackward(),\n () => commands.selectNodeBackward(),\n ]);\n const handleDelete = () => this.editor.commands.first(({ commands }) => [\n () => commands.deleteSelection(),\n () => commands.deleteCurrentNode(),\n () => commands.joinForward(),\n () => commands.selectNodeForward(),\n ]);\n const handleEnter = () => this.editor.commands.first(({ commands }) => [\n () => commands.newlineInCode(),\n () => commands.createParagraphNear(),\n () => commands.liftEmptyBlock(),\n () => commands.splitBlock(),\n ]);\n const baseKeymap = {\n Enter: handleEnter,\n 'Mod-Enter': () => this.editor.commands.exitCode(),\n Backspace: handleBackspace,\n 'Mod-Backspace': handleBackspace,\n 'Shift-Backspace': handleBackspace,\n Delete: handleDelete,\n 'Mod-Delete': handleDelete,\n 'Mod-a': () => this.editor.commands.selectAll(),\n };\n const pcKeymap = {\n ...baseKeymap,\n };\n const macKeymap = {\n ...baseKeymap,\n 'Ctrl-h': handleBackspace,\n 'Alt-Backspace': handleBackspace,\n 'Ctrl-d': handleDelete,\n 'Ctrl-Alt-Backspace': handleDelete,\n 'Alt-Delete': handleDelete,\n 'Alt-d': handleDelete,\n 'Ctrl-a': () => this.editor.commands.selectTextblockStart(),\n 'Ctrl-e': () => this.editor.commands.selectTextblockEnd(),\n };\n if (isiOS() || isMacOS()) {\n return macKeymap;\n }\n return pcKeymap;\n },\n addProseMirrorPlugins() {\n return [\n // With this plugin we check if the whole document was selected and deleted.\n // In this case we will additionally call `clearNodes()` to convert e.g. a heading\n // to a paragraph if necessary.\n // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well\n // with many other commands.\n new Plugin({\n key: new PluginKey('clearDocument'),\n appendTransaction: (transactions, oldState, newState) => {\n if (transactions.some(tr => tr.getMeta('composition'))) {\n return;\n }\n const docChanges = transactions.some(transaction => transaction.docChanged)\n && !oldState.doc.eq(newState.doc);\n const ignoreTr = transactions.some(transaction => transaction.getMeta('preventClearDocument'));\n if (!docChanges || ignoreTr) {\n return;\n }\n const { empty, from, to } = oldState.selection;\n const allFrom = Selection.atStart(oldState.doc).from;\n const allEnd = Selection.atEnd(oldState.doc).to;\n const allWasSelected = from === allFrom && to === allEnd;\n if (empty || !allWasSelected) {\n return;\n }\n const isEmpty = isNodeEmpty(newState.doc);\n if (!isEmpty) {\n return;\n }\n const tr = newState.tr;\n const state = createChainableState({\n state: newState,\n transaction: tr,\n });\n const { commands } = new CommandManager({\n editor: this.editor,\n state,\n });\n commands.clearNodes();\n if (!tr.steps.length) {\n return;\n }\n return tr;\n },\n }),\n ];\n },\n});\n\nconst Paste = Extension.create({\n name: 'paste',\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tiptapPaste'),\n props: {\n handlePaste: (_view, e, slice) => {\n this.editor.emit('paste', {\n editor: this.editor,\n event: e,\n slice,\n });\n },\n },\n }),\n ];\n },\n});\n\nconst Tabindex = Extension.create({\n name: 'tabindex',\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tabindex'),\n props: {\n attributes: () => (this.editor.isEditable ? { tabindex: '0' } : {}),\n },\n }),\n ];\n },\n});\n\nvar index = /*#__PURE__*/Object.freeze({\n __proto__: null,\n ClipboardTextSerializer: ClipboardTextSerializer,\n Commands: Commands,\n Drop: Drop,\n Editable: Editable,\n FocusEvents: FocusEvents,\n Keymap: Keymap,\n Paste: Paste,\n Tabindex: Tabindex\n});\n\nclass NodePos {\n get name() {\n return this.node.type.name;\n }\n constructor(pos, editor, isBlock = false, node = null) {\n this.currentNode = null;\n this.actualDepth = null;\n this.isBlock = isBlock;\n this.resolvedPos = pos;\n this.editor = editor;\n this.currentNode = node;\n }\n get node() {\n return this.currentNode || this.resolvedPos.node();\n }\n get element() {\n return this.editor.view.domAtPos(this.pos).node;\n }\n get depth() {\n var _a;\n return (_a = this.actualDepth) !== null && _a !== void 0 ? _a : this.resolvedPos.depth;\n }\n get pos() {\n return this.resolvedPos.pos;\n }\n get content() {\n return this.node.content;\n }\n set content(content) {\n let from = this.from;\n let to = this.to;\n if (this.isBlock) {\n if (this.content.size === 0) {\n console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);\n return;\n }\n from = this.from + 1;\n to = this.to - 1;\n }\n this.editor.commands.insertContentAt({ from, to }, content);\n }\n get attributes() {\n return this.node.attrs;\n }\n get textContent() {\n return this.node.textContent;\n }\n get size() {\n return this.node.nodeSize;\n }\n get from() {\n if (this.isBlock) {\n return this.pos;\n }\n return this.resolvedPos.start(this.resolvedPos.depth);\n }\n get range() {\n return {\n from: this.from,\n to: this.to,\n };\n }\n get to() {\n if (this.isBlock) {\n return this.pos + this.size;\n }\n return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1);\n }\n get parent() {\n if (this.depth === 0) {\n return null;\n }\n const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1);\n const $pos = this.resolvedPos.doc.resolve(parentPos);\n return new NodePos($pos, this.editor);\n }\n get before() {\n let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2));\n if ($pos.depth !== this.depth) {\n $pos = this.resolvedPos.doc.resolve(this.from - 3);\n }\n return new NodePos($pos, this.editor);\n }\n get after() {\n let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1));\n if ($pos.depth !== this.depth) {\n $pos = this.resolvedPos.doc.resolve(this.to + 3);\n }\n return new NodePos($pos, this.editor);\n }\n get children() {\n const children = [];\n this.node.content.forEach((node, offset) => {\n const isBlock = node.isBlock && !node.isTextblock;\n const isNonTextAtom = node.isAtom && !node.isText;\n const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1);\n const $pos = this.resolvedPos.doc.resolve(targetPos);\n if (!isBlock && $pos.depth <= this.depth) {\n return;\n }\n const childNodePos = new NodePos($pos, this.editor, isBlock, isBlock ? node : null);\n if (isBlock) {\n childNodePos.actualDepth = this.depth + 1;\n }\n children.push(new NodePos($pos, this.editor, isBlock, isBlock ? node : null));\n });\n return children;\n }\n get firstChild() {\n return this.children[0] || null;\n }\n get lastChild() {\n const children = this.children;\n return children[children.length - 1] || null;\n }\n closest(selector, attributes = {}) {\n let node = null;\n let currentNode = this.parent;\n while (currentNode && !node) {\n if (currentNode.node.type.name === selector) {\n if (Object.keys(attributes).length > 0) {\n const nodeAttributes = currentNode.node.attrs;\n const attrKeys = Object.keys(attributes);\n for (let index = 0; index < attrKeys.length; index += 1) {\n const key = attrKeys[index];\n if (nodeAttributes[key] !== attributes[key]) {\n break;\n }\n }\n }\n else {\n node = currentNode;\n }\n }\n currentNode = currentNode.parent;\n }\n return node;\n }\n querySelector(selector, attributes = {}) {\n return this.querySelectorAll(selector, attributes, true)[0] || null;\n }\n querySelectorAll(selector, attributes = {}, firstItemOnly = false) {\n let nodes = [];\n if (!this.children || this.children.length === 0) {\n return nodes;\n }\n const attrKeys = Object.keys(attributes);\n /**\n * Finds all children recursively that match the selector and attributes\n * If firstItemOnly is true, it will return the first item found\n */\n this.children.forEach(childPos => {\n // If we already found a node and we only want the first item, we dont need to keep going\n if (firstItemOnly && nodes.length > 0) {\n return;\n }\n if (childPos.node.type.name === selector) {\n const doesAllAttributesMatch = attrKeys.every(key => attributes[key] === childPos.node.attrs[key]);\n if (doesAllAttributesMatch) {\n nodes.push(childPos);\n }\n }\n // If we already found a node and we only want the first item, we can stop here and skip the recursion\n if (firstItemOnly && nodes.length > 0) {\n return;\n }\n nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly));\n });\n return nodes;\n }\n setAttribute(attributes) {\n const { tr } = this.editor.state;\n tr.setNodeMarkup(this.from, undefined, {\n ...this.node.attrs,\n ...attributes,\n });\n this.editor.view.dispatch(tr);\n }\n}\n\nconst style = `.ProseMirror {\n position: relative;\n}\n\n.ProseMirror {\n word-wrap: break-word;\n white-space: pre-wrap;\n white-space: break-spaces;\n -webkit-font-variant-ligatures: none;\n font-variant-ligatures: none;\n font-feature-settings: \"liga\" 0; /* the above doesn't seem to work in Edge */\n}\n\n.ProseMirror [contenteditable=\"false\"] {\n white-space: normal;\n}\n\n.ProseMirror [contenteditable=\"false\"] [contenteditable=\"true\"] {\n white-space: pre-wrap;\n}\n\n.ProseMirror pre {\n white-space: pre-wrap;\n}\n\nimg.ProseMirror-separator {\n display: inline !important;\n border: none !important;\n margin: 0 !important;\n width: 0 !important;\n height: 0 !important;\n}\n\n.ProseMirror-gapcursor {\n display: none;\n pointer-events: none;\n position: absolute;\n margin: 0;\n}\n\n.ProseMirror-gapcursor:after {\n content: \"\";\n display: block;\n position: absolute;\n top: -2px;\n width: 20px;\n border-top: 1px solid black;\n animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;\n}\n\n@keyframes ProseMirror-cursor-blink {\n to {\n visibility: hidden;\n }\n}\n\n.ProseMirror-hideselection *::selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection *::-moz-selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection * {\n caret-color: transparent;\n}\n\n.ProseMirror-focused .ProseMirror-gapcursor {\n display: block;\n}\n\n.tippy-box[data-animation=fade][data-state=hidden] {\n opacity: 0\n}`;\n\nfunction createStyleTag(style, nonce, suffix) {\n const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ''}]`);\n if (tiptapStyleTag !== null) {\n return tiptapStyleTag;\n }\n const styleNode = document.createElement('style');\n if (nonce) {\n styleNode.setAttribute('nonce', nonce);\n }\n styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ''}`, '');\n styleNode.innerHTML = style;\n document.getElementsByTagName('head')[0].appendChild(styleNode);\n return styleNode;\n}\n\nclass Editor extends EventEmitter {\n constructor(options = {}) {\n super();\n this.isFocused = false;\n /**\n * The editor is considered initialized after the `create` event has been emitted.\n */\n this.isInitialized = false;\n this.extensionStorage = {};\n this.options = {\n element: document.createElement('div'),\n content: '',\n injectCSS: true,\n injectNonce: undefined,\n extensions: [],\n autofocus: false,\n editable: true,\n editorProps: {},\n parseOptions: {},\n coreExtensionOptions: {},\n enableInputRules: true,\n enablePasteRules: true,\n enableCoreExtensions: true,\n enableContentCheck: false,\n onBeforeCreate: () => null,\n onCreate: () => null,\n onUpdate: () => null,\n onSelectionUpdate: () => null,\n onTransaction: () => null,\n onFocus: () => null,\n onBlur: () => null,\n onDestroy: () => null,\n onContentError: ({ error }) => { throw error; },\n onPaste: () => null,\n onDrop: () => null,\n };\n this.isCapturingTransaction = false;\n this.capturedTransaction = null;\n this.setOptions(options);\n this.createExtensionManager();\n this.createCommandManager();\n this.createSchema();\n this.on('beforeCreate', this.options.onBeforeCreate);\n this.emit('beforeCreate', { editor: this });\n this.on('contentError', this.options.onContentError);\n this.createView();\n this.injectCSS();\n this.on('create', this.options.onCreate);\n this.on('update', this.options.onUpdate);\n this.on('selectionUpdate', this.options.onSelectionUpdate);\n this.on('transaction', this.options.onTransaction);\n this.on('focus', this.options.onFocus);\n this.on('blur', this.options.onBlur);\n this.on('destroy', this.options.onDestroy);\n this.on('drop', ({ event, slice, moved }) => this.options.onDrop(event, slice, moved));\n this.on('paste', ({ event, slice }) => this.options.onPaste(event, slice));\n window.setTimeout(() => {\n if (this.isDestroyed) {\n return;\n }\n this.commands.focus(this.options.autofocus);\n this.emit('create', { editor: this });\n this.isInitialized = true;\n }, 0);\n }\n /**\n * Returns the editor storage.\n */\n get storage() {\n return this.extensionStorage;\n }\n /**\n * An object of all registered commands.\n */\n get commands() {\n return this.commandManager.commands;\n }\n /**\n * Create a command chain to call multiple commands at once.\n */\n chain() {\n return this.commandManager.chain();\n }\n /**\n * Check if a command or a command chain can be executed. Without executing it.\n */\n can() {\n return this.commandManager.can();\n }\n /**\n * Inject CSS styles.\n */\n injectCSS() {\n if (this.options.injectCSS && document) {\n this.css = createStyleTag(style, this.options.injectNonce);\n }\n }\n /**\n * Update editor options.\n *\n * @param options A list of options\n */\n setOptions(options = {}) {\n this.options = {\n ...this.options,\n ...options,\n };\n if (!this.view || !this.state || this.isDestroyed) {\n return;\n }\n if (this.options.editorProps) {\n this.view.setProps(this.options.editorProps);\n }\n this.view.updateState(this.state);\n }\n /**\n * Update editable state of the editor.\n */\n setEditable(editable, emitUpdate = true) {\n this.setOptions({ editable });\n if (emitUpdate) {\n this.emit('update', { editor: this, transaction: this.state.tr });\n }\n }\n /**\n * Returns whether the editor is editable.\n */\n get isEditable() {\n // since plugins are applied after creating the view\n // `editable` is always `true` for one tick.\n // that’s why we also have to check for `options.editable`\n return this.options.editable && this.view && this.view.editable;\n }\n /**\n * Returns the editor state.\n */\n get state() {\n return this.view.state;\n }\n /**\n * Register a ProseMirror plugin.\n *\n * @param plugin A ProseMirror plugin\n * @param handlePlugins Control how to merge the plugin into the existing plugins.\n * @returns The new editor state\n */\n registerPlugin(plugin, handlePlugins) {\n const plugins = isFunction(handlePlugins)\n ? handlePlugins(plugin, [...this.state.plugins])\n : [...this.state.plugins, plugin];\n const state = this.state.reconfigure({ plugins });\n this.view.updateState(state);\n return state;\n }\n /**\n * Unregister a ProseMirror plugin.\n *\n * @param nameOrPluginKeyToRemove The plugins name\n * @returns The new editor state or undefined if the editor is destroyed\n */\n unregisterPlugin(nameOrPluginKeyToRemove) {\n if (this.isDestroyed) {\n return undefined;\n }\n const prevPlugins = this.state.plugins;\n let plugins = prevPlugins;\n [].concat(nameOrPluginKeyToRemove).forEach(nameOrPluginKey => {\n // @ts-ignore\n const name = typeof nameOrPluginKey === 'string' ? `${nameOrPluginKey}$` : nameOrPluginKey.key;\n // @ts-ignore\n plugins = prevPlugins.filter(plugin => !plugin.key.startsWith(name));\n });\n if (prevPlugins.length === plugins.length) {\n // No plugin was removed, so we don’t need to update the state\n return undefined;\n }\n const state = this.state.reconfigure({\n plugins,\n });\n this.view.updateState(state);\n return state;\n }\n /**\n * Creates an extension manager.\n */\n createExtensionManager() {\n var _a, _b;\n const coreExtensions = this.options.enableCoreExtensions ? [\n Editable,\n ClipboardTextSerializer.configure({\n blockSeparator: (_b = (_a = this.options.coreExtensionOptions) === null || _a === void 0 ? void 0 : _a.clipboardTextSerializer) === null || _b === void 0 ? void 0 : _b.blockSeparator,\n }),\n Commands,\n FocusEvents,\n Keymap,\n Tabindex,\n Drop,\n Paste,\n ].filter(ext => {\n if (typeof this.options.enableCoreExtensions === 'object') {\n return this.options.enableCoreExtensions[ext.name] !== false;\n }\n return true;\n }) : [];\n const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {\n return ['extension', 'node', 'mark'].includes(extension === null || extension === void 0 ? void 0 : extension.type);\n });\n this.extensionManager = new ExtensionManager(allExtensions, this);\n }\n /**\n * Creates an command manager.\n */\n createCommandManager() {\n this.commandManager = new CommandManager({\n editor: this,\n });\n }\n /**\n * Creates a ProseMirror schema.\n */\n createSchema() {\n this.schema = this.extensionManager.schema;\n }\n /**\n * Creates a ProseMirror view.\n */\n createView() {\n var _a;\n let doc;\n try {\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: this.options.enableContentCheck });\n }\n catch (e) {\n if (!(e instanceof Error) || !['[tiptap error]: Invalid JSON content', '[tiptap error]: Invalid HTML content'].includes(e.message)) {\n // Not the content error we were expecting\n throw e;\n }\n this.emit('contentError', {\n editor: this,\n error: e,\n disableCollaboration: () => {\n if (this.storage.collaboration) {\n this.storage.collaboration.isDisabled = true;\n }\n // To avoid syncing back invalid content, reinitialize the extensions without the collaboration extension\n this.options.extensions = this.options.extensions.filter(extension => extension.name !== 'collaboration');\n // Restart the initialization process by recreating the extension manager with the new set of extensions\n this.createExtensionManager();\n },\n });\n // Content is invalid, but attempt to create it anyway, stripping out the invalid parts\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: false });\n }\n const selection = resolveFocusPosition(doc, this.options.autofocus);\n this.view = new EditorView(this.options.element, {\n ...this.options.editorProps,\n attributes: {\n // add `role=\"textbox\"` to the editor element\n role: 'textbox',\n ...(_a = this.options.editorProps) === null || _a === void 0 ? void 0 : _a.attributes,\n },\n dispatchTransaction: this.dispatchTransaction.bind(this),\n state: EditorState.create({\n doc,\n selection: selection || undefined,\n }),\n });\n // `editor.view` is not yet available at this time.\n // Therefore we will add all plugins and node views directly afterwards.\n const newState = this.state.reconfigure({\n plugins: this.extensionManager.plugins,\n });\n this.view.updateState(newState);\n this.createNodeViews();\n this.prependClass();\n // Let’s store the editor instance in the DOM element.\n // So we’ll have access to it for tests.\n // @ts-ignore\n const dom = this.view.dom;\n dom.editor = this;\n }\n /**\n * Creates all node views.\n */\n createNodeViews() {\n if (this.view.isDestroyed) {\n return;\n }\n this.view.setProps({\n nodeViews: this.extensionManager.nodeViews,\n });\n }\n /**\n * Prepend class name to element.\n */\n prependClass() {\n this.view.dom.className = `tiptap ${this.view.dom.className}`;\n }\n captureTransaction(fn) {\n this.isCapturingTransaction = true;\n fn();\n this.isCapturingTransaction = false;\n const tr = this.capturedTransaction;\n this.capturedTransaction = null;\n return tr;\n }\n /**\n * The callback over which to send transactions (state updates) produced by the view.\n *\n * @param transaction An editor state transaction\n */\n dispatchTransaction(transaction) {\n // if the editor / the view of the editor was destroyed\n // the transaction should not be dispatched as there is no view anymore.\n if (this.view.isDestroyed) {\n return;\n }\n if (this.isCapturingTransaction) {\n if (!this.capturedTransaction) {\n this.capturedTransaction = transaction;\n return;\n }\n transaction.steps.forEach(step => { var _a; return (_a = this.capturedTransaction) === null || _a === void 0 ? void 0 : _a.step(step); });\n return;\n }\n const state = this.state.apply(transaction);\n const selectionHasChanged = !this.state.selection.eq(state.selection);\n this.emit('beforeTransaction', {\n editor: this,\n transaction,\n nextState: state,\n });\n this.view.updateState(state);\n this.emit('transaction', {\n editor: this,\n transaction,\n });\n if (selectionHasChanged) {\n this.emit('selectionUpdate', {\n editor: this,\n transaction,\n });\n }\n const focus = transaction.getMeta('focus');\n const blur = transaction.getMeta('blur');\n if (focus) {\n this.emit('focus', {\n editor: this,\n event: focus.event,\n transaction,\n });\n }\n if (blur) {\n this.emit('blur', {\n editor: this,\n event: blur.event,\n transaction,\n });\n }\n if (!transaction.docChanged || transaction.getMeta('preventUpdate')) {\n return;\n }\n this.emit('update', {\n editor: this,\n transaction,\n });\n }\n /**\n * Get attributes of the currently selected node or mark.\n */\n getAttributes(nameOrType) {\n return getAttributes(this.state, nameOrType);\n }\n isActive(nameOrAttributes, attributesOrUndefined) {\n const name = typeof nameOrAttributes === 'string' ? nameOrAttributes : null;\n const attributes = typeof nameOrAttributes === 'string' ? attributesOrUndefined : nameOrAttributes;\n return isActive(this.state, name, attributes);\n }\n /**\n * Get the document as JSON.\n */\n getJSON() {\n return this.state.doc.toJSON();\n }\n /**\n * Get the document as HTML.\n */\n getHTML() {\n return getHTMLFromFragment(this.state.doc.content, this.schema);\n }\n /**\n * Get the document as text.\n */\n getText(options) {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {};\n return getText(this.state.doc, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(this.schema),\n ...textSerializers,\n },\n });\n }\n /**\n * Check if there is no content.\n */\n get isEmpty() {\n return isNodeEmpty(this.state.doc);\n }\n /**\n * Get the number of characters for the current document.\n *\n * @deprecated\n */\n getCharacterCount() {\n console.warn('[tiptap warn]: \"editor.getCharacterCount()\" is deprecated. Please use \"editor.storage.characterCount.characters()\" instead.');\n return this.state.doc.content.size - 2;\n }\n /**\n * Destroy the editor.\n */\n destroy() {\n this.emit('destroy');\n if (this.view) {\n // Cleanup our reference to prevent circular references which caused memory leaks\n // @ts-ignore\n const dom = this.view.dom;\n if (dom && dom.editor) {\n delete dom.editor;\n }\n this.view.destroy();\n }\n this.removeAllListeners();\n }\n /**\n * Check if the editor is already destroyed.\n */\n get isDestroyed() {\n var _a;\n // @ts-ignore\n return !((_a = this.view) === null || _a === void 0 ? void 0 : _a.docView);\n }\n $node(selector, attributes) {\n var _a;\n return ((_a = this.$doc) === null || _a === void 0 ? void 0 : _a.querySelector(selector, attributes)) || null;\n }\n $nodes(selector, attributes) {\n var _a;\n return ((_a = this.$doc) === null || _a === void 0 ? void 0 : _a.querySelectorAll(selector, attributes)) || null;\n }\n $pos(pos) {\n const $pos = this.state.doc.resolve(pos);\n return new NodePos($pos, this);\n }\n get $doc() {\n return this.$pos(0);\n }\n}\n\n/**\n * Build an input rule that adds a mark when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nfunction markInputRule(config) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match);\n if (attributes === false || attributes === null) {\n return null;\n }\n const { tr } = state;\n const captureGroup = match[match.length - 1];\n const fullMatch = match[0];\n if (captureGroup) {\n const startSpaces = fullMatch.search(/\\S/);\n const textStart = range.from + fullMatch.indexOf(captureGroup);\n const textEnd = textStart + captureGroup.length;\n const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n .filter(item => {\n // @ts-ignore\n const excluded = item.mark.type.excluded;\n return excluded.find(type => type === config.type && type !== item.mark.type);\n })\n .filter(item => item.to > textStart);\n if (excludedMarks.length) {\n return null;\n }\n if (textEnd < range.to) {\n tr.delete(textEnd, range.to);\n }\n if (textStart > range.from) {\n tr.delete(range.from + startSpaces, textStart);\n }\n const markEnd = range.from + startSpaces + captureGroup.length;\n tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}));\n tr.removeStoredMark(config.type);\n }\n },\n });\n}\n\n/**\n * Build an input rule that adds a node when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nfunction nodeInputRule(config) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {};\n const { tr } = state;\n const start = range.from;\n let end = range.to;\n const newNode = config.type.create(attributes);\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1]);\n let matchStart = start + offset;\n if (matchStart > end) {\n matchStart = end;\n }\n else {\n end = matchStart + match[1].length;\n }\n // insert last typed character\n const lastChar = match[0][match[0].length - 1];\n tr.insertText(lastChar, start + match[0].length - 1);\n // insert node from input rule\n tr.replaceWith(matchStart, end, newNode);\n }\n else if (match[0]) {\n const insertionStart = config.type.isInline ? start : start - 1;\n tr.insert(insertionStart, config.type.create(attributes)).delete(tr.mapping.map(start), tr.mapping.map(end));\n }\n tr.scrollIntoView();\n },\n });\n}\n\n/**\n * Build an input rule that changes the type of a textblock when the\n * matched text is typed into it. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nfunction textblockTypeInputRule(config) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const $start = state.doc.resolve(range.from);\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {};\n if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {\n return null;\n }\n state.tr\n .delete(range.from, range.to)\n .setBlockType(range.from, range.from, config.type, attributes);\n },\n });\n}\n\n/**\n * Build an input rule that replaces text when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nfunction textInputRule(config) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace;\n let start = range.from;\n const end = range.to;\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1]);\n insert += match[0].slice(offset + match[1].length);\n start += offset;\n const cutOff = start - end;\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert;\n start = end;\n }\n }\n state.tr.insertText(insert, start, end);\n },\n });\n}\n\n/**\n * Build an input rule for automatically wrapping a textblock when a\n * given string is typed. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n *\n * `type` is the type of node to wrap in.\n *\n * By default, if there’s a node with the same type above the newly\n * wrapped node, the rule will try to join those\n * two nodes. You can pass a join predicate, which takes a regular\n * expression match and the node before the wrapped node, and can\n * return a boolean to indicate whether a join should happen.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nfunction wrappingInputRule(config) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match, chain, }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {};\n const tr = state.tr.delete(range.from, range.to);\n const $start = tr.doc.resolve(range.from);\n const blockRange = $start.blockRange();\n const wrapping = blockRange && findWrapping(blockRange, config.type, attributes);\n if (!wrapping) {\n return null;\n }\n tr.wrap(blockRange, wrapping);\n if (config.keepMarks && config.editor) {\n const { selection, storedMarks } = state;\n const { splittableMarks } = config.editor.extensionManager;\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks());\n if (marks) {\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name));\n tr.ensureMarks(filteredMarks);\n }\n }\n if (config.keepAttributes) {\n /** If the nodeType is `bulletList` or `orderedList` set the `nodeType` as `listItem` */\n const nodeType = config.type.name === 'bulletList' || config.type.name === 'orderedList' ? 'listItem' : 'taskList';\n chain().updateAttributes(nodeType, attributes).run();\n }\n const before = tr.doc.resolve(range.from - 1).nodeBefore;\n if (before\n && before.type === config.type\n && canJoin(tr.doc, range.from - 1)\n && (!config.joinPredicate || config.joinPredicate(match, before))) {\n tr.join(range.from - 1);\n }\n },\n });\n}\n\n/**\n * The Node class is used to create custom node extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nclass Node {\n constructor(config = {}) {\n this.type = 'node';\n this.name = 'node';\n this.parent = null;\n this.child = null;\n this.config = {\n name: this.name,\n defaultOptions: {},\n };\n this.config = {\n ...this.config,\n ...config,\n };\n this.name = this.config.name;\n if (config.defaultOptions && Object.keys(config.defaultOptions).length > 0) {\n console.warn(`[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${this.name}\".`);\n }\n // TODO: remove `addOptions` fallback\n this.options = this.config.defaultOptions;\n if (this.config.addOptions) {\n this.options = callOrReturn(getExtensionField(this, 'addOptions', {\n name: this.name,\n }));\n }\n this.storage = callOrReturn(getExtensionField(this, 'addStorage', {\n name: this.name,\n options: this.options,\n })) || {};\n }\n static create(config = {}) {\n return new Node(config);\n }\n configure(options = {}) {\n // return a new instance so we can use the same extension\n // with different calls of `configure`\n const extension = this.extend({\n ...this.config,\n addOptions: () => {\n return mergeDeep(this.options, options);\n },\n });\n // Always preserve the current name\n extension.name = this.name;\n // Set the parent to be our parent\n extension.parent = this.parent;\n return extension;\n }\n extend(extendedConfig = {}) {\n const extension = new Node(extendedConfig);\n extension.parent = this;\n this.child = extension;\n extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name;\n if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {\n console.warn(`[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${extension.name}\".`);\n }\n extension.options = callOrReturn(getExtensionField(extension, 'addOptions', {\n name: extension.name,\n }));\n extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {\n name: extension.name,\n options: extension.options,\n }));\n return extension;\n }\n}\n\n/**\n * Node views are used to customize the rendered DOM structure of a node.\n * @see https://tiptap.dev/guide/node-views\n */\nclass NodeView {\n constructor(component, props, options) {\n this.isDragging = false;\n this.component = component;\n this.editor = props.editor;\n this.options = {\n stopEvent: null,\n ignoreMutation: null,\n ...options,\n };\n this.extension = props.extension;\n this.node = props.node;\n this.decorations = props.decorations;\n this.innerDecorations = props.innerDecorations;\n this.view = props.view;\n this.HTMLAttributes = props.HTMLAttributes;\n this.getPos = props.getPos;\n this.mount();\n }\n mount() {\n // eslint-disable-next-line\n return;\n }\n get dom() {\n return this.editor.view.dom;\n }\n get contentDOM() {\n return null;\n }\n onDragStart(event) {\n var _a, _b, _c, _d, _e, _f, _g;\n const { view } = this.editor;\n const target = event.target;\n // get the drag handle element\n // `closest` is not available for text nodes so we may have to use its parent\n const dragHandle = target.nodeType === 3\n ? (_a = target.parentElement) === null || _a === void 0 ? void 0 : _a.closest('[data-drag-handle]')\n : target.closest('[data-drag-handle]');\n if (!this.dom || ((_b = this.contentDOM) === null || _b === void 0 ? void 0 : _b.contains(target)) || !dragHandle) {\n return;\n }\n let x = 0;\n let y = 0;\n // calculate offset for drag element if we use a different drag handle element\n if (this.dom !== dragHandle) {\n const domBox = this.dom.getBoundingClientRect();\n const handleBox = dragHandle.getBoundingClientRect();\n // In React, we have to go through nativeEvent to reach offsetX/offsetY.\n const offsetX = (_c = event.offsetX) !== null && _c !== void 0 ? _c : (_d = event.nativeEvent) === null || _d === void 0 ? void 0 : _d.offsetX;\n const offsetY = (_e = event.offsetY) !== null && _e !== void 0 ? _e : (_f = event.nativeEvent) === null || _f === void 0 ? void 0 : _f.offsetY;\n x = handleBox.x - domBox.x + offsetX;\n y = handleBox.y - domBox.y + offsetY;\n }\n (_g = event.dataTransfer) === null || _g === void 0 ? void 0 : _g.setDragImage(this.dom, x, y);\n const pos = this.getPos();\n if (typeof pos !== 'number') {\n return;\n }\n // we need to tell ProseMirror that we want to move the whole node\n // so we create a NodeSelection\n const selection = NodeSelection.create(view.state.doc, pos);\n const transaction = view.state.tr.setSelection(selection);\n view.dispatch(transaction);\n }\n stopEvent(event) {\n var _a;\n if (!this.dom) {\n return false;\n }\n if (typeof this.options.stopEvent === 'function') {\n return this.options.stopEvent({ event });\n }\n const target = event.target;\n const isInElement = this.dom.contains(target) && !((_a = this.contentDOM) === null || _a === void 0 ? void 0 : _a.contains(target));\n // any event from child nodes should be handled by ProseMirror\n if (!isInElement) {\n return false;\n }\n const isDragEvent = event.type.startsWith('drag');\n const isDropEvent = event.type === 'drop';\n const isInput = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'].includes(target.tagName) || target.isContentEditable;\n // any input event within node views should be ignored by ProseMirror\n if (isInput && !isDropEvent && !isDragEvent) {\n return true;\n }\n const { isEditable } = this.editor;\n const { isDragging } = this;\n const isDraggable = !!this.node.type.spec.draggable;\n const isSelectable = NodeSelection.isSelectable(this.node);\n const isCopyEvent = event.type === 'copy';\n const isPasteEvent = event.type === 'paste';\n const isCutEvent = event.type === 'cut';\n const isClickEvent = event.type === 'mousedown';\n // ProseMirror tries to drag selectable nodes\n // even if `draggable` is set to `false`\n // this fix prevents that\n if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) {\n event.preventDefault();\n }\n if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) {\n event.preventDefault();\n return false;\n }\n // we have to store that dragging started\n if (isDraggable && isEditable && !isDragging && isClickEvent) {\n const dragHandle = target.closest('[data-drag-handle]');\n const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle));\n if (isValidDragHandle) {\n this.isDragging = true;\n document.addEventListener('dragend', () => {\n this.isDragging = false;\n }, { once: true });\n document.addEventListener('drop', () => {\n this.isDragging = false;\n }, { once: true });\n document.addEventListener('mouseup', () => {\n this.isDragging = false;\n }, { once: true });\n }\n }\n // these events are handled by prosemirror\n if (isDragging\n || isDropEvent\n || isCopyEvent\n || isPasteEvent\n || isCutEvent\n || (isClickEvent && isSelectable)) {\n return false;\n }\n return true;\n }\n /**\n * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.\n * @return `false` if the editor should re-read the selection or re-parse the range around the mutation\n * @return `true` if it can safely be ignored.\n */\n ignoreMutation(mutation) {\n if (!this.dom || !this.contentDOM) {\n return true;\n }\n if (typeof this.options.ignoreMutation === 'function') {\n return this.options.ignoreMutation({ mutation });\n }\n // a leaf/atom node is like a black box for ProseMirror\n // and should be fully handled by the node view\n if (this.node.isLeaf || this.node.isAtom) {\n return true;\n }\n // ProseMirror should handle any selections\n if (mutation.type === 'selection') {\n return false;\n }\n // try to prevent a bug on iOS and Android that will break node views on enter\n // this is because ProseMirror can’t preventDispatch on enter\n // this will lead to a re-render of the node view on enter\n // see: https://github.com/ueberdosis/tiptap/issues/1214\n // see: https://github.com/ueberdosis/tiptap/issues/2534\n if (this.dom.contains(mutation.target)\n && mutation.type === 'childList'\n && (isiOS() || isAndroid())\n && this.editor.isFocused) {\n const changedNodes = [\n ...Array.from(mutation.addedNodes),\n ...Array.from(mutation.removedNodes),\n ];\n // we’ll check if every changed node is contentEditable\n // to make sure it’s probably mutated by ProseMirror\n if (changedNodes.every(node => node.isContentEditable)) {\n return false;\n }\n }\n // we will allow mutation contentDOM with attributes\n // so we can for example adding classes within our node view\n if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n return true;\n }\n // ProseMirror should handle any changes within contentDOM\n if (this.contentDOM.contains(mutation.target)) {\n return false;\n }\n return true;\n }\n /**\n * Update the attributes of the prosemirror node.\n */\n updateAttributes(attributes) {\n this.editor.commands.command(({ tr }) => {\n const pos = this.getPos();\n if (typeof pos !== 'number') {\n return false;\n }\n tr.setNodeMarkup(pos, undefined, {\n ...this.node.attrs,\n ...attributes,\n });\n return true;\n });\n }\n /**\n * Delete the node.\n */\n deleteNode() {\n const from = this.getPos();\n if (typeof from !== 'number') {\n return;\n }\n const to = from + this.node.nodeSize;\n this.editor.commands.deleteRange({ from, to });\n }\n}\n\n/**\n * Build an paste rule that adds a mark when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nfunction markPasteRule(config) {\n return new PasteRule({\n find: config.find,\n handler: ({ state, range, match, pasteEvent, }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent);\n if (attributes === false || attributes === null) {\n return null;\n }\n const { tr } = state;\n const captureGroup = match[match.length - 1];\n const fullMatch = match[0];\n let markEnd = range.to;\n if (captureGroup) {\n const startSpaces = fullMatch.search(/\\S/);\n const textStart = range.from + fullMatch.indexOf(captureGroup);\n const textEnd = textStart + captureGroup.length;\n const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n .filter(item => {\n // @ts-ignore\n const excluded = item.mark.type.excluded;\n return excluded.find(type => type === config.type && type !== item.mark.type);\n })\n .filter(item => item.to > textStart);\n if (excludedMarks.length) {\n return null;\n }\n if (textEnd < range.to) {\n tr.delete(textEnd, range.to);\n }\n if (textStart > range.from) {\n tr.delete(range.from + startSpaces, textStart);\n }\n markEnd = range.from + startSpaces + captureGroup.length;\n tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}));\n tr.removeStoredMark(config.type);\n }\n },\n });\n}\n\n// source: https://stackoverflow.com/a/6969486\nfunction escapeForRegEx(string) {\n return string.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n}\n\nfunction isString(value) {\n return typeof value === 'string';\n}\n\n/**\n * Build an paste rule that adds a node when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nfunction nodePasteRule(config) {\n return new PasteRule({\n find: config.find,\n handler({ match, chain, range, pasteEvent, }) {\n const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent);\n const content = callOrReturn(config.getContent, undefined, attributes);\n if (attributes === false || attributes === null) {\n return null;\n }\n const node = { type: config.type.name, attrs: attributes };\n if (content) {\n node.content = content;\n }\n if (match.input) {\n chain().deleteRange(range).insertContentAt(range.from, node);\n }\n },\n });\n}\n\n/**\n * Build an paste rule that replaces text when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nfunction textPasteRule(config) {\n return new PasteRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace;\n let start = range.from;\n const end = range.to;\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1]);\n insert += match[0].slice(offset + match[1].length);\n start += offset;\n const cutOff = start - end;\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert;\n start = end;\n }\n }\n state.tr.insertText(insert, start, end);\n },\n });\n}\n\nclass Tracker {\n constructor(transaction) {\n this.transaction = transaction;\n this.currentStep = this.transaction.steps.length;\n }\n map(position) {\n let deleted = false;\n const mappedPosition = this.transaction.steps\n .slice(this.currentStep)\n .reduce((newPosition, step) => {\n const mapResult = step.getMap().mapResult(newPosition);\n if (mapResult.deleted) {\n deleted = true;\n }\n return mapResult.pos;\n }, position);\n return {\n position: mappedPosition,\n deleted,\n };\n }\n}\n\nexport { CommandManager, Editor, Extension, InputRule, Mark, Node, NodePos, NodeView, PasteRule, Tracker, callOrReturn, combineTransactionSteps, createChainableState, createDocument, createNodeFromContent, createStyleTag, defaultBlockAt, deleteProps, elementFromString, escapeForRegEx, index as extensions, findChildren, findChildrenInRange, findDuplicates, findParentNode, findParentNodeClosestToPos, fromString, generateHTML, generateJSON, generateText, getAttributes, getAttributesFromExtensions, getChangedRanges, getDebugJSON, getExtensionField, getHTMLFromFragment, getMarkAttributes, getMarkRange, getMarkType, getMarksBetween, getNodeAtPosition, getNodeAttributes, getNodeType, getRenderedAttributes, getSchema, getSchemaByResolvedExtensions, getSchemaTypeByName, getSchemaTypeNameByName, getSplittedAttributes, getText, getTextBetween, getTextContentFromNodes, getTextSerializersFromSchema, injectExtensionAttributesToParseRule, inputRulesPlugin, isActive, isAtEndOfNode, isAtStartOfNode, isEmptyObject, isExtensionRulesEnabled, isFunction, isList, isMacOS, isMarkActive, isNodeActive, isNodeEmpty, isNodeSelection, isNumber, isPlainObject, isRegExp, isString, isTextSelection, isiOS, markInputRule, markPasteRule, mergeAttributes, mergeDeep, minMax, nodeInputRule, nodePasteRule, objectIncludes, pasteRulesPlugin, posToDOMRect, removeDuplicates, resolveFocusPosition, rewriteUnknownContent, selectionToInsertionEnd, splitExtensions, textInputRule, textPasteRule, textblockTypeInputRule, wrappingInputRule };\n//# sourceMappingURL=index.js.map\n","// THIS FILE IS AUTOMATICALLY GENERATED DO NOT EDIT DIRECTLY\n// See update-tlds.js for encoding/decoding format\n// https://data.iana.org/TLD/tlds-alpha-by-domain.txt\nconst encodedTlds = 'aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2ntley5rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6logistics9properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3ncaster6d0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2psy3ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0america6xi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2';\n// Internationalized domain names containing non-ASCII\nconst encodedUtlds = 'ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2';\n\n/**\n * @template A\n * @template B\n * @param {A} target\n * @param {B} properties\n * @return {A & B}\n */\nconst assign = (target, properties) => {\n for (const key in properties) {\n target[key] = properties[key];\n }\n return target;\n};\n\n/**\n * Finite State Machine generation utilities\n */\n\n/**\n * @template T\n * @typedef {{ [group: string]: T[] }} Collections\n */\n\n/**\n * @typedef {{ [group: string]: true }} Flags\n */\n\n// Keys in scanner Collections instances\nconst numeric = 'numeric';\nconst ascii = 'ascii';\nconst alpha = 'alpha';\nconst asciinumeric = 'asciinumeric';\nconst alphanumeric = 'alphanumeric';\nconst domain = 'domain';\nconst emoji = 'emoji';\nconst scheme = 'scheme';\nconst slashscheme = 'slashscheme';\nconst whitespace = 'whitespace';\n\n/**\n * @template T\n * @param {string} name\n * @param {Collections} groups to register in\n * @returns {T[]} Current list of tokens in the given collection\n */\nfunction registerGroup(name, groups) {\n if (!(name in groups)) {\n groups[name] = [];\n }\n return groups[name];\n}\n\n/**\n * @template T\n * @param {T} t token to add\n * @param {Collections} groups\n * @param {Flags} flags\n */\nfunction addToGroups(t, flags, groups) {\n if (flags[numeric]) {\n flags[asciinumeric] = true;\n flags[alphanumeric] = true;\n }\n if (flags[ascii]) {\n flags[asciinumeric] = true;\n flags[alpha] = true;\n }\n if (flags[asciinumeric]) {\n flags[alphanumeric] = true;\n }\n if (flags[alpha]) {\n flags[alphanumeric] = true;\n }\n if (flags[alphanumeric]) {\n flags[domain] = true;\n }\n if (flags[emoji]) {\n flags[domain] = true;\n }\n for (const k in flags) {\n const group = registerGroup(k, groups);\n if (group.indexOf(t) < 0) {\n group.push(t);\n }\n }\n}\n\n/**\n * @template T\n * @param {T} t token to check\n * @param {Collections} groups\n * @returns {Flags} group flags that contain this token\n */\nfunction flagsForToken(t, groups) {\n const result = {};\n for (const c in groups) {\n if (groups[c].indexOf(t) >= 0) {\n result[c] = true;\n }\n }\n return result;\n}\n\n/**\n * @template T\n * @typedef {null | T } Transition\n */\n\n/**\n * Define a basic state machine state. j is the list of character transitions,\n * jr is the list of regex-match transitions, jd is the default state to\n * transition to t is the accepting token type, if any. If this is the terminal\n * state, then it does not emit a token.\n *\n * The template type T represents the type of the token this state accepts. This\n * should be a string (such as of the token exports in `text.js`) or a\n * MultiToken subclass (from `multi.js`)\n *\n * @template T\n * @param {T} [token] Token that this state emits\n */\nfunction State(token = null) {\n // this.n = null; // DEBUG: State name\n /** @type {{ [input: string]: State }} j */\n this.j = {}; // IMPLEMENTATION 1\n // this.j = []; // IMPLEMENTATION 2\n /** @type {[RegExp, State][]} jr */\n this.jr = [];\n /** @type {?State} jd */\n this.jd = null;\n /** @type {?T} t */\n this.t = token;\n}\n\n/**\n * Scanner token groups\n * @type Collections\n */\nState.groups = {};\nState.prototype = {\n accepts() {\n return !!this.t;\n },\n /**\n * Follow an existing transition from the given input to the next state.\n * Does not mutate.\n * @param {string} input character or token type to transition on\n * @returns {?State} the next state, if any\n */\n go(input) {\n const state = this;\n const nextState = state.j[input];\n if (nextState) {\n return nextState;\n }\n for (let i = 0; i < state.jr.length; i++) {\n const regex = state.jr[i][0];\n const nextState = state.jr[i][1]; // note: might be empty to prevent default jump\n if (nextState && regex.test(input)) {\n return nextState;\n }\n }\n // Nowhere left to jump! Return default, if any\n return state.jd;\n },\n /**\n * Whether the state has a transition for the given input. Set the second\n * argument to true to only look for an exact match (and not a default or\n * regular-expression-based transition)\n * @param {string} input\n * @param {boolean} exactOnly\n */\n has(input, exactOnly = false) {\n return exactOnly ? input in this.j : !!this.go(input);\n },\n /**\n * Short for \"transition all\"; create a transition from the array of items\n * in the given list to the same final resulting state.\n * @param {string | string[]} inputs Group of inputs to transition on\n * @param {Transition | State} [next] Transition options\n * @param {Flags} [flags] Collections flags to add token to\n * @param {Collections} [groups] Master list of token groups\n */\n ta(inputs, next, flags, groups) {\n for (let i = 0; i < inputs.length; i++) {\n this.tt(inputs[i], next, flags, groups);\n }\n },\n /**\n * Short for \"take regexp transition\"; defines a transition for this state\n * when it encounters a token which matches the given regular expression\n * @param {RegExp} regexp Regular expression transition (populate first)\n * @param {T | State} [next] Transition options\n * @param {Flags} [flags] Collections flags to add token to\n * @param {Collections} [groups] Master list of token groups\n * @returns {State} taken after the given input\n */\n tr(regexp, next, flags, groups) {\n groups = groups || State.groups;\n let nextState;\n if (next && next.j) {\n nextState = next;\n } else {\n // Token with maybe token groups\n nextState = new State(next);\n if (flags && groups) {\n addToGroups(next, flags, groups);\n }\n }\n this.jr.push([regexp, nextState]);\n return nextState;\n },\n /**\n * Short for \"take transitions\", will take as many sequential transitions as\n * the length of the given input and returns the\n * resulting final state.\n * @param {string | string[]} input\n * @param {T | State} [next] Transition options\n * @param {Flags} [flags] Collections flags to add token to\n * @param {Collections} [groups] Master list of token groups\n * @returns {State} taken after the given input\n */\n ts(input, next, flags, groups) {\n let state = this;\n const len = input.length;\n if (!len) {\n return state;\n }\n for (let i = 0; i < len - 1; i++) {\n state = state.tt(input[i]);\n }\n return state.tt(input[len - 1], next, flags, groups);\n },\n /**\n * Short for \"take transition\", this is a method for building/working with\n * state machines.\n *\n * If a state already exists for the given input, returns it.\n *\n * If a token is specified, that state will emit that token when reached by\n * the linkify engine.\n *\n * If no state exists, it will be initialized with some default transitions\n * that resemble existing default transitions.\n *\n * If a state is given for the second argument, that state will be\n * transitioned to on the given input regardless of what that input\n * previously did.\n *\n * Specify a token group flags to define groups that this token belongs to.\n * The token will be added to corresponding entires in the given groups\n * object.\n *\n * @param {string} input character, token type to transition on\n * @param {T | State} [next] Transition options\n * @param {Flags} [flags] Collections flags to add token to\n * @param {Collections} [groups] Master list of groups\n * @returns {State} taken after the given input\n */\n tt(input, next, flags, groups) {\n groups = groups || State.groups;\n const state = this;\n\n // Check if existing state given, just a basic transition\n if (next && next.j) {\n state.j[input] = next;\n return next;\n }\n const t = next;\n\n // Take the transition with the usual default mechanisms and use that as\n // a template for creating the next state\n let nextState,\n templateState = state.go(input);\n if (templateState) {\n nextState = new State();\n assign(nextState.j, templateState.j);\n nextState.jr.push.apply(nextState.jr, templateState.jr);\n nextState.jd = templateState.jd;\n nextState.t = templateState.t;\n } else {\n nextState = new State();\n }\n if (t) {\n // Ensure newly token is in the same groups as the old token\n if (groups) {\n if (nextState.t && typeof nextState.t === 'string') {\n const allFlags = assign(flagsForToken(nextState.t, groups), flags);\n addToGroups(t, allFlags, groups);\n } else if (flags) {\n addToGroups(t, flags, groups);\n }\n }\n nextState.t = t; // overwrite anything that was previously there\n }\n state.j[input] = nextState;\n return nextState;\n }\n};\n\n// Helper functions to improve minification (not exported outside linkifyjs module)\n\n/**\n * @template T\n * @param {State} state\n * @param {string | string[]} input\n * @param {Flags} [flags]\n * @param {Collections} [groups]\n */\nconst ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups);\n\n/**\n * @template T\n * @param {State} state\n * @param {RegExp} regexp\n * @param {T | State} [next]\n * @param {Flags} [flags]\n * @param {Collections} [groups]\n */\nconst tr = (state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups);\n\n/**\n * @template T\n * @param {State} state\n * @param {string | string[]} input\n * @param {T | State} [next]\n * @param {Flags} [flags]\n * @param {Collections} [groups]\n */\nconst ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups);\n\n/**\n * @template T\n * @param {State} state\n * @param {string} input\n * @param {T | State} [next]\n * @param {Collections} [groups]\n * @param {Flags} [flags]\n */\nconst tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups);\n\n/******************************************************************************\nText Tokens\nIdentifiers for token outputs from the regexp scanner\n******************************************************************************/\n\n// A valid web domain token\nconst WORD = 'WORD'; // only contains a-z\nconst UWORD = 'UWORD'; // contains letters other than a-z, used for IDN\nconst ASCIINUMERICAL = 'ASCIINUMERICAL'; // contains a-z, 0-9\nconst ALPHANUMERICAL = 'ALPHANUMERICAL'; // contains numbers and letters other than a-z, used for IDN\n\n// Special case of word\nconst LOCALHOST = 'LOCALHOST';\n\n// Valid top-level domain, special case of WORD (see tlds.js)\nconst TLD = 'TLD';\n\n// Valid IDN TLD, special case of UWORD (see tlds.js)\nconst UTLD = 'UTLD';\n\n// The scheme portion of a web URI protocol. Supported types include: `mailto`,\n// `file`, and user-defined custom protocols. Limited to schemes that contain\n// only letters\nconst SCHEME = 'SCHEME';\n\n// Similar to SCHEME, except makes distinction for schemes that must always be\n// followed by `://`, not just `:`. Supported types include `http`, `https`,\n// `ftp`, `ftps`\nconst SLASH_SCHEME = 'SLASH_SCHEME';\n\n// Any sequence of digits 0-9\nconst NUM = 'NUM';\n\n// Any number of consecutive whitespace characters that are not newline\nconst WS = 'WS';\n\n// New line (unix style)\nconst NL = 'NL'; // \\n\n\n// Opening/closing bracket classes\n// TODO: Rename OPEN -> LEFT and CLOSE -> RIGHT in v5 to fit with Unicode names\n// Also rename angle brackes to LESSTHAN and GREATER THAN\nconst OPENBRACE = 'OPENBRACE'; // {\nconst CLOSEBRACE = 'CLOSEBRACE'; // }\nconst OPENBRACKET = 'OPENBRACKET'; // [\nconst CLOSEBRACKET = 'CLOSEBRACKET'; // ]\nconst OPENPAREN = 'OPENPAREN'; // (\nconst CLOSEPAREN = 'CLOSEPAREN'; // )\nconst OPENANGLEBRACKET = 'OPENANGLEBRACKET'; // <\nconst CLOSEANGLEBRACKET = 'CLOSEANGLEBRACKET'; // >\nconst FULLWIDTHLEFTPAREN = 'FULLWIDTHLEFTPAREN'; // (\nconst FULLWIDTHRIGHTPAREN = 'FULLWIDTHRIGHTPAREN'; // )\nconst LEFTCORNERBRACKET = 'LEFTCORNERBRACKET'; // 「\nconst RIGHTCORNERBRACKET = 'RIGHTCORNERBRACKET'; // 」\nconst LEFTWHITECORNERBRACKET = 'LEFTWHITECORNERBRACKET'; // 『\nconst RIGHTWHITECORNERBRACKET = 'RIGHTWHITECORNERBRACKET'; // 』\nconst FULLWIDTHLESSTHAN = 'FULLWIDTHLESSTHAN'; // <\nconst FULLWIDTHGREATERTHAN = 'FULLWIDTHGREATERTHAN'; // >\n\n// Various symbols\nconst AMPERSAND = 'AMPERSAND'; // &\nconst APOSTROPHE = 'APOSTROPHE'; // '\nconst ASTERISK = 'ASTERISK'; // *\nconst AT = 'AT'; // @\nconst BACKSLASH = 'BACKSLASH'; // \\\nconst BACKTICK = 'BACKTICK'; // `\nconst CARET = 'CARET'; // ^\nconst COLON = 'COLON'; // :\nconst COMMA = 'COMMA'; // ,\nconst DOLLAR = 'DOLLAR'; // $\nconst DOT = 'DOT'; // .\nconst EQUALS = 'EQUALS'; // =\nconst EXCLAMATION = 'EXCLAMATION'; // !\nconst HYPHEN = 'HYPHEN'; // -\nconst PERCENT = 'PERCENT'; // %\nconst PIPE = 'PIPE'; // |\nconst PLUS = 'PLUS'; // +\nconst POUND = 'POUND'; // #\nconst QUERY = 'QUERY'; // ?\nconst QUOTE = 'QUOTE'; // \"\nconst FULLWIDTHMIDDLEDOT = 'FULLWIDTHMIDDLEDOT'; // ・\n\nconst SEMI = 'SEMI'; // ;\nconst SLASH = 'SLASH'; // /\nconst TILDE = 'TILDE'; // ~\nconst UNDERSCORE = 'UNDERSCORE'; // _\n\n// Emoji symbol\nconst EMOJI$1 = 'EMOJI';\n\n// Default token - anything that is not one of the above\nconst SYM = 'SYM';\n\nvar tk = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tWORD: WORD,\n\tUWORD: UWORD,\n\tASCIINUMERICAL: ASCIINUMERICAL,\n\tALPHANUMERICAL: ALPHANUMERICAL,\n\tLOCALHOST: LOCALHOST,\n\tTLD: TLD,\n\tUTLD: UTLD,\n\tSCHEME: SCHEME,\n\tSLASH_SCHEME: SLASH_SCHEME,\n\tNUM: NUM,\n\tWS: WS,\n\tNL: NL,\n\tOPENBRACE: OPENBRACE,\n\tCLOSEBRACE: CLOSEBRACE,\n\tOPENBRACKET: OPENBRACKET,\n\tCLOSEBRACKET: CLOSEBRACKET,\n\tOPENPAREN: OPENPAREN,\n\tCLOSEPAREN: CLOSEPAREN,\n\tOPENANGLEBRACKET: OPENANGLEBRACKET,\n\tCLOSEANGLEBRACKET: CLOSEANGLEBRACKET,\n\tFULLWIDTHLEFTPAREN: FULLWIDTHLEFTPAREN,\n\tFULLWIDTHRIGHTPAREN: FULLWIDTHRIGHTPAREN,\n\tLEFTCORNERBRACKET: LEFTCORNERBRACKET,\n\tRIGHTCORNERBRACKET: RIGHTCORNERBRACKET,\n\tLEFTWHITECORNERBRACKET: LEFTWHITECORNERBRACKET,\n\tRIGHTWHITECORNERBRACKET: RIGHTWHITECORNERBRACKET,\n\tFULLWIDTHLESSTHAN: FULLWIDTHLESSTHAN,\n\tFULLWIDTHGREATERTHAN: FULLWIDTHGREATERTHAN,\n\tAMPERSAND: AMPERSAND,\n\tAPOSTROPHE: APOSTROPHE,\n\tASTERISK: ASTERISK,\n\tAT: AT,\n\tBACKSLASH: BACKSLASH,\n\tBACKTICK: BACKTICK,\n\tCARET: CARET,\n\tCOLON: COLON,\n\tCOMMA: COMMA,\n\tDOLLAR: DOLLAR,\n\tDOT: DOT,\n\tEQUALS: EQUALS,\n\tEXCLAMATION: EXCLAMATION,\n\tHYPHEN: HYPHEN,\n\tPERCENT: PERCENT,\n\tPIPE: PIPE,\n\tPLUS: PLUS,\n\tPOUND: POUND,\n\tQUERY: QUERY,\n\tQUOTE: QUOTE,\n\tFULLWIDTHMIDDLEDOT: FULLWIDTHMIDDLEDOT,\n\tSEMI: SEMI,\n\tSLASH: SLASH,\n\tTILDE: TILDE,\n\tUNDERSCORE: UNDERSCORE,\n\tEMOJI: EMOJI$1,\n\tSYM: SYM\n});\n\n// Note that these two Unicode ones expand into a really big one with Babel\nconst ASCII_LETTER = /[a-z]/;\nconst LETTER = /\\p{L}/u; // Any Unicode character with letter data type\nconst EMOJI = /\\p{Emoji}/u; // Any Unicode emoji character\nconst EMOJI_VARIATION$1 = /\\ufe0f/;\nconst DIGIT = /\\d/;\nconst SPACE = /\\s/;\n\nvar regexp = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tASCII_LETTER: ASCII_LETTER,\n\tLETTER: LETTER,\n\tEMOJI: EMOJI,\n\tEMOJI_VARIATION: EMOJI_VARIATION$1,\n\tDIGIT: DIGIT,\n\tSPACE: SPACE\n});\n\n/**\n\tThe scanner provides an interface that takes a string of text as input, and\n\toutputs an array of tokens instances that can be used for easy URL parsing.\n*/\nconst CR = '\\r'; // carriage-return character\nconst LF = '\\n'; // line-feed character\nconst EMOJI_VARIATION = '\\ufe0f'; // Variation selector, follows heart and others\nconst EMOJI_JOINER = '\\u200d'; // zero-width joiner\nconst OBJECT_REPLACEMENT = '\\ufffc'; // whitespace placeholder that sometimes appears in rich text editors\n\nlet tlds = null,\n utlds = null; // don't change so only have to be computed once\n\n/**\n * Scanner output token:\n * - `t` is the token name (e.g., 'NUM', 'EMOJI', 'TLD')\n * - `v` is the value of the token (e.g., '123', '❤️', 'com')\n * - `s` is the start index of the token in the original string\n * - `e` is the end index of the token in the original string\n * @typedef {{t: string, v: string, s: number, e: number}} Token\n */\n\n/**\n * @template T\n * @typedef {{ [collection: string]: T[] }} Collections\n */\n\n/**\n * Initialize the scanner character-based state machine for the given start\n * state\n * @param {[string, boolean][]} customSchemes List of custom schemes, where each\n * item is a length-2 tuple with the first element set to the string scheme, and\n * the second element set to `true` if the `://` after the scheme is optional\n */\nfunction init$2(customSchemes = []) {\n // Frequently used states (name argument removed during minification)\n /** @type Collections */\n const groups = {}; // of tokens\n State.groups = groups;\n /** @type State */\n const Start = new State();\n if (tlds == null) {\n tlds = decodeTlds(encodedTlds);\n }\n if (utlds == null) {\n utlds = decodeTlds(encodedUtlds);\n }\n\n // States for special URL symbols that accept immediately after start\n tt(Start, \"'\", APOSTROPHE);\n tt(Start, '{', OPENBRACE);\n tt(Start, '}', CLOSEBRACE);\n tt(Start, '[', OPENBRACKET);\n tt(Start, ']', CLOSEBRACKET);\n tt(Start, '(', OPENPAREN);\n tt(Start, ')', CLOSEPAREN);\n tt(Start, '<', OPENANGLEBRACKET);\n tt(Start, '>', CLOSEANGLEBRACKET);\n tt(Start, '(', FULLWIDTHLEFTPAREN);\n tt(Start, ')', FULLWIDTHRIGHTPAREN);\n tt(Start, '「', LEFTCORNERBRACKET);\n tt(Start, '」', RIGHTCORNERBRACKET);\n tt(Start, '『', LEFTWHITECORNERBRACKET);\n tt(Start, '』', RIGHTWHITECORNERBRACKET);\n tt(Start, '<', FULLWIDTHLESSTHAN);\n tt(Start, '>', FULLWIDTHGREATERTHAN);\n tt(Start, '&', AMPERSAND);\n tt(Start, '*', ASTERISK);\n tt(Start, '@', AT);\n tt(Start, '`', BACKTICK);\n tt(Start, '^', CARET);\n tt(Start, ':', COLON);\n tt(Start, ',', COMMA);\n tt(Start, '$', DOLLAR);\n tt(Start, '.', DOT);\n tt(Start, '=', EQUALS);\n tt(Start, '!', EXCLAMATION);\n tt(Start, '-', HYPHEN);\n tt(Start, '%', PERCENT);\n tt(Start, '|', PIPE);\n tt(Start, '+', PLUS);\n tt(Start, '#', POUND);\n tt(Start, '?', QUERY);\n tt(Start, '\"', QUOTE);\n tt(Start, '/', SLASH);\n tt(Start, ';', SEMI);\n tt(Start, '~', TILDE);\n tt(Start, '_', UNDERSCORE);\n tt(Start, '\\\\', BACKSLASH);\n tt(Start, '・', FULLWIDTHMIDDLEDOT);\n const Num = tr(Start, DIGIT, NUM, {\n [numeric]: true\n });\n tr(Num, DIGIT, Num);\n const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, {\n [asciinumeric]: true\n });\n const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, {\n [alphanumeric]: true\n });\n\n // State which emits a word token\n const Word = tr(Start, ASCII_LETTER, WORD, {\n [ascii]: true\n });\n tr(Word, DIGIT, Asciinumeric);\n tr(Word, ASCII_LETTER, Word);\n tr(Asciinumeric, DIGIT, Asciinumeric);\n tr(Asciinumeric, ASCII_LETTER, Asciinumeric);\n\n // Same as previous, but specific to non-fsm.ascii alphabet words\n const UWord = tr(Start, LETTER, UWORD, {\n [alpha]: true\n });\n tr(UWord, ASCII_LETTER); // Non-accepting\n tr(UWord, DIGIT, Alphanumeric);\n tr(UWord, LETTER, UWord);\n tr(Alphanumeric, DIGIT, Alphanumeric);\n tr(Alphanumeric, ASCII_LETTER); // Non-accepting\n tr(Alphanumeric, LETTER, Alphanumeric); // Non-accepting\n\n // Whitespace jumps\n // Tokens of only non-newline whitespace are arbitrarily long\n // If any whitespace except newline, more whitespace!\n const Nl = tt(Start, LF, NL, {\n [whitespace]: true\n });\n const Cr = tt(Start, CR, WS, {\n [whitespace]: true\n });\n const Ws = tr(Start, SPACE, WS, {\n [whitespace]: true\n });\n tt(Start, OBJECT_REPLACEMENT, Ws);\n tt(Cr, LF, Nl); // \\r\\n\n tt(Cr, OBJECT_REPLACEMENT, Ws);\n tr(Cr, SPACE, Ws);\n tt(Ws, CR); // non-accepting state to avoid mixing whitespaces\n tt(Ws, LF); // non-accepting state to avoid mixing whitespaces\n tr(Ws, SPACE, Ws);\n tt(Ws, OBJECT_REPLACEMENT, Ws);\n\n // Emoji tokens. They are not grouped by the scanner except in cases where a\n // zero-width joiner is present\n const Emoji = tr(Start, EMOJI, EMOJI$1, {\n [emoji]: true\n });\n tt(Emoji, '#'); // no transition, emoji regex seems to match #\n tr(Emoji, EMOJI, Emoji);\n tt(Emoji, EMOJI_VARIATION, Emoji);\n // tt(Start, EMOJI_VARIATION, Emoji); // This one is sketchy\n\n const EmojiJoiner = tt(Emoji, EMOJI_JOINER);\n tt(EmojiJoiner, '#');\n tr(EmojiJoiner, EMOJI, Emoji);\n // tt(EmojiJoiner, EMOJI_VARIATION, Emoji); // also sketchy\n\n // Generates states for top-level domains\n // Note that this is most accurate when tlds are in alphabetical order\n const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]];\n const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]];\n for (let i = 0; i < tlds.length; i++) {\n fastts(Start, tlds[i], TLD, WORD, wordjr);\n }\n for (let i = 0; i < utlds.length; i++) {\n fastts(Start, utlds[i], UTLD, UWORD, uwordjr);\n }\n addToGroups(TLD, {\n tld: true,\n ascii: true\n }, groups);\n addToGroups(UTLD, {\n utld: true,\n alpha: true\n }, groups);\n\n // Collect the states generated by different protocols. NOTE: If any new TLDs\n // get added that are also protocols, set the token to be the same as the\n // protocol to ensure parsing works as expected.\n fastts(Start, 'file', SCHEME, WORD, wordjr);\n fastts(Start, 'mailto', SCHEME, WORD, wordjr);\n fastts(Start, 'http', SLASH_SCHEME, WORD, wordjr);\n fastts(Start, 'https', SLASH_SCHEME, WORD, wordjr);\n fastts(Start, 'ftp', SLASH_SCHEME, WORD, wordjr);\n fastts(Start, 'ftps', SLASH_SCHEME, WORD, wordjr);\n addToGroups(SCHEME, {\n scheme: true,\n ascii: true\n }, groups);\n addToGroups(SLASH_SCHEME, {\n slashscheme: true,\n ascii: true\n }, groups);\n\n // Register custom schemes. Assumes each scheme is asciinumeric with hyphens\n customSchemes = customSchemes.sort((a, b) => a[0] > b[0] ? 1 : -1);\n for (let i = 0; i < customSchemes.length; i++) {\n const sch = customSchemes[i][0];\n const optionalSlashSlash = customSchemes[i][1];\n const flags = optionalSlashSlash ? {\n [scheme]: true\n } : {\n [slashscheme]: true\n };\n if (sch.indexOf('-') >= 0) {\n flags[domain] = true;\n } else if (!ASCII_LETTER.test(sch)) {\n flags[numeric] = true; // numbers only\n } else if (DIGIT.test(sch)) {\n flags[asciinumeric] = true;\n } else {\n flags[ascii] = true;\n }\n ts(Start, sch, sch, flags);\n }\n\n // Localhost token\n ts(Start, 'localhost', LOCALHOST, {\n ascii: true\n });\n\n // Set default transition for start state (some symbol)\n Start.jd = new State(SYM);\n return {\n start: Start,\n tokens: assign({\n groups\n }, tk)\n };\n}\n\n/**\n\tGiven a string, returns an array of TOKEN instances representing the\n\tcomposition of that string.\n\n\t@method run\n\t@param {State} start scanner starting state\n\t@param {string} str input string to scan\n\t@return {Token[]} list of tokens, each with a type and value\n*/\nfunction run$1(start, str) {\n // State machine is not case sensitive, so input is tokenized in lowercased\n // form (still returns regular case). Uses selective `toLowerCase` because\n // lowercasing the entire string causes the length and character position to\n // vary in some non-English strings with V8-based runtimes.\n const iterable = stringToArray(str.replace(/[A-Z]/g, c => c.toLowerCase()));\n const charCount = iterable.length; // <= len if there are emojis, etc\n const tokens = []; // return value\n\n // cursor through the string itself, accounting for characters that have\n // width with length 2 such as emojis\n let cursor = 0;\n\n // Cursor through the array-representation of the string\n let charCursor = 0;\n\n // Tokenize the string\n while (charCursor < charCount) {\n let state = start;\n let nextState = null;\n let tokenLength = 0;\n let latestAccepting = null;\n let sinceAccepts = -1;\n let charsSinceAccepts = -1;\n while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) {\n state = nextState;\n\n // Keep track of the latest accepting state\n if (state.accepts()) {\n sinceAccepts = 0;\n charsSinceAccepts = 0;\n latestAccepting = state;\n } else if (sinceAccepts >= 0) {\n sinceAccepts += iterable[charCursor].length;\n charsSinceAccepts++;\n }\n tokenLength += iterable[charCursor].length;\n cursor += iterable[charCursor].length;\n charCursor++;\n }\n\n // Roll back to the latest accepting state\n cursor -= sinceAccepts;\n charCursor -= charsSinceAccepts;\n tokenLength -= sinceAccepts;\n\n // No more jumps, just make a new token from the last accepting one\n tokens.push({\n t: latestAccepting.t,\n // token type/name\n v: str.slice(cursor - tokenLength, cursor),\n // string value\n s: cursor - tokenLength,\n // start index\n e: cursor // end index (excluding)\n });\n }\n return tokens;\n}\n\n/**\n * Convert a String to an Array of characters, taking into account that some\n * characters like emojis take up two string indexes.\n *\n * Adapted from core-js (MIT license)\n * https://github.com/zloirock/core-js/blob/2d69cf5f99ab3ea3463c395df81e5a15b68f49d9/packages/core-js/internals/string-multibyte.js\n *\n * @function stringToArray\n * @param {string} str\n * @returns {string[]}\n */\nfunction stringToArray(str) {\n const result = [];\n const len = str.length;\n let index = 0;\n while (index < len) {\n let first = str.charCodeAt(index);\n let second;\n let char = first < 0xd800 || first > 0xdbff || index + 1 === len || (second = str.charCodeAt(index + 1)) < 0xdc00 || second > 0xdfff ? str[index] // single character\n : str.slice(index, index + 2); // two-index characters\n result.push(char);\n index += char.length;\n }\n return result;\n}\n\n/**\n * Fast version of ts function for when transition defaults are well known\n * @param {State} state\n * @param {string} input\n * @param {string} t\n * @param {string} defaultt\n * @param {[RegExp, State][]} jr\n * @returns {State}\n */\nfunction fastts(state, input, t, defaultt, jr) {\n let next;\n const len = input.length;\n for (let i = 0; i < len - 1; i++) {\n const char = input[i];\n if (state.j[char]) {\n next = state.j[char];\n } else {\n next = new State(defaultt);\n next.jr = jr.slice();\n state.j[char] = next;\n }\n state = next;\n }\n next = new State(t);\n next.jr = jr.slice();\n state.j[input[len - 1]] = next;\n return next;\n}\n\n/**\n * Converts a string of Top-Level Domain names encoded in update-tlds.js back\n * into a list of strings.\n * @param {str} encoded encoded TLDs string\n * @returns {str[]} original TLDs list\n */\nfunction decodeTlds(encoded) {\n const words = [];\n const stack = [];\n let i = 0;\n let digits = '0123456789';\n while (i < encoded.length) {\n let popDigitCount = 0;\n while (digits.indexOf(encoded[i + popDigitCount]) >= 0) {\n popDigitCount++; // encountered some digits, have to pop to go one level up trie\n }\n if (popDigitCount > 0) {\n words.push(stack.join('')); // whatever preceded the pop digits must be a word\n for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) {\n stack.pop();\n }\n i += popDigitCount;\n } else {\n stack.push(encoded[i]); // drop down a level into the trie\n i++;\n }\n }\n return words;\n}\n\n/**\n * An object where each key is a valid DOM Event Name such as `click` or `focus`\n * and each value is an event handler function.\n *\n * https://developer.mozilla.org/en-US/docs/Web/API/Element#events\n * @typedef {?{ [event: string]: Function }} EventListeners\n */\n\n/**\n * All formatted properties required to render a link, including `tagName`,\n * `attributes`, `content` and `eventListeners`.\n * @typedef {{ tagName: any, attributes: {[attr: string]: any}, content: string,\n * eventListeners: EventListeners }} IntermediateRepresentation\n */\n\n/**\n * Specify either an object described by the template type `O` or a function.\n *\n * The function takes a string value (usually the link's href attribute), the\n * link type (`'url'`, `'hashtag`', etc.) and an internal token representation\n * of the link. It should return an object of the template type `O`\n * @template O\n * @typedef {O | ((value: string, type: string, token: MultiToken) => O)} OptObj\n */\n\n/**\n * Specify either a function described by template type `F` or an object.\n *\n * Each key in the object should be a link type (`'url'`, `'hashtag`', etc.). Each\n * value should be a function with template type `F` that is called when the\n * corresponding link type is encountered.\n * @template F\n * @typedef {F | { [type: string]: F}} OptFn\n */\n\n/**\n * Specify either a value with template type `V`, a function that returns `V` or\n * an object where each value resolves to `V`.\n *\n * The function takes a string value (usually the link's href attribute), the\n * link type (`'url'`, `'hashtag`', etc.) and an internal token representation\n * of the link. It should return an object of the template type `V`\n *\n * For the object, each key should be a link type (`'url'`, `'hashtag`', etc.).\n * Each value should either have type `V` or a function that returns V. This\n * function similarly takes a string value and a token.\n *\n * Example valid types for `Opt`:\n *\n * ```js\n * 'hello'\n * (value, type, token) => 'world'\n * { url: 'hello', email: (value, token) => 'world'}\n * ```\n * @template V\n * @typedef {V | ((value: string, type: string, token: MultiToken) => V) | { [type: string]: V | ((value: string, token: MultiToken) => V) }} Opt\n */\n\n/**\n * See available options: https://linkify.js.org/docs/options.html\n * @typedef {{\n * \tdefaultProtocol?: string,\n * events?: OptObj,\n * \tformat?: Opt,\n * \tformatHref?: Opt,\n * \tnl2br?: boolean,\n * \ttagName?: Opt,\n * \ttarget?: Opt,\n * \trel?: Opt,\n * \tvalidate?: Opt,\n * \ttruncate?: Opt,\n * \tclassName?: Opt,\n * \tattributes?: OptObj<({ [attr: string]: any })>,\n * ignoreTags?: string[],\n * \trender?: OptFn<((ir: IntermediateRepresentation) => any)>\n * }} Opts\n */\n\n/**\n * @type Required\n */\nconst defaults = {\n defaultProtocol: 'http',\n events: null,\n format: noop,\n formatHref: noop,\n nl2br: false,\n tagName: 'a',\n target: null,\n rel: null,\n validate: true,\n truncate: Infinity,\n className: null,\n attributes: null,\n ignoreTags: [],\n render: null\n};\n\n/**\n * Utility class for linkify interfaces to apply specified\n * {@link Opts formatting and rendering options}.\n *\n * @param {Opts | Options} [opts] Option value overrides.\n * @param {(ir: IntermediateRepresentation) => any} [defaultRender] (For\n * internal use) default render function that determines how to generate an\n * HTML element based on a link token's derived tagName, attributes and HTML.\n * Similar to render option\n */\nfunction Options(opts, defaultRender = null) {\n let o = assign({}, defaults);\n if (opts) {\n o = assign(o, opts instanceof Options ? opts.o : opts);\n }\n\n // Ensure all ignored tags are uppercase\n const ignoredTags = o.ignoreTags;\n const uppercaseIgnoredTags = [];\n for (let i = 0; i < ignoredTags.length; i++) {\n uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase());\n }\n /** @protected */\n this.o = o;\n if (defaultRender) {\n this.defaultRender = defaultRender;\n }\n this.ignoreTags = uppercaseIgnoredTags;\n}\nOptions.prototype = {\n o: defaults,\n /**\n * @type string[]\n */\n ignoreTags: [],\n /**\n * @param {IntermediateRepresentation} ir\n * @returns {any}\n */\n defaultRender(ir) {\n return ir;\n },\n /**\n * Returns true or false based on whether a token should be displayed as a\n * link based on the user options.\n * @param {MultiToken} token\n * @returns {boolean}\n */\n check(token) {\n return this.get('validate', token.toString(), token);\n },\n // Private methods\n\n /**\n * Resolve an option's value based on the value of the option and the given\n * params. If operator and token are specified and the target option is\n * callable, automatically calls the function with the given argument.\n * @template {keyof Opts} K\n * @param {K} key Name of option to use\n * @param {string} [operator] will be passed to the target option if it's a\n * function. If not specified, RAW function value gets returned\n * @param {MultiToken} [token] The token from linkify.tokenize\n * @returns {Opts[K] | any}\n */\n get(key, operator, token) {\n const isCallable = operator != null;\n let option = this.o[key];\n if (!option) {\n return option;\n }\n if (typeof option === 'object') {\n option = token.t in option ? option[token.t] : defaults[key];\n if (typeof option === 'function' && isCallable) {\n option = option(operator, token);\n }\n } else if (typeof option === 'function' && isCallable) {\n option = option(operator, token.t, token);\n }\n return option;\n },\n /**\n * @template {keyof Opts} L\n * @param {L} key Name of options object to use\n * @param {string} [operator]\n * @param {MultiToken} [token]\n * @returns {Opts[L] | any}\n */\n getObj(key, operator, token) {\n let obj = this.o[key];\n if (typeof obj === 'function' && operator != null) {\n obj = obj(operator, token.t, token);\n }\n return obj;\n },\n /**\n * Convert the given token to a rendered element that may be added to the\n * calling-interface's DOM\n * @param {MultiToken} token Token to render to an HTML element\n * @returns {any} Render result; e.g., HTML string, DOM element, React\n * Component, etc.\n */\n render(token) {\n const ir = token.render(this); // intermediate representation\n const renderFn = this.get('render', null, token) || this.defaultRender;\n return renderFn(ir, token.t, token);\n }\n};\nfunction noop(val) {\n return val;\n}\n\nvar options = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tdefaults: defaults,\n\tOptions: Options,\n\tassign: assign\n});\n\n/******************************************************************************\n\tMulti-Tokens\n\tTokens composed of arrays of TextTokens\n******************************************************************************/\n\n/**\n * @param {string} value\n * @param {Token[]} tokens\n */\nfunction MultiToken(value, tokens) {\n this.t = 'token';\n this.v = value;\n this.tk = tokens;\n}\n\n/**\n * Abstract class used for manufacturing tokens of text tokens. That is rather\n * than the value for a token being a small string of text, it's value an array\n * of text tokens.\n *\n * Used for grouping together URLs, emails, hashtags, and other potential\n * creations.\n * @class MultiToken\n * @property {string} t\n * @property {string} v\n * @property {Token[]} tk\n * @abstract\n */\nMultiToken.prototype = {\n isLink: false,\n /**\n * Return the string this token represents.\n * @return {string}\n */\n toString() {\n return this.v;\n },\n /**\n * What should the value for this token be in the `href` HTML attribute?\n * Returns the `.toString` value by default.\n * @param {string} [scheme]\n * @return {string}\n */\n toHref(scheme) {\n return this.toString();\n },\n /**\n * @param {Options} options Formatting options\n * @returns {string}\n */\n toFormattedString(options) {\n const val = this.toString();\n const truncate = options.get('truncate', val, this);\n const formatted = options.get('format', val, this);\n return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + '…' : formatted;\n },\n /**\n *\n * @param {Options} options\n * @returns {string}\n */\n toFormattedHref(options) {\n return options.get('formatHref', this.toHref(options.get('defaultProtocol')), this);\n },\n /**\n * The start index of this token in the original input string\n * @returns {number}\n */\n startIndex() {\n return this.tk[0].s;\n },\n /**\n * The end index of this token in the original input string (up to this\n * index but not including it)\n * @returns {number}\n */\n endIndex() {\n return this.tk[this.tk.length - 1].e;\n },\n /**\n \tReturns an object of relevant values for this token, which includes keys\n \t* type - Kind of token ('url', 'email', etc.)\n \t* value - Original text\n \t* href - The value that should be added to the anchor tag's href\n \t\tattribute\n \t\t@method toObject\n \t@param {string} [protocol] `'http'` by default\n */\n toObject(protocol = defaults.defaultProtocol) {\n return {\n type: this.t,\n value: this.toString(),\n isLink: this.isLink,\n href: this.toHref(protocol),\n start: this.startIndex(),\n end: this.endIndex()\n };\n },\n /**\n *\n * @param {Options} options Formatting option\n */\n toFormattedObject(options) {\n return {\n type: this.t,\n value: this.toFormattedString(options),\n isLink: this.isLink,\n href: this.toFormattedHref(options),\n start: this.startIndex(),\n end: this.endIndex()\n };\n },\n /**\n * Whether this token should be rendered as a link according to the given options\n * @param {Options} options\n * @returns {boolean}\n */\n validate(options) {\n return options.get('validate', this.toString(), this);\n },\n /**\n * Return an object that represents how this link should be rendered.\n * @param {Options} options Formattinng options\n */\n render(options) {\n const token = this;\n const href = this.toHref(options.get('defaultProtocol'));\n const formattedHref = options.get('formatHref', href, this);\n const tagName = options.get('tagName', href, token);\n const content = this.toFormattedString(options);\n const attributes = {};\n const className = options.get('className', href, token);\n const target = options.get('target', href, token);\n const rel = options.get('rel', href, token);\n const attrs = options.getObj('attributes', href, token);\n const eventListeners = options.getObj('events', href, token);\n attributes.href = formattedHref;\n if (className) {\n attributes.class = className;\n }\n if (target) {\n attributes.target = target;\n }\n if (rel) {\n attributes.rel = rel;\n }\n if (attrs) {\n assign(attributes, attrs);\n }\n return {\n tagName,\n attributes,\n content,\n eventListeners\n };\n }\n};\n\n/**\n * Create a new token that can be emitted by the parser state machine\n * @param {string} type readable type of the token\n * @param {object} props properties to assign or override, including isLink = true or false\n * @returns {new (value: string, tokens: Token[]) => MultiToken} new token class\n */\nfunction createTokenClass(type, props) {\n class Token extends MultiToken {\n constructor(value, tokens) {\n super(value, tokens);\n this.t = type;\n }\n }\n for (const p in props) {\n Token.prototype[p] = props[p];\n }\n Token.t = type;\n return Token;\n}\n\n/**\n\tRepresents a list of tokens making up a valid email address\n*/\nconst Email = createTokenClass('email', {\n isLink: true,\n toHref() {\n return 'mailto:' + this.toString();\n }\n});\n\n/**\n\tRepresents some plain text\n*/\nconst Text = createTokenClass('text');\n\n/**\n\tMulti-linebreak token - represents a line break\n\t@class Nl\n*/\nconst Nl = createTokenClass('nl');\n\n/**\n\tRepresents a list of text tokens making up a valid URL\n\t@class Url\n*/\nconst Url = createTokenClass('url', {\n isLink: true,\n /**\n \tLowercases relevant parts of the domain and adds the protocol if\n \trequired. Note that this will not escape unsafe HTML characters in the\n \tURL.\n \t\t@param {string} [scheme] default scheme (e.g., 'https')\n \t@return {string} the full href\n */\n toHref(scheme = defaults.defaultProtocol) {\n // Check if already has a prefix scheme\n return this.hasProtocol() ? this.v : `${scheme}://${this.v}`;\n },\n /**\n * Check whether this URL token has a protocol\n * @return {boolean}\n */\n hasProtocol() {\n const tokens = this.tk;\n return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON;\n }\n});\n\nvar multi = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tMultiToken: MultiToken,\n\tBase: MultiToken,\n\tcreateTokenClass: createTokenClass,\n\tEmail: Email,\n\tText: Text,\n\tNl: Nl,\n\tUrl: Url\n});\n\n/**\n\tNot exactly parser, more like the second-stage scanner (although we can\n\ttheoretically hotswap the code here with a real parser in the future... but\n\tfor a little URL-finding utility abstract syntax trees may be a little\n\toverkill).\n\n\tURL format: http://en.wikipedia.org/wiki/URI_scheme\n\tEmail format: http://en.wikipedia.org/wiki/EmailAddress (links to RFC in\n\treference)\n\n\t@module linkify\n\t@submodule parser\n\t@main run\n*/\nconst makeState = arg => new State(arg);\n\n/**\n * Generate the parser multi token-based state machine\n * @param {{ groups: Collections }} tokens\n */\nfunction init$1({\n groups\n}) {\n // Types of characters the URL can definitely end in\n const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]);\n\n // Types of tokens that can follow a URL and be part of the query string\n // but cannot be the very last characters\n // Characters that cannot appear in the URL at all should be excluded\n const qsNonAccepting = [COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN];\n\n // For addresses without the mailto prefix\n // Tokens allowed in the localpart of the email\n const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE];\n\n // The universal starting state.\n /**\n * @type State\n */\n const Start = makeState();\n const Localpart = tt(Start, TILDE); // Local part of the email address\n ta(Localpart, localpartAccepting, Localpart);\n ta(Localpart, groups.domain, Localpart);\n const Domain = makeState(),\n Scheme = makeState(),\n SlashScheme = makeState();\n ta(Start, groups.domain, Domain); // parsed string ends with a potential domain name (A)\n ta(Start, groups.scheme, Scheme); // e.g., 'mailto'\n ta(Start, groups.slashscheme, SlashScheme); // e.g., 'http'\n\n ta(Domain, localpartAccepting, Localpart);\n ta(Domain, groups.domain, Domain);\n const LocalpartAt = tt(Domain, AT); // Local part of the email address plus @\n\n tt(Localpart, AT, LocalpartAt); // close to an email address now\n\n // Local part of an email address can be e.g. 'http' or 'mailto'\n tt(Scheme, AT, LocalpartAt);\n tt(SlashScheme, AT, LocalpartAt);\n const LocalpartDot = tt(Localpart, DOT); // Local part of the email address plus '.' (localpart cannot end in .)\n ta(LocalpartDot, localpartAccepting, Localpart);\n ta(LocalpartDot, groups.domain, Localpart);\n const EmailDomain = makeState();\n ta(LocalpartAt, groups.domain, EmailDomain); // parsed string starts with local email info + @ with a potential domain name\n ta(EmailDomain, groups.domain, EmailDomain);\n const EmailDomainDot = tt(EmailDomain, DOT); // domain followed by DOT\n ta(EmailDomainDot, groups.domain, EmailDomain);\n const Email$1 = makeState(Email); // Possible email address (could have more tlds)\n ta(EmailDomainDot, groups.tld, Email$1);\n ta(EmailDomainDot, groups.utld, Email$1);\n tt(LocalpartAt, LOCALHOST, Email$1);\n\n // Hyphen can jump back to a domain name\n const EmailDomainHyphen = tt(EmailDomain, HYPHEN); // parsed string starts with local email info + @ with a potential domain name\n tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen);\n ta(EmailDomainHyphen, groups.domain, EmailDomain);\n ta(Email$1, groups.domain, EmailDomain);\n tt(Email$1, DOT, EmailDomainDot);\n tt(Email$1, HYPHEN, EmailDomainHyphen);\n\n // Final possible email states\n const EmailColon = tt(Email$1, COLON); // URL followed by colon (potential port number here)\n /*const EmailColonPort = */\n ta(EmailColon, groups.numeric, Email); // URL followed by colon and port number\n\n // Account for dots and hyphens. Hyphens are usually parts of domain names\n // (but not TLDs)\n const DomainHyphen = tt(Domain, HYPHEN); // domain followed by hyphen\n const DomainDot = tt(Domain, DOT); // domain followed by DOT\n tt(DomainHyphen, HYPHEN, DomainHyphen);\n ta(DomainHyphen, groups.domain, Domain);\n ta(DomainDot, localpartAccepting, Localpart);\n ta(DomainDot, groups.domain, Domain);\n const DomainDotTld = makeState(Url); // Simplest possible URL with no query string\n ta(DomainDot, groups.tld, DomainDotTld);\n ta(DomainDot, groups.utld, DomainDotTld);\n ta(DomainDotTld, groups.domain, Domain);\n ta(DomainDotTld, localpartAccepting, Localpart);\n tt(DomainDotTld, DOT, DomainDot);\n tt(DomainDotTld, HYPHEN, DomainHyphen);\n tt(DomainDotTld, AT, LocalpartAt);\n const DomainDotTldColon = tt(DomainDotTld, COLON); // URL followed by colon (potential port number here)\n const DomainDotTldColonPort = makeState(Url); // TLD followed by a port number\n ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort);\n\n // Long URL with optional port and maybe query string\n const Url$1 = makeState(Url);\n\n // URL with extra symbols at the end, followed by an opening bracket\n const UrlNonaccept = makeState(); // URL followed by some symbols (will not be part of the final URL)\n\n // Query strings\n ta(Url$1, qsAccepting, Url$1);\n ta(Url$1, qsNonAccepting, UrlNonaccept);\n ta(UrlNonaccept, qsAccepting, Url$1);\n ta(UrlNonaccept, qsNonAccepting, UrlNonaccept);\n\n // Become real URLs after `SLASH` or `COLON NUM SLASH`\n // Here works with or without scheme:// prefix\n tt(DomainDotTld, SLASH, Url$1);\n tt(DomainDotTldColonPort, SLASH, Url$1);\n\n // Note that domains that begin with schemes are treated slighly differently\n const SchemeColon = tt(Scheme, COLON); // e.g., 'mailto:'\n const SlashSchemeColon = tt(SlashScheme, COLON); // e.g., 'http:'\n const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH); // e.g., 'http:/'\n\n const UriPrefix = tt(SlashSchemeColonSlash, SLASH); // e.g., 'http://'\n\n // Scheme states can transition to domain states\n ta(Scheme, groups.domain, Domain);\n tt(Scheme, DOT, DomainDot);\n tt(Scheme, HYPHEN, DomainHyphen);\n ta(SlashScheme, groups.domain, Domain);\n tt(SlashScheme, DOT, DomainDot);\n tt(SlashScheme, HYPHEN, DomainHyphen);\n\n // Force URL with scheme prefix followed by anything sane\n ta(SchemeColon, groups.domain, Url$1);\n tt(SchemeColon, SLASH, Url$1);\n tt(SchemeColon, QUERY, Url$1);\n ta(UriPrefix, groups.domain, Url$1);\n ta(UriPrefix, qsAccepting, Url$1);\n tt(UriPrefix, SLASH, Url$1);\n const bracketPairs = [[OPENBRACE, CLOSEBRACE],\n // {}\n [OPENBRACKET, CLOSEBRACKET],\n // []\n [OPENPAREN, CLOSEPAREN],\n // ()\n [OPENANGLEBRACKET, CLOSEANGLEBRACKET],\n // <>\n [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN],\n // ()\n [LEFTCORNERBRACKET, RIGHTCORNERBRACKET],\n // 「」\n [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET],\n // 『』\n [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN] // <>\n ];\n for (let i = 0; i < bracketPairs.length; i++) {\n const [OPEN, CLOSE] = bracketPairs[i];\n const UrlOpen = tt(Url$1, OPEN); // URL followed by open bracket\n\n // Continue not accepting for open brackets\n tt(UrlNonaccept, OPEN, UrlOpen);\n\n // Closing bracket component. This character WILL be included in the URL\n tt(UrlOpen, CLOSE, Url$1);\n\n // URL that beings with an opening bracket, followed by a symbols.\n // Note that the final state can still be `UrlOpen` (if the URL has a\n // single opening bracket for some reason).\n const UrlOpenQ = makeState(Url);\n ta(UrlOpen, qsAccepting, UrlOpenQ);\n const UrlOpenSyms = makeState(); // UrlOpen followed by some symbols it cannot end it\n ta(UrlOpen, qsNonAccepting);\n\n // URL that begins with an opening bracket, followed by some symbols\n ta(UrlOpenQ, qsAccepting, UrlOpenQ);\n ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms);\n ta(UrlOpenSyms, qsAccepting, UrlOpenQ);\n ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms);\n\n // Close brace/bracket to become regular URL\n tt(UrlOpenQ, CLOSE, Url$1);\n tt(UrlOpenSyms, CLOSE, Url$1);\n }\n tt(Start, LOCALHOST, DomainDotTld); // localhost is a valid URL state\n tt(Start, NL, Nl); // single new line\n\n return {\n start: Start,\n tokens: tk\n };\n}\n\n/**\n * Run the parser state machine on a list of scanned string-based tokens to\n * create a list of multi tokens, each of which represents a URL, email address,\n * plain text, etc.\n *\n * @param {State} start parser start state\n * @param {string} input the original input used to generate the given tokens\n * @param {Token[]} tokens list of scanned tokens\n * @returns {MultiToken[]}\n */\nfunction run(start, input, tokens) {\n let len = tokens.length;\n let cursor = 0;\n let multis = [];\n let textTokens = [];\n while (cursor < len) {\n let state = start;\n let secondState = null;\n let nextState = null;\n let multiLength = 0;\n let latestAccepting = null;\n let sinceAccepts = -1;\n while (cursor < len && !(secondState = state.go(tokens[cursor].t))) {\n // Starting tokens with nowhere to jump to.\n // Consider these to be just plain text\n textTokens.push(tokens[cursor++]);\n }\n while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) {\n // Get the next state\n secondState = null;\n state = nextState;\n\n // Keep track of the latest accepting state\n if (state.accepts()) {\n sinceAccepts = 0;\n latestAccepting = state;\n } else if (sinceAccepts >= 0) {\n sinceAccepts++;\n }\n cursor++;\n multiLength++;\n }\n if (sinceAccepts < 0) {\n // No accepting state was found, part of a regular text token add\n // the first text token to the text tokens array and try again from\n // the next\n cursor -= multiLength;\n if (cursor < len) {\n textTokens.push(tokens[cursor]);\n cursor++;\n }\n } else {\n // Accepting state!\n // First close off the textTokens (if available)\n if (textTokens.length > 0) {\n multis.push(initMultiToken(Text, input, textTokens));\n textTokens = [];\n }\n\n // Roll back to the latest accepting state\n cursor -= sinceAccepts;\n multiLength -= sinceAccepts;\n\n // Create a new multitoken\n const Multi = latestAccepting.t;\n const subtokens = tokens.slice(cursor - multiLength, cursor);\n multis.push(initMultiToken(Multi, input, subtokens));\n }\n }\n\n // Finally close off the textTokens (if available)\n if (textTokens.length > 0) {\n multis.push(initMultiToken(Text, input, textTokens));\n }\n return multis;\n}\n\n/**\n * Utility function for instantiating a new multitoken with all the relevant\n * fields during parsing.\n * @param {new (value: string, tokens: Token[]) => MultiToken} Multi class to instantiate\n * @param {string} input original input string\n * @param {Token[]} tokens consecutive tokens scanned from input string\n * @returns {MultiToken}\n */\nfunction initMultiToken(Multi, input, tokens) {\n const startIdx = tokens[0].s;\n const endIdx = tokens[tokens.length - 1].e;\n const value = input.slice(startIdx, endIdx);\n return new Multi(value, tokens);\n}\n\nconst warn = typeof console !== 'undefined' && console && console.warn || (() => {});\nconst warnAdvice = 'until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.';\n\n// Side-effect initialization state\nconst INIT = {\n scanner: null,\n parser: null,\n tokenQueue: [],\n pluginQueue: [],\n customSchemes: [],\n initialized: false\n};\n\n/**\n * @typedef {{\n * \tstart: State,\n * \ttokens: { groups: Collections } & typeof tk\n * }} ScannerInit\n */\n\n/**\n * @typedef {{\n * \tstart: State,\n * \ttokens: typeof multi\n * }} ParserInit\n */\n\n/**\n * @typedef {(arg: { scanner: ScannerInit }) => void} TokenPlugin\n */\n\n/**\n * @typedef {(arg: { scanner: ScannerInit, parser: ParserInit }) => void} Plugin\n */\n\n/**\n * De-register all plugins and reset the internal state-machine. Used for\n * testing; not required in practice.\n * @private\n */\nfunction reset() {\n State.groups = {};\n INIT.scanner = null;\n INIT.parser = null;\n INIT.tokenQueue = [];\n INIT.pluginQueue = [];\n INIT.customSchemes = [];\n INIT.initialized = false;\n return INIT;\n}\n\n/**\n * Register a token plugin to allow the scanner to recognize additional token\n * types before the parser state machine is constructed from the results.\n * @param {string} name of plugin to register\n * @param {TokenPlugin} plugin function that accepts the scanner state machine\n * and available scanner tokens and collections and extends the state machine to\n * recognize additional tokens or groups.\n */\nfunction registerTokenPlugin(name, plugin) {\n if (typeof plugin !== 'function') {\n throw new Error(`linkifyjs: Invalid token plugin ${plugin} (expects function)`);\n }\n for (let i = 0; i < INIT.tokenQueue.length; i++) {\n if (name === INIT.tokenQueue[i][0]) {\n warn(`linkifyjs: token plugin \"${name}\" already registered - will be overwritten`);\n INIT.tokenQueue[i] = [name, plugin];\n return;\n }\n }\n INIT.tokenQueue.push([name, plugin]);\n if (INIT.initialized) {\n warn(`linkifyjs: already initialized - will not register token plugin \"${name}\" ${warnAdvice}`);\n }\n}\n\n/**\n * Register a linkify plugin\n * @param {string} name of plugin to register\n * @param {Plugin} plugin function that accepts the parser state machine and\n * extends the parser to recognize additional link types\n */\nfunction registerPlugin(name, plugin) {\n if (typeof plugin !== 'function') {\n throw new Error(`linkifyjs: Invalid plugin ${plugin} (expects function)`);\n }\n for (let i = 0; i < INIT.pluginQueue.length; i++) {\n if (name === INIT.pluginQueue[i][0]) {\n warn(`linkifyjs: plugin \"${name}\" already registered - will be overwritten`);\n INIT.pluginQueue[i] = [name, plugin];\n return;\n }\n }\n INIT.pluginQueue.push([name, plugin]);\n if (INIT.initialized) {\n warn(`linkifyjs: already initialized - will not register plugin \"${name}\" ${warnAdvice}`);\n }\n}\n\n/**\n * Detect URLs with the following additional protocol. Anything with format\n * \"protocol://...\" will be considered a link. If `optionalSlashSlash` is set to\n * `true`, anything with format \"protocol:...\" will be considered a link.\n * @param {string} scheme\n * @param {boolean} [optionalSlashSlash]\n */\nfunction registerCustomProtocol(scheme, optionalSlashSlash = false) {\n if (INIT.initialized) {\n warn(`linkifyjs: already initialized - will not register custom scheme \"${scheme}\" ${warnAdvice}`);\n }\n if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme)) {\n throw new Error(`linkifyjs: incorrect scheme format.\n1. Must only contain digits, lowercase ASCII letters or \"-\"\n2. Cannot start or end with \"-\"\n3. \"-\" cannot repeat`);\n }\n INIT.customSchemes.push([scheme, optionalSlashSlash]);\n}\n\n/**\n * Initialize the linkify state machine. Called automatically the first time\n * linkify is called on a string, but may be called manually as well.\n */\nfunction init() {\n // Initialize scanner state machine and plugins\n INIT.scanner = init$2(INIT.customSchemes);\n for (let i = 0; i < INIT.tokenQueue.length; i++) {\n INIT.tokenQueue[i][1]({\n scanner: INIT.scanner\n });\n }\n\n // Initialize parser state machine and plugins\n INIT.parser = init$1(INIT.scanner.tokens);\n for (let i = 0; i < INIT.pluginQueue.length; i++) {\n INIT.pluginQueue[i][1]({\n scanner: INIT.scanner,\n parser: INIT.parser\n });\n }\n INIT.initialized = true;\n return INIT;\n}\n\n/**\n * Parse a string into tokens that represent linkable and non-linkable sub-components\n * @param {string} str\n * @return {MultiToken[]} tokens\n */\nfunction tokenize(str) {\n if (!INIT.initialized) {\n init();\n }\n return run(INIT.parser.start, str, run$1(INIT.scanner.start, str));\n}\ntokenize.scan = run$1; // for testing\n\n/**\n * Find a list of linkable items in the given string.\n * @param {string} str string to find links in\n * @param {string | Opts} [type] either formatting options or specific type of\n * links to find, e.g., 'url' or 'email'\n * @param {Opts} [opts] formatting options for final output. Cannot be specified\n * if opts already provided in `type` argument\n */\nfunction find(str, type = null, opts = null) {\n if (type && typeof type === 'object') {\n if (opts) {\n throw Error(`linkifyjs: Invalid link type ${type}; must be a string`);\n }\n opts = type;\n type = null;\n }\n const options = new Options(opts);\n const tokens = tokenize(str);\n const filtered = [];\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n if (token.isLink && (!type || token.t === type) && options.check(token)) {\n filtered.push(token.toFormattedObject(options));\n }\n }\n return filtered;\n}\n\n/**\n * Is the given string valid linkable text of some sort. Note that this does not\n * trim the text for you.\n *\n * Optionally pass in a second `type` param, which is the type of link to test\n * for.\n *\n * For example,\n *\n * linkify.test(str, 'email');\n *\n * Returns `true` if str is a valid email.\n * @param {string} str string to test for links\n * @param {string} [type] optional specific link type to look for\n * @returns boolean true/false\n */\nfunction test(str, type = null) {\n const tokens = tokenize(str);\n return tokens.length === 1 && tokens[0].isLink && (!type || tokens[0].t === type);\n}\n\nexport { MultiToken, Options, State, createTokenClass, find, init, multi, options, regexp, registerCustomProtocol, registerPlugin, registerTokenPlugin, reset, stringToArray, test, multi as text, tokenize };\n","import { combineTransactionSteps, getChangedRanges, findChildrenInRange, getMarksBetween, getAttributes, Mark, mergeAttributes, markPasteRule } from '@tiptap/core';\nimport { tokenize, find, registerCustomProtocol, reset } from 'linkifyjs';\nimport { Plugin, PluginKey } from '@tiptap/pm/state';\n\n/**\n * Check if the provided tokens form a valid link structure, which can either be a single link token\n * or a link token surrounded by parentheses or square brackets.\n *\n * This ensures that only complete and valid text is hyperlinked, preventing cases where a valid\n * top-level domain (TLD) is immediately followed by an invalid character, like a number. For\n * example, with the `find` method from Linkify, entering `example.com1` would result in\n * `example.com` being linked and the trailing `1` left as plain text. By using the `tokenize`\n * method, we can perform more comprehensive validation on the input text.\n */\nfunction isValidLinkStructure(tokens) {\n if (tokens.length === 1) {\n return tokens[0].isLink;\n }\n if (tokens.length === 3 && tokens[1].isLink) {\n return ['()', '[]'].includes(tokens[0].value + tokens[2].value);\n }\n return false;\n}\n/**\n * This plugin allows you to automatically add links to your editor.\n * @param options The plugin options\n * @returns The plugin instance\n */\nfunction autolink(options) {\n return new Plugin({\n key: new PluginKey('autolink'),\n appendTransaction: (transactions, oldState, newState) => {\n /**\n * Does the transaction change the document?\n */\n const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc);\n /**\n * Prevent autolink if the transaction is not a document change or if the transaction has the meta `preventAutolink`.\n */\n const preventAutolink = transactions.some(transaction => transaction.getMeta('preventAutolink'));\n /**\n * Prevent autolink if the transaction is not a document change\n * or if the transaction has the meta `preventAutolink`.\n */\n if (!docChanges || preventAutolink) {\n return;\n }\n const { tr } = newState;\n const transform = combineTransactionSteps(oldState.doc, [...transactions]);\n const changes = getChangedRanges(transform);\n changes.forEach(({ newRange }) => {\n // Now let’s see if we can add new links.\n const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, node => node.isTextblock);\n let textBlock;\n let textBeforeWhitespace;\n if (nodesInChangedRanges.length > 1) {\n // Grab the first node within the changed ranges (ex. the first of two paragraphs when hitting enter).\n textBlock = nodesInChangedRanges[0];\n textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, textBlock.pos + textBlock.node.nodeSize, undefined, ' ');\n }\n else if (nodesInChangedRanges.length\n // We want to make sure to include the block seperator argument to treat hard breaks like spaces.\n && newState.doc.textBetween(newRange.from, newRange.to, ' ', ' ').endsWith(' ')) {\n textBlock = nodesInChangedRanges[0];\n textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, undefined, ' ');\n }\n if (textBlock && textBeforeWhitespace) {\n const wordsBeforeWhitespace = textBeforeWhitespace.split(' ').filter(s => s !== '');\n if (wordsBeforeWhitespace.length <= 0) {\n return false;\n }\n const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1];\n const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace);\n if (!lastWordBeforeSpace) {\n return false;\n }\n const linksBeforeSpace = tokenize(lastWordBeforeSpace).map(t => t.toObject(options.defaultProtocol));\n if (!isValidLinkStructure(linksBeforeSpace)) {\n return false;\n }\n linksBeforeSpace\n .filter(link => link.isLink)\n // Calculate link position.\n .map(link => ({\n ...link,\n from: lastWordAndBlockOffset + link.start + 1,\n to: lastWordAndBlockOffset + link.end + 1,\n }))\n // ignore link inside code mark\n .filter(link => {\n if (!newState.schema.marks.code) {\n return true;\n }\n return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code);\n })\n // validate link\n .filter(link => options.validate(link.value))\n // check whether should autolink\n .filter(link => options.shouldAutoLink(link.value))\n // Add link mark.\n .forEach(link => {\n if (getMarksBetween(link.from, link.to, newState.doc).some(item => item.mark.type === options.type)) {\n return;\n }\n tr.addMark(link.from, link.to, options.type.create({\n href: link.href,\n }));\n });\n }\n });\n if (!tr.steps.length) {\n return;\n }\n return tr;\n },\n });\n}\n\nfunction clickHandler(options) {\n return new Plugin({\n key: new PluginKey('handleClickLink'),\n props: {\n handleClick: (view, pos, event) => {\n var _a, _b;\n if (event.button !== 0) {\n return false;\n }\n if (!view.editable) {\n return false;\n }\n let a = event.target;\n const els = [];\n while (a.nodeName !== 'DIV') {\n els.push(a);\n a = a.parentNode;\n }\n if (!els.find(value => value.nodeName === 'A')) {\n return false;\n }\n const attrs = getAttributes(view.state, options.type.name);\n const link = event.target;\n const href = (_a = link === null || link === void 0 ? void 0 : link.href) !== null && _a !== void 0 ? _a : attrs.href;\n const target = (_b = link === null || link === void 0 ? void 0 : link.target) !== null && _b !== void 0 ? _b : attrs.target;\n if (link && href) {\n window.open(href, target);\n return true;\n }\n return false;\n },\n },\n });\n}\n\nfunction pasteHandler(options) {\n return new Plugin({\n key: new PluginKey('handlePasteLink'),\n props: {\n handlePaste: (view, event, slice) => {\n const { state } = view;\n const { selection } = state;\n const { empty } = selection;\n if (empty) {\n return false;\n }\n let textContent = '';\n slice.content.forEach(node => {\n textContent += node.textContent;\n });\n const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find(item => item.isLink && item.value === textContent);\n if (!textContent || !link) {\n return false;\n }\n return options.editor.commands.setMark(options.type, {\n href: link.href,\n });\n },\n },\n });\n}\n\nconst pasteRegex = /https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z]{2,}\\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi;\n// From DOMPurify\n// https://github.com/cure53/DOMPurify/blob/main/src/regexp.js\n// eslint-disable-next-line no-control-regex\nconst ATTR_WHITESPACE = /[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g;\nfunction isAllowedUri(uri, protocols) {\n const allowedProtocols = [\n 'http',\n 'https',\n 'ftp',\n 'ftps',\n 'mailto',\n 'tel',\n 'callto',\n 'sms',\n 'cid',\n 'xmpp',\n ];\n if (protocols) {\n protocols.forEach(protocol => {\n const nextProtocol = typeof protocol === 'string' ? protocol : protocol.scheme;\n if (nextProtocol) {\n allowedProtocols.push(nextProtocol);\n }\n });\n }\n return (!uri\n || uri\n .replace(ATTR_WHITESPACE, '')\n .match(new RegExp(\n // eslint-disable-next-line no-useless-escape\n `^(?:(?:${allowedProtocols.join('|')}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`, 'i')));\n}\n/**\n * This extension allows you to create links.\n * @see https://www.tiptap.dev/api/marks/link\n */\nconst Link = Mark.create({\n name: 'link',\n priority: 1000,\n keepOnSplit: false,\n exitable: true,\n onCreate() {\n if (this.options.validate && !this.options.shouldAutoLink) {\n // Copy the validate function to the shouldAutoLink option\n this.options.shouldAutoLink = this.options.validate;\n console.warn('The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.');\n }\n this.options.protocols.forEach(protocol => {\n if (typeof protocol === 'string') {\n registerCustomProtocol(protocol);\n return;\n }\n registerCustomProtocol(protocol.scheme, protocol.optionalSlashes);\n });\n },\n onDestroy() {\n reset();\n },\n inclusive() {\n return this.options.autolink;\n },\n addOptions() {\n return {\n openOnClick: true,\n linkOnPaste: true,\n autolink: true,\n protocols: [],\n defaultProtocol: 'http',\n HTMLAttributes: {\n target: '_blank',\n rel: 'noopener noreferrer nofollow',\n class: null,\n },\n isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols),\n validate: url => !!url,\n shouldAutoLink: url => !!url,\n };\n },\n addAttributes() {\n return {\n href: {\n default: null,\n parseHTML(element) {\n return element.getAttribute('href');\n },\n },\n target: {\n default: this.options.HTMLAttributes.target,\n },\n rel: {\n default: this.options.HTMLAttributes.rel,\n },\n class: {\n default: this.options.HTMLAttributes.class,\n },\n };\n },\n parseHTML() {\n return [\n {\n tag: 'a[href]',\n getAttrs: dom => {\n const href = dom.getAttribute('href');\n // prevent XSS attacks\n if (!href\n || !this.options.isAllowedUri(href, {\n defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n protocols: this.options.protocols,\n defaultProtocol: this.options.defaultProtocol,\n })) {\n return false;\n }\n return null;\n },\n },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n // prevent XSS attacks\n if (!this.options.isAllowedUri(HTMLAttributes.href, {\n defaultValidate: href => !!isAllowedUri(href, this.options.protocols),\n protocols: this.options.protocols,\n defaultProtocol: this.options.defaultProtocol,\n })) {\n // strip out the href\n return [\n 'a',\n mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: '' }),\n 0,\n ];\n }\n return ['a', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setLink: attributes => ({ chain }) => {\n const { href } = attributes;\n if (!this.options.isAllowedUri(href, {\n defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n protocols: this.options.protocols,\n defaultProtocol: this.options.defaultProtocol,\n })) {\n return false;\n }\n return chain().setMark(this.name, attributes).setMeta('preventAutolink', true).run();\n },\n toggleLink: attributes => ({ chain }) => {\n const { href } = attributes;\n if (!this.options.isAllowedUri(href, {\n defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n protocols: this.options.protocols,\n defaultProtocol: this.options.defaultProtocol,\n })) {\n return false;\n }\n return chain()\n .toggleMark(this.name, attributes, { extendEmptyMarkRange: true })\n .setMeta('preventAutolink', true)\n .run();\n },\n unsetLink: () => ({ chain }) => {\n return chain()\n .unsetMark(this.name, { extendEmptyMarkRange: true })\n .setMeta('preventAutolink', true)\n .run();\n },\n };\n },\n addPasteRules() {\n return [\n markPasteRule({\n find: text => {\n const foundLinks = [];\n if (text) {\n const { protocols, defaultProtocol } = this.options;\n const links = find(text).filter(item => item.isLink\n && this.options.isAllowedUri(item.value, {\n defaultValidate: href => !!isAllowedUri(href, protocols),\n protocols,\n defaultProtocol,\n }));\n if (links.length) {\n links.forEach(link => foundLinks.push({\n text: link.value,\n data: {\n href: link.href,\n },\n index: link.start,\n }));\n }\n }\n return foundLinks;\n },\n type: this.type,\n getAttributes: match => {\n var _a;\n return {\n href: (_a = match.data) === null || _a === void 0 ? void 0 : _a.href,\n };\n },\n }),\n ];\n },\n addProseMirrorPlugins() {\n const plugins = [];\n const { protocols, defaultProtocol } = this.options;\n if (this.options.autolink) {\n plugins.push(autolink({\n type: this.type,\n defaultProtocol: this.options.defaultProtocol,\n validate: url => this.options.isAllowedUri(url, {\n defaultValidate: href => !!isAllowedUri(href, protocols),\n protocols,\n defaultProtocol,\n }),\n shouldAutoLink: this.options.shouldAutoLink,\n }));\n }\n if (this.options.openOnClick === true) {\n plugins.push(clickHandler({\n type: this.type,\n }));\n }\n if (this.options.linkOnPaste) {\n plugins.push(pasteHandler({\n editor: this.editor,\n defaultProtocol: this.options.defaultProtocol,\n type: this.type,\n }));\n }\n return plugins;\n },\n});\n\nexport { Link, Link as default, isAllowedUri, pasteRegex };\n//# sourceMappingURL=index.js.map\n","'use client';\nvar classes = {\"root\":\"m_dd3f7539\",\"typographyStylesProvider\":\"m_d37966d9\",\"content\":\"m_c2204cc2\",\"linkEditorDropdown\":\"m_8a991b4f\",\"control\":\"m_c2207da6\",\"controlIcon\":\"m_9cdfeb3f\",\"controlsGroup\":\"m_2ab47ef2\",\"linkEditor\":\"m_b67b711e\",\"linkEditorInput\":\"m_296cf94c\",\"linkEditorExternalControl\":\"m_cfef614\",\"linkEditorSave\":\"m_3b28e7bb\",\"toolbar\":\"m_4574a3c4\",\"taskList\":\"m_8b44009a\"};\n\nexport { classes as default };\n//# sourceMappingURL=RichTextEditor.module.css.mjs.map\n","'use client';\nconst DEFAULT_LABELS = {\n // Controls labels\n linkControlLabel: \"Link\",\n colorPickerControlLabel: \"Text color\",\n highlightControlLabel: \"Highlight text\",\n colorControlLabel: (color) => `Set text color ${color}`,\n boldControlLabel: \"Bold\",\n italicControlLabel: \"Italic\",\n underlineControlLabel: \"Underline\",\n strikeControlLabel: \"Strikethrough\",\n clearFormattingControlLabel: \"Clear formatting\",\n unlinkControlLabel: \"Remove link\",\n bulletListControlLabel: \"Bullet list\",\n orderedListControlLabel: \"Ordered list\",\n h1ControlLabel: \"Heading 1\",\n h2ControlLabel: \"Heading 2\",\n h3ControlLabel: \"Heading 3\",\n h4ControlLabel: \"Heading 4\",\n h5ControlLabel: \"Heading 5\",\n h6ControlLabel: \"Heading 6\",\n blockquoteControlLabel: \"Blockquote\",\n alignLeftControlLabel: \"Align text: left\",\n alignCenterControlLabel: \"Align text: center\",\n alignRightControlLabel: \"Align text: right\",\n alignJustifyControlLabel: \"Align text: justify\",\n codeControlLabel: \"Code\",\n codeBlockControlLabel: \"Code block\",\n subscriptControlLabel: \"Subscript\",\n superscriptControlLabel: \"Superscript\",\n unsetColorControlLabel: \"Unset color\",\n hrControlLabel: \"Horizontal line\",\n undoControlLabel: \"Undo\",\n redoControlLabel: \"Redo\",\n // Task list\n tasksControlLabel: \"Task list\",\n tasksSinkLabel: \"Decrease task level\",\n tasksLiftLabel: \"Increase task level\",\n // Link editor\n linkEditorInputLabel: \"Enter URL\",\n linkEditorInputPlaceholder: \"https://example.com/\",\n linkEditorExternalLink: \"Open link in a new tab\",\n linkEditorInternalLink: \"Open link in the same tab\",\n linkEditorSave: \"Save\",\n // Color picker control\n colorPickerCancel: \"Cancel\",\n colorPickerClear: \"Clear color\",\n colorPickerColorPicker: \"Color picker\",\n colorPickerPalette: \"Color palette\",\n colorPickerSave: \"Save\",\n colorPickerColorLabel: (color) => `Set text color ${color}`\n};\n\nexport { DEFAULT_LABELS };\n//# sourceMappingURL=labels.mjs.map\n","'use client';\nimport { createSafeContext } from '@mantine/core';\n\nconst [RichTextEditorProvider, useRichTextEditorContext] = createSafeContext(\"RichTextEditor component was not found in tree\");\n\nexport { RichTextEditorProvider, useRichTextEditorContext };\n//# sourceMappingURL=RichTextEditor.context.mjs.map\n","import { BubbleMenuPlugin } from '@tiptap/extension-bubble-menu';\nimport React, { forwardRef, useState, useDebugValue, useLayoutEffect, useEffect, useRef, createContext, useContext } from 'react';\nimport ReactDOM, { flushSync } from 'react-dom';\nimport { Editor, NodeView, getRenderedAttributes } from '@tiptap/core';\nexport * from '@tiptap/core';\nimport { FloatingMenuPlugin } from '@tiptap/extension-floating-menu';\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar shim = {exports: {}};\n\nvar useSyncExternalStoreShim_production_min = {};\n\n/**\n * @license React\n * use-sync-external-store-shim.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar hasRequiredUseSyncExternalStoreShim_production_min;\n\nfunction requireUseSyncExternalStoreShim_production_min () {\n\tif (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min;\n\thasRequiredUseSyncExternalStoreShim_production_min = 1;\nvar e=React;function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c});},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c});})},[a]);p(d);return d}\n\tfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k(a,d)}catch(f){return !0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;useSyncExternalStoreShim_production_min.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n\treturn useSyncExternalStoreShim_production_min;\n}\n\nvar useSyncExternalStoreShim_development = {};\n\n/**\n * @license React\n * use-sync-external-store-shim.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar hasRequiredUseSyncExternalStoreShim_development;\n\nfunction requireUseSyncExternalStoreShim_development () {\n\tif (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;\n\thasRequiredUseSyncExternalStoreShim_development = 1;\n\n\tif (process.env.NODE_ENV !== \"production\") {\n\t (function() {\n\n\t/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n\tif (\n\t typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n\t typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n\t 'function'\n\t) {\n\t __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n\t}\n\t var React$1 = React;\n\n\tvar ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\n\tfunction error(format) {\n\t {\n\t {\n\t for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n\t args[_key2 - 1] = arguments[_key2];\n\t }\n\n\t printWarning('error', format, args);\n\t }\n\t }\n\t}\n\n\tfunction printWarning(level, format, args) {\n\t // When changing this logic, you might want to also\n\t // update consoleWithStackDev.www.js as well.\n\t {\n\t var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\t var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n\t if (stack !== '') {\n\t format += '%s';\n\t args = args.concat([stack]);\n\t } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n\t var argsWithFormat = args.map(function (item) {\n\t return String(item);\n\t }); // Careful: RN currently depends on this prefix\n\n\t argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n\t // breaks IE9: https://github.com/facebook/react/issues/13610\n\t // eslint-disable-next-line react-internal/no-production-logging\n\n\t Function.prototype.apply.call(console[level], console, argsWithFormat);\n\t }\n\t}\n\n\t/**\n\t * inlined Object.is polyfill to avoid requiring consumers ship their own\n\t * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n\t */\n\tfunction is(x, y) {\n\t return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n\t ;\n\t}\n\n\tvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\n\t// dispatch for CommonJS interop named imports.\n\n\tvar useState = React$1.useState,\n\t useEffect = React$1.useEffect,\n\t useLayoutEffect = React$1.useLayoutEffect,\n\t useDebugValue = React$1.useDebugValue;\n\tvar didWarnOld18Alpha = false;\n\tvar didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works\n\t// because of a very particular set of implementation details and assumptions\n\t// -- change any one of them and it will break. The most important assumption\n\t// is that updates are always synchronous, because concurrent rendering is\n\t// only available in versions of React that also have a built-in\n\t// useSyncExternalStore API. And we only use this shim when the built-in API\n\t// does not exist.\n\t//\n\t// Do not assume that the clever hacks used by this hook also work in general.\n\t// The point of this shim is to replace the need for hacks by other libraries.\n\n\tfunction useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n\t// React do not expose a way to check if we're hydrating. So users of the shim\n\t// will need to track that themselves and return the correct value\n\t// from `getSnapshot`.\n\tgetServerSnapshot) {\n\t {\n\t if (!didWarnOld18Alpha) {\n\t if (React$1.startTransition !== undefined) {\n\t didWarnOld18Alpha = true;\n\n\t error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');\n\t }\n\t }\n\t } // Read the current snapshot from the store on every render. Again, this\n\t // breaks the rules of React, and only works here because of specific\n\t // implementation details, most importantly that updates are\n\t // always synchronous.\n\n\n\t var value = getSnapshot();\n\n\t {\n\t if (!didWarnUncachedGetSnapshot) {\n\t var cachedValue = getSnapshot();\n\n\t if (!objectIs(value, cachedValue)) {\n\t error('The result of getSnapshot should be cached to avoid an infinite loop');\n\n\t didWarnUncachedGetSnapshot = true;\n\t }\n\t }\n\t } // Because updates are synchronous, we don't queue them. Instead we force a\n\t // re-render whenever the subscribed state changes by updating an some\n\t // arbitrary useState hook. Then, during render, we call getSnapshot to read\n\t // the current value.\n\t //\n\t // Because we don't actually use the state returned by the useState hook, we\n\t // can save a bit of memory by storing other stuff in that slot.\n\t //\n\t // To implement the early bailout, we need to track some things on a mutable\n\t // object. Usually, we would put that in a useRef hook, but we can stash it in\n\t // our useState hook instead.\n\t //\n\t // To force a re-render, we call forceUpdate({inst}). That works because the\n\t // new object always fails an equality check.\n\n\n\t var _useState = useState({\n\t inst: {\n\t value: value,\n\t getSnapshot: getSnapshot\n\t }\n\t }),\n\t inst = _useState[0].inst,\n\t forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated\n\t // in the layout phase so we can access it during the tearing check that\n\t // happens on subscribe.\n\n\n\t useLayoutEffect(function () {\n\t inst.value = value;\n\t inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the\n\t // commit phase if there was an interleaved mutation. In concurrent mode\n\t // this can happen all the time, but even in synchronous mode, an earlier\n\t // effect may have mutated the store.\n\n\t if (checkIfSnapshotChanged(inst)) {\n\t // Force a re-render.\n\t forceUpdate({\n\t inst: inst\n\t });\n\t }\n\t }, [subscribe, value, getSnapshot]);\n\t useEffect(function () {\n\t // Check for changes right before subscribing. Subsequent changes will be\n\t // detected in the subscription handler.\n\t if (checkIfSnapshotChanged(inst)) {\n\t // Force a re-render.\n\t forceUpdate({\n\t inst: inst\n\t });\n\t }\n\n\t var handleStoreChange = function () {\n\t // TODO: Because there is no cross-renderer API for batching updates, it's\n\t // up to the consumer of this library to wrap their subscription event\n\t // with unstable_batchedUpdates. Should we try to detect when this isn't\n\t // the case and print a warning in development?\n\t // The store changed. Check if the snapshot changed since the last time we\n\t // read from the store.\n\t if (checkIfSnapshotChanged(inst)) {\n\t // Force a re-render.\n\t forceUpdate({\n\t inst: inst\n\t });\n\t }\n\t }; // Subscribe to the store and return a clean-up function.\n\n\n\t return subscribe(handleStoreChange);\n\t }, [subscribe]);\n\t useDebugValue(value);\n\t return value;\n\t}\n\n\tfunction checkIfSnapshotChanged(inst) {\n\t var latestGetSnapshot = inst.getSnapshot;\n\t var prevValue = inst.value;\n\n\t try {\n\t var nextValue = latestGetSnapshot();\n\t return !objectIs(prevValue, nextValue);\n\t } catch (error) {\n\t return true;\n\t }\n\t}\n\n\tfunction useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {\n\t // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n\t // React do not expose a way to check if we're hydrating. So users of the shim\n\t // will need to track that themselves and return the correct value\n\t // from `getSnapshot`.\n\t return getSnapshot();\n\t}\n\n\tvar canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\n\n\tvar isServerEnvironment = !canUseDOM;\n\n\tvar shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;\n\tvar useSyncExternalStore$2 = React$1.useSyncExternalStore !== undefined ? React$1.useSyncExternalStore : shim;\n\n\tuseSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;\n\t /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n\tif (\n\t typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n\t typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n\t 'function'\n\t) {\n\t __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n\t}\n\t \n\t })();\n\t}\n\treturn useSyncExternalStoreShim_development;\n}\n\nif (process.env.NODE_ENV === 'production') {\n shim.exports = requireUseSyncExternalStoreShim_production_min();\n} else {\n shim.exports = requireUseSyncExternalStoreShim_development();\n}\n\nvar shimExports = shim.exports;\n\nconst mergeRefs = (...refs) => {\n return (node) => {\n refs.forEach(ref => {\n if (typeof ref === 'function') {\n ref(node);\n }\n else if (ref) {\n ref.current = node;\n }\n });\n };\n};\n/**\n * This component renders all of the editor's node views.\n */\nconst Portals = ({ contentComponent, }) => {\n // For performance reasons, we render the node view portals on state changes only\n const renderers = shimExports.useSyncExternalStore(contentComponent.subscribe, contentComponent.getSnapshot, contentComponent.getServerSnapshot);\n // This allows us to directly render the portals without any additional wrapper\n return (React.createElement(React.Fragment, null, Object.values(renderers)));\n};\nfunction getInstance() {\n const subscribers = new Set();\n let renderers = {};\n return {\n /**\n * Subscribe to the editor instance's changes.\n */\n subscribe(callback) {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n },\n getSnapshot() {\n return renderers;\n },\n getServerSnapshot() {\n return renderers;\n },\n /**\n * Adds a new NodeView Renderer to the editor.\n */\n setRenderer(id, renderer) {\n renderers = {\n ...renderers,\n [id]: ReactDOM.createPortal(renderer.reactElement, renderer.element, id),\n };\n subscribers.forEach(subscriber => subscriber());\n },\n /**\n * Removes a NodeView Renderer from the editor.\n */\n removeRenderer(id) {\n const nextRenderers = { ...renderers };\n delete nextRenderers[id];\n renderers = nextRenderers;\n subscribers.forEach(subscriber => subscriber());\n },\n };\n}\nclass PureEditorContent extends React.Component {\n constructor(props) {\n var _a;\n super(props);\n this.editorContentRef = React.createRef();\n this.initialized = false;\n this.state = {\n hasContentComponentInitialized: Boolean((_a = props.editor) === null || _a === void 0 ? void 0 : _a.contentComponent),\n };\n }\n componentDidMount() {\n this.init();\n }\n componentDidUpdate() {\n this.init();\n }\n init() {\n const editor = this.props.editor;\n if (editor && !editor.isDestroyed && editor.options.element) {\n if (editor.contentComponent) {\n return;\n }\n const element = this.editorContentRef.current;\n element.append(...editor.options.element.childNodes);\n editor.setOptions({\n element,\n });\n editor.contentComponent = getInstance();\n // Has the content component been initialized?\n if (!this.state.hasContentComponentInitialized) {\n // Subscribe to the content component\n this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {\n this.setState(prevState => {\n if (!prevState.hasContentComponentInitialized) {\n return {\n hasContentComponentInitialized: true,\n };\n }\n return prevState;\n });\n // Unsubscribe to previous content component\n if (this.unsubscribeToContentComponent) {\n this.unsubscribeToContentComponent();\n }\n });\n }\n editor.createNodeViews();\n this.initialized = true;\n }\n }\n componentWillUnmount() {\n const editor = this.props.editor;\n if (!editor) {\n return;\n }\n this.initialized = false;\n if (!editor.isDestroyed) {\n editor.view.setProps({\n nodeViews: {},\n });\n }\n if (this.unsubscribeToContentComponent) {\n this.unsubscribeToContentComponent();\n }\n editor.contentComponent = null;\n if (!editor.options.element.firstChild) {\n return;\n }\n const newElement = document.createElement('div');\n newElement.append(...editor.options.element.childNodes);\n editor.setOptions({\n element: newElement,\n });\n }\n render() {\n const { editor, innerRef, ...rest } = this.props;\n return (React.createElement(React.Fragment, null,\n React.createElement(\"div\", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),\n (editor === null || editor === void 0 ? void 0 : editor.contentComponent) && React.createElement(Portals, { contentComponent: editor.contentComponent })));\n }\n}\n// EditorContent should be re-created whenever the Editor instance changes\nconst EditorContentWithKey = forwardRef((props, ref) => {\n const key = React.useMemo(() => {\n return Math.floor(Math.random() * 0xffffffff).toString();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.editor]);\n // Can't use JSX here because it conflicts with the type definition of Vue's JSX, so use createElement\n return React.createElement(PureEditorContent, {\n key,\n innerRef: ref,\n ...props,\n });\n});\nconst EditorContent = React.memo(EditorContentWithKey);\n\nvar react = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n if ((a instanceof Map) && (b instanceof Map)) {\n if (a.size !== b.size) return false;\n for (i of a.entries())\n if (!b.has(i[0])) return false;\n for (i of a.entries())\n if (!equal(i[1], b.get(i[0]))) return false;\n return true;\n }\n\n if ((a instanceof Set) && (b instanceof Set)) {\n if (a.size !== b.size) return false;\n for (i of a.entries())\n if (!b.has(i[0])) return false;\n return true;\n }\n\n if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (a[i] !== b[i]) return false;\n return true;\n }\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (key === '_owner' && a.$$typeof) {\n // React-specific: avoid traversing React elements' _owner.\n // _owner contains circular references\n // and is not needed when comparing the actual elements (and not their owners)\n continue;\n }\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n\nvar deepEqual = /*@__PURE__*/getDefaultExportFromCjs(react);\n\nvar withSelector = {exports: {}};\n\nvar withSelector_production_min = {};\n\n/**\n * @license React\n * use-sync-external-store-shim/with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar hasRequiredWithSelector_production_min;\n\nfunction requireWithSelector_production_min () {\n\tif (hasRequiredWithSelector_production_min) return withSelector_production_min;\n\thasRequiredWithSelector_production_min = 1;\nvar h=React,n=shimExports;function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q=\"function\"===typeof Object.is?Object.is:p,r=n.useSyncExternalStore,t=h.useRef,u=h.useEffect,v=h.useMemo,w=h.useDebugValue;\n\twithSelector_production_min.useSyncExternalStoreWithSelector=function(a,b,e,l,g){var c=t(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f;}else f=c.current;c=v(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return [function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r(a,c[0],c[1]);\n\tu(function(){f.hasValue=!0;f.value=d;},[d]);w(d);return d};\n\treturn withSelector_production_min;\n}\n\nvar withSelector_development = {};\n\n/**\n * @license React\n * use-sync-external-store-shim/with-selector.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar hasRequiredWithSelector_development;\n\nfunction requireWithSelector_development () {\n\tif (hasRequiredWithSelector_development) return withSelector_development;\n\thasRequiredWithSelector_development = 1;\n\n\tif (process.env.NODE_ENV !== \"production\") {\n\t (function() {\n\n\t/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n\tif (\n\t typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n\t typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n\t 'function'\n\t) {\n\t __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n\t}\n\t var React$1 = React;\n\tvar shim = shimExports;\n\n\t/**\n\t * inlined Object.is polyfill to avoid requiring consumers ship their own\n\t * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n\t */\n\tfunction is(x, y) {\n\t return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n\t ;\n\t}\n\n\tvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\n\tvar useSyncExternalStore = shim.useSyncExternalStore;\n\n\t// for CommonJS interop.\n\n\tvar useRef = React$1.useRef,\n\t useEffect = React$1.useEffect,\n\t useMemo = React$1.useMemo,\n\t useDebugValue = React$1.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.\n\n\tfunction useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {\n\t // Use this to track the rendered snapshot.\n\t var instRef = useRef(null);\n\t var inst;\n\n\t if (instRef.current === null) {\n\t inst = {\n\t hasValue: false,\n\t value: null\n\t };\n\t instRef.current = inst;\n\t } else {\n\t inst = instRef.current;\n\t }\n\n\t var _useMemo = useMemo(function () {\n\t // Track the memoized state using closure variables that are local to this\n\t // memoized instance of a getSnapshot function. Intentionally not using a\n\t // useRef hook, because that state would be shared across all concurrent\n\t // copies of the hook/component.\n\t var hasMemo = false;\n\t var memoizedSnapshot;\n\t var memoizedSelection;\n\n\t var memoizedSelector = function (nextSnapshot) {\n\t if (!hasMemo) {\n\t // The first time the hook is called, there is no memoized result.\n\t hasMemo = true;\n\t memoizedSnapshot = nextSnapshot;\n\n\t var _nextSelection = selector(nextSnapshot);\n\n\t if (isEqual !== undefined) {\n\t // Even if the selector has changed, the currently rendered selection\n\t // may be equal to the new selection. We should attempt to reuse the\n\t // current value if possible, to preserve downstream memoizations.\n\t if (inst.hasValue) {\n\t var currentSelection = inst.value;\n\n\t if (isEqual(currentSelection, _nextSelection)) {\n\t memoizedSelection = currentSelection;\n\t return currentSelection;\n\t }\n\t }\n\t }\n\n\t memoizedSelection = _nextSelection;\n\t return _nextSelection;\n\t } // We may be able to reuse the previous invocation's result.\n\n\n\t // We may be able to reuse the previous invocation's result.\n\t var prevSnapshot = memoizedSnapshot;\n\t var prevSelection = memoizedSelection;\n\n\t if (objectIs(prevSnapshot, nextSnapshot)) {\n\t // The snapshot is the same as last time. Reuse the previous selection.\n\t return prevSelection;\n\t } // The snapshot has changed, so we need to compute a new selection.\n\n\n\t // The snapshot has changed, so we need to compute a new selection.\n\t var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data\n\t // has changed. If it hasn't, return the previous selection. That signals\n\t // to React that the selections are conceptually equal, and we can bail\n\t // out of rendering.\n\n\t // If a custom isEqual function is provided, use that to check if the data\n\t // has changed. If it hasn't, return the previous selection. That signals\n\t // to React that the selections are conceptually equal, and we can bail\n\t // out of rendering.\n\t if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {\n\t return prevSelection;\n\t }\n\n\t memoizedSnapshot = nextSnapshot;\n\t memoizedSelection = nextSelection;\n\t return nextSelection;\n\t }; // Assigning this to a constant so that Flow knows it can't change.\n\n\n\t // Assigning this to a constant so that Flow knows it can't change.\n\t var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;\n\n\t var getSnapshotWithSelector = function () {\n\t return memoizedSelector(getSnapshot());\n\t };\n\n\t var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {\n\t return memoizedSelector(maybeGetServerSnapshot());\n\t };\n\t return [getSnapshotWithSelector, getServerSnapshotWithSelector];\n\t }, [getSnapshot, getServerSnapshot, selector, isEqual]),\n\t getSelection = _useMemo[0],\n\t getServerSelection = _useMemo[1];\n\n\t var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);\n\t useEffect(function () {\n\t inst.hasValue = true;\n\t inst.value = value;\n\t }, [value]);\n\t useDebugValue(value);\n\t return value;\n\t}\n\n\twithSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;\n\t /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n\tif (\n\t typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n\t typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n\t 'function'\n\t) {\n\t __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n\t}\n\t \n\t })();\n\t}\n\treturn withSelector_development;\n}\n\nif (process.env.NODE_ENV === 'production') {\n withSelector.exports = requireWithSelector_production_min();\n} else {\n withSelector.exports = requireWithSelector_development();\n}\n\nvar withSelectorExports = withSelector.exports;\n\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n/**\n * To synchronize the editor instance with the component state,\n * we need to create a separate instance that is not affected by the component re-renders.\n */\nclass EditorStateManager {\n constructor(initialEditor) {\n this.transactionNumber = 0;\n this.lastTransactionNumber = 0;\n this.subscribers = new Set();\n this.editor = initialEditor;\n this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 };\n this.getSnapshot = this.getSnapshot.bind(this);\n this.getServerSnapshot = this.getServerSnapshot.bind(this);\n this.watch = this.watch.bind(this);\n this.subscribe = this.subscribe.bind(this);\n }\n /**\n * Get the current editor instance.\n */\n getSnapshot() {\n if (this.transactionNumber === this.lastTransactionNumber) {\n return this.lastSnapshot;\n }\n this.lastTransactionNumber = this.transactionNumber;\n this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber };\n return this.lastSnapshot;\n }\n /**\n * Always disable the editor on the server-side.\n */\n getServerSnapshot() {\n return { editor: null, transactionNumber: 0 };\n }\n /**\n * Subscribe to the editor instance's changes.\n */\n subscribe(callback) {\n this.subscribers.add(callback);\n return () => {\n this.subscribers.delete(callback);\n };\n }\n /**\n * Watch the editor instance for changes.\n */\n watch(nextEditor) {\n this.editor = nextEditor;\n if (this.editor) {\n /**\n * This will force a re-render when the editor state changes.\n * This is to support things like `editor.can().toggleBold()` in components that `useEditor`.\n * This could be more efficient, but it's a good trade-off for now.\n */\n const fn = () => {\n this.transactionNumber += 1;\n this.subscribers.forEach(callback => callback());\n };\n const currentEditor = this.editor;\n currentEditor.on('transaction', fn);\n return () => {\n currentEditor.off('transaction', fn);\n };\n }\n return undefined;\n }\n}\n/**\n * This hook allows you to watch for changes on the editor instance.\n * It will allow you to select a part of the editor state and re-render the component when it changes.\n * @example\n * ```tsx\n * const editor = useEditor({...options})\n * const { currentSelection } = useEditorState({\n * editor,\n * selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),\n * })\n */\nfunction useEditorState(options) {\n var _a;\n const [editorStateManager] = useState(() => new EditorStateManager(options.editor));\n // Using the `useSyncExternalStore` hook to sync the editor instance with the component state\n const selectedState = withSelectorExports.useSyncExternalStoreWithSelector(editorStateManager.subscribe, editorStateManager.getSnapshot, editorStateManager.getServerSnapshot, options.selector, (_a = options.equalityFn) !== null && _a !== void 0 ? _a : deepEqual);\n useIsomorphicLayoutEffect(() => {\n return editorStateManager.watch(options.editor);\n }, [options.editor, editorStateManager]);\n useDebugValue(selectedState);\n return selectedState;\n}\n\nconst isDev = process.env.NODE_ENV !== 'production';\nconst isSSR = typeof window === 'undefined';\nconst isNext = isSSR || Boolean(typeof window !== 'undefined' && window.next);\n/**\n * This class handles the creation, destruction, and re-creation of the editor instance.\n */\nclass EditorInstanceManager {\n constructor(options) {\n /**\n * The current editor instance.\n */\n this.editor = null;\n /**\n * The subscriptions to notify when the editor instance\n * has been created or destroyed.\n */\n this.subscriptions = new Set();\n /**\n * Whether the editor has been mounted.\n */\n this.isComponentMounted = false;\n /**\n * The most recent dependencies array.\n */\n this.previousDeps = null;\n /**\n * The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.\n */\n this.instanceId = '';\n this.options = options;\n this.subscriptions = new Set();\n this.setEditor(this.getInitialEditor());\n this.scheduleDestroy();\n this.getEditor = this.getEditor.bind(this);\n this.getServerSnapshot = this.getServerSnapshot.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.refreshEditorInstance = this.refreshEditorInstance.bind(this);\n this.scheduleDestroy = this.scheduleDestroy.bind(this);\n this.onRender = this.onRender.bind(this);\n this.createEditor = this.createEditor.bind(this);\n }\n setEditor(editor) {\n this.editor = editor;\n this.instanceId = Math.random().toString(36).slice(2, 9);\n // Notify all subscribers that the editor instance has been created\n this.subscriptions.forEach(cb => cb());\n }\n getInitialEditor() {\n if (this.options.current.immediatelyRender === undefined) {\n if (isSSR || isNext) {\n // TODO in the next major release, we should throw an error here\n if (isDev) {\n /**\n * Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd\n * and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches.\n */\n console.warn('Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.');\n }\n // Best faith effort in production, run the code in the legacy mode to avoid hydration mismatches and errors in production\n return null;\n }\n // Default to immediately rendering when client-side rendering\n return this.createEditor();\n }\n if (this.options.current.immediatelyRender && isSSR && isDev) {\n // Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches.\n throw new Error('Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches.');\n }\n if (this.options.current.immediatelyRender) {\n return this.createEditor();\n }\n return null;\n }\n /**\n * Create a new editor instance. And attach event listeners.\n */\n createEditor() {\n const optionsToApply = {\n ...this.options.current,\n // Always call the most recent version of the callback function by default\n onBeforeCreate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onBeforeCreate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onBlur: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onBlur) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onCreate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onCreate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onDestroy: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onDestroy) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onFocus: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onFocus) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onSelectionUpdate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onSelectionUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onTransaction: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onTransaction) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onUpdate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onContentError: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onContentError) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onDrop: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onDrop) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n onPaste: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onPaste) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },\n };\n const editor = new Editor(optionsToApply);\n // no need to keep track of the event listeners, they will be removed when the editor is destroyed\n return editor;\n }\n /**\n * Get the current editor instance.\n */\n getEditor() {\n return this.editor;\n }\n /**\n * Always disable the editor on the server-side.\n */\n getServerSnapshot() {\n return null;\n }\n /**\n * Subscribe to the editor instance's changes.\n */\n subscribe(onStoreChange) {\n this.subscriptions.add(onStoreChange);\n return () => {\n this.subscriptions.delete(onStoreChange);\n };\n }\n static compareOptions(a, b) {\n return Object.keys(a).every(key => {\n if (['onCreate', 'onBeforeCreate', 'onDestroy', 'onUpdate', 'onTransaction', 'onFocus', 'onBlur', 'onSelectionUpdate', 'onContentError', 'onDrop', 'onPaste'].includes(key)) {\n // we don't want to compare callbacks, they are always different and only registered once\n return true;\n }\n // We often encourage putting extensions inlined in the options object, so we will do a slightly deeper comparison here\n if (key === 'extensions' && a.extensions && b.extensions) {\n if (a.extensions.length !== b.extensions.length) {\n return false;\n }\n return a.extensions.every((extension, index) => {\n var _a;\n if (extension !== ((_a = b.extensions) === null || _a === void 0 ? void 0 : _a[index])) {\n return false;\n }\n return true;\n });\n }\n if (a[key] !== b[key]) {\n // if any of the options have changed, we should update the editor options\n return false;\n }\n return true;\n });\n }\n /**\n * On each render, we will create, update, or destroy the editor instance.\n * @param deps The dependencies to watch for changes\n * @returns A cleanup function\n */\n onRender(deps) {\n // The returned callback will run on each render\n return () => {\n this.isComponentMounted = true;\n // Cleanup any scheduled destructions, since we are currently rendering\n clearTimeout(this.scheduledDestructionTimeout);\n if (this.editor && !this.editor.isDestroyed && deps.length === 0) {\n // if the editor does exist & deps are empty, we don't need to re-initialize the editor generally\n if (!EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) {\n // But, the options are different, so we need to update the editor options\n // Still, this is faster than re-creating the editor\n this.editor.setOptions({\n ...this.options.current,\n editable: this.editor.isEditable,\n });\n }\n }\n else {\n // When the editor:\n // - does not yet exist\n // - is destroyed\n // - the deps array changes\n // We need to destroy the editor instance and re-initialize it\n this.refreshEditorInstance(deps);\n }\n return () => {\n this.isComponentMounted = false;\n this.scheduleDestroy();\n };\n };\n }\n /**\n * Recreate the editor instance if the dependencies have changed.\n */\n refreshEditorInstance(deps) {\n if (this.editor && !this.editor.isDestroyed) {\n // Editor instance already exists\n if (this.previousDeps === null) {\n // If lastDeps has not yet been initialized, reuse the current editor instance\n this.previousDeps = deps;\n return;\n }\n const depsAreEqual = this.previousDeps.length === deps.length\n && this.previousDeps.every((dep, index) => dep === deps[index]);\n if (depsAreEqual) {\n // deps exist and are equal, no need to recreate\n return;\n }\n }\n if (this.editor && !this.editor.isDestroyed) {\n // Destroy the editor instance if it exists\n this.editor.destroy();\n }\n this.setEditor(this.createEditor());\n // Update the lastDeps to the current deps\n this.previousDeps = deps;\n }\n /**\n * Schedule the destruction of the editor instance.\n * This will only destroy the editor if it was not mounted on the next tick.\n * This is to avoid destroying the editor instance when it's actually still mounted.\n */\n scheduleDestroy() {\n const currentInstanceId = this.instanceId;\n const currentEditor = this.editor;\n // Wait two ticks to see if the component is still mounted\n this.scheduledDestructionTimeout = setTimeout(() => {\n if (this.isComponentMounted && this.instanceId === currentInstanceId) {\n // If still mounted on the following tick, with the same instanceId, do not destroy the editor\n if (currentEditor) {\n // just re-apply options as they might have changed\n currentEditor.setOptions(this.options.current);\n }\n return;\n }\n if (currentEditor && !currentEditor.isDestroyed) {\n currentEditor.destroy();\n if (this.instanceId === currentInstanceId) {\n this.setEditor(null);\n }\n }\n // This allows the effect to run again between ticks\n // which may save us from having to re-create the editor\n }, 1);\n }\n}\nfunction useEditor(options = {}, deps = []) {\n const mostRecentOptions = useRef(options);\n mostRecentOptions.current = options;\n const [instanceManager] = useState(() => new EditorInstanceManager(mostRecentOptions));\n const editor = shimExports.useSyncExternalStore(instanceManager.subscribe, instanceManager.getEditor, instanceManager.getServerSnapshot);\n useDebugValue(editor);\n // This effect will handle creating/updating the editor instance\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(instanceManager.onRender(deps));\n // The default behavior is to re-render on each transaction\n // This is legacy behavior that will be removed in future versions\n useEditorState({\n editor,\n selector: ({ transactionNumber }) => {\n if (options.shouldRerenderOnTransaction === false) {\n // This will prevent the editor from re-rendering on each transaction\n return null;\n }\n // This will avoid re-rendering on the first transaction when `immediatelyRender` is set to `true`\n if (options.immediatelyRender && transactionNumber === 0) {\n return 0;\n }\n return transactionNumber + 1;\n },\n });\n return editor;\n}\n\nconst EditorContext = createContext({\n editor: null,\n});\nconst EditorConsumer = EditorContext.Consumer;\n/**\n * A hook to get the current editor instance.\n */\nconst useCurrentEditor = () => useContext(EditorContext);\n/**\n * This is the provider component for the editor.\n * It allows the editor to be accessible across the entire component tree\n * with `useCurrentEditor`.\n */\nfunction EditorProvider({ children, slotAfter, slotBefore, editorContainerProps = {}, ...editorOptions }) {\n const editor = useEditor(editorOptions);\n if (!editor) {\n return null;\n }\n return (React.createElement(EditorContext.Provider, { value: { editor } },\n slotBefore,\n React.createElement(EditorConsumer, null, ({ editor: currentEditor }) => (React.createElement(EditorContent, { editor: currentEditor, ...editorContainerProps }))),\n children,\n slotAfter));\n}\n\nconst BubbleMenu = (props) => {\n const [element, setElement] = useState(null);\n const { editor: currentEditor } = useCurrentEditor();\n useEffect(() => {\n var _a;\n if (!element) {\n return;\n }\n if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {\n return;\n }\n const { pluginKey = 'bubbleMenu', editor, tippyOptions = {}, updateDelay, shouldShow = null, } = props;\n const menuEditor = editor || currentEditor;\n if (!menuEditor) {\n console.warn('BubbleMenu component is not rendered inside of an editor component or does not have editor prop.');\n return;\n }\n const plugin = BubbleMenuPlugin({\n updateDelay,\n editor: menuEditor,\n element,\n pluginKey,\n shouldShow,\n tippyOptions,\n });\n menuEditor.registerPlugin(plugin);\n return () => { menuEditor.unregisterPlugin(pluginKey); };\n }, [props.editor, currentEditor, element]);\n return (React.createElement(\"div\", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));\n};\n\nconst FloatingMenu = (props) => {\n const [element, setElement] = useState(null);\n const { editor: currentEditor } = useCurrentEditor();\n useEffect(() => {\n var _a;\n if (!element) {\n return;\n }\n if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {\n return;\n }\n const { pluginKey = 'floatingMenu', editor, tippyOptions = {}, shouldShow = null, } = props;\n const menuEditor = editor || currentEditor;\n if (!menuEditor) {\n console.warn('FloatingMenu component is not rendered inside of an editor component or does not have editor prop.');\n return;\n }\n const plugin = FloatingMenuPlugin({\n pluginKey,\n editor: menuEditor,\n element,\n tippyOptions,\n shouldShow,\n });\n menuEditor.registerPlugin(plugin);\n return () => { menuEditor.unregisterPlugin(pluginKey); };\n }, [\n props.editor,\n currentEditor,\n element,\n ]);\n return (React.createElement(\"div\", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));\n};\n\nconst ReactNodeViewContext = createContext({\n onDragStart: undefined,\n});\nconst useReactNodeView = () => useContext(ReactNodeViewContext);\n\nconst NodeViewContent = props => {\n const Tag = props.as || 'div';\n const { nodeViewContentRef } = useReactNodeView();\n return (\n // @ts-ignore\n React.createElement(Tag, { ...props, ref: nodeViewContentRef, \"data-node-view-content\": \"\", style: {\n whiteSpace: 'pre-wrap',\n ...props.style,\n } }));\n};\n\nconst NodeViewWrapper = React.forwardRef((props, ref) => {\n const { onDragStart } = useReactNodeView();\n const Tag = props.as || 'div';\n return (\n // @ts-ignore\n React.createElement(Tag, { ...props, ref: ref, \"data-node-view-wrapper\": \"\", onDragStart: onDragStart, style: {\n whiteSpace: 'normal',\n ...props.style,\n } }));\n});\n\n/**\n * Check if a component is a class component.\n * @param Component\n * @returns {boolean}\n */\nfunction isClassComponent(Component) {\n return !!(typeof Component === 'function'\n && Component.prototype\n && Component.prototype.isReactComponent);\n}\n/**\n * Check if a component is a forward ref component.\n * @param Component\n * @returns {boolean}\n */\nfunction isForwardRefComponent(Component) {\n var _a;\n return !!(typeof Component === 'object'\n && ((_a = Component.$$typeof) === null || _a === void 0 ? void 0 : _a.toString()) === 'Symbol(react.forward_ref)');\n}\n/**\n * The ReactRenderer class. It's responsible for rendering React components inside the editor.\n * @example\n * new ReactRenderer(MyComponent, {\n * editor,\n * props: {\n * foo: 'bar',\n * },\n * as: 'span',\n * })\n*/\nclass ReactRenderer {\n /**\n * Immediately creates element and renders the provided React component.\n */\n constructor(component, { editor, props = {}, as = 'div', className = '', }) {\n this.ref = null;\n this.id = Math.floor(Math.random() * 0xFFFFFFFF).toString();\n this.component = component;\n this.editor = editor;\n this.props = props;\n this.element = document.createElement(as);\n this.element.classList.add('react-renderer');\n if (className) {\n this.element.classList.add(...className.split(' '));\n }\n if (this.editor.isInitialized) {\n // On first render, we need to flush the render synchronously\n // Renders afterwards can be async, but this fixes a cursor positioning issue\n flushSync(() => {\n this.render();\n });\n }\n else {\n this.render();\n }\n }\n /**\n * Render the React component.\n */\n render() {\n var _a;\n const Component = this.component;\n const props = this.props;\n const editor = this.editor;\n if (isClassComponent(Component) || isForwardRefComponent(Component)) {\n // @ts-ignore This is a hack to make the ref work\n props.ref = (ref) => {\n this.ref = ref;\n };\n }\n this.reactElement = React.createElement(Component, { ...props });\n (_a = editor === null || editor === void 0 ? void 0 : editor.contentComponent) === null || _a === void 0 ? void 0 : _a.setRenderer(this.id, this);\n }\n /**\n * Re-renders the React component with new props.\n */\n updateProps(props = {}) {\n this.props = {\n ...this.props,\n ...props,\n };\n this.render();\n }\n /**\n * Destroy the React component.\n */\n destroy() {\n var _a;\n const editor = this.editor;\n (_a = editor === null || editor === void 0 ? void 0 : editor.contentComponent) === null || _a === void 0 ? void 0 : _a.removeRenderer(this.id);\n }\n /**\n * Update the attributes of the element that holds the React component.\n */\n updateAttributes(attributes) {\n Object.keys(attributes).forEach(key => {\n this.element.setAttribute(key, attributes[key]);\n });\n }\n}\n\nclass ReactNodeView extends NodeView {\n /**\n * Setup the React component.\n * Called on initialization.\n */\n mount() {\n const props = {\n editor: this.editor,\n node: this.node,\n decorations: this.decorations,\n innerDecorations: this.innerDecorations,\n view: this.view,\n selected: false,\n extension: this.extension,\n HTMLAttributes: this.HTMLAttributes,\n getPos: () => this.getPos(),\n updateAttributes: (attributes = {}) => this.updateAttributes(attributes),\n deleteNode: () => this.deleteNode(),\n };\n if (!this.component.displayName) {\n const capitalizeFirstChar = (string) => {\n return string.charAt(0).toUpperCase() + string.substring(1);\n };\n this.component.displayName = capitalizeFirstChar(this.extension.name);\n }\n const onDragStart = this.onDragStart.bind(this);\n const nodeViewContentRef = element => {\n if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {\n element.appendChild(this.contentDOMElement);\n }\n };\n const context = { onDragStart, nodeViewContentRef };\n const Component = this.component;\n // For performance reasons, we memoize the provider component\n // And all of the things it requires are declared outside of the component, so it doesn't need to re-render\n const ReactNodeViewProvider = React.memo(componentProps => {\n return (React.createElement(ReactNodeViewContext.Provider, { value: context }, React.createElement(Component, componentProps)));\n });\n ReactNodeViewProvider.displayName = 'ReactNodeView';\n if (this.node.isLeaf) {\n this.contentDOMElement = null;\n }\n else if (this.options.contentDOMElementTag) {\n this.contentDOMElement = document.createElement(this.options.contentDOMElementTag);\n }\n else {\n this.contentDOMElement = document.createElement(this.node.isInline ? 'span' : 'div');\n }\n if (this.contentDOMElement) {\n this.contentDOMElement.dataset.nodeViewContentReact = '';\n // For some reason the whiteSpace prop is not inherited properly in Chrome and Safari\n // With this fix it seems to work fine\n // See: https://github.com/ueberdosis/tiptap/issues/1197\n this.contentDOMElement.style.whiteSpace = 'inherit';\n }\n let as = this.node.isInline ? 'span' : 'div';\n if (this.options.as) {\n as = this.options.as;\n }\n const { className = '' } = this.options;\n this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this);\n this.renderer = new ReactRenderer(ReactNodeViewProvider, {\n editor: this.editor,\n props,\n as,\n className: `node-${this.node.type.name} ${className}`.trim(),\n });\n this.editor.on('selectionUpdate', this.handleSelectionUpdate);\n this.updateElementAttributes();\n }\n /**\n * Return the DOM element.\n * This is the element that will be used to display the node view.\n */\n get dom() {\n var _a;\n if (this.renderer.element.firstElementChild\n && !((_a = this.renderer.element.firstElementChild) === null || _a === void 0 ? void 0 : _a.hasAttribute('data-node-view-wrapper'))) {\n throw Error('Please use the NodeViewWrapper component for your node view.');\n }\n return this.renderer.element;\n }\n /**\n * Return the content DOM element.\n * This is the element that will be used to display the rich-text content of the node.\n */\n get contentDOM() {\n if (this.node.isLeaf) {\n return null;\n }\n return this.contentDOMElement;\n }\n /**\n * On editor selection update, check if the node is selected.\n * If it is, call `selectNode`, otherwise call `deselectNode`.\n */\n handleSelectionUpdate() {\n const { from, to } = this.editor.state.selection;\n const pos = this.getPos();\n if (typeof pos !== 'number') {\n return;\n }\n if (from <= pos && to >= pos + this.node.nodeSize) {\n if (this.renderer.props.selected) {\n return;\n }\n this.selectNode();\n }\n else {\n if (!this.renderer.props.selected) {\n return;\n }\n this.deselectNode();\n }\n }\n /**\n * On update, update the React component.\n * To prevent unnecessary updates, the `update` option can be used.\n */\n update(node, decorations, innerDecorations) {\n const rerenderComponent = (props) => {\n this.renderer.updateProps(props);\n if (typeof this.options.attrs === 'function') {\n this.updateElementAttributes();\n }\n };\n if (node.type !== this.node.type) {\n return false;\n }\n if (typeof this.options.update === 'function') {\n const oldNode = this.node;\n const oldDecorations = this.decorations;\n const oldInnerDecorations = this.innerDecorations;\n this.node = node;\n this.decorations = decorations;\n this.innerDecorations = innerDecorations;\n return this.options.update({\n oldNode,\n oldDecorations,\n newNode: node,\n newDecorations: decorations,\n oldInnerDecorations,\n innerDecorations,\n updateProps: () => rerenderComponent({ node, decorations, innerDecorations }),\n });\n }\n if (node === this.node\n && this.decorations === decorations\n && this.innerDecorations === innerDecorations) {\n return true;\n }\n this.node = node;\n this.decorations = decorations;\n this.innerDecorations = innerDecorations;\n rerenderComponent({ node, decorations, innerDecorations });\n return true;\n }\n /**\n * Select the node.\n * Add the `selected` prop and the `ProseMirror-selectednode` class.\n */\n selectNode() {\n this.renderer.updateProps({\n selected: true,\n });\n this.renderer.element.classList.add('ProseMirror-selectednode');\n }\n /**\n * Deselect the node.\n * Remove the `selected` prop and the `ProseMirror-selectednode` class.\n */\n deselectNode() {\n this.renderer.updateProps({\n selected: false,\n });\n this.renderer.element.classList.remove('ProseMirror-selectednode');\n }\n /**\n * Destroy the React component instance.\n */\n destroy() {\n this.renderer.destroy();\n this.editor.off('selectionUpdate', this.handleSelectionUpdate);\n this.contentDOMElement = null;\n }\n /**\n * Update the attributes of the top-level element that holds the React component.\n * Applying the attributes defined in the `attrs` option.\n */\n updateElementAttributes() {\n if (this.options.attrs) {\n let attrsObj = {};\n if (typeof this.options.attrs === 'function') {\n const extensionAttributes = this.editor.extensionManager.attributes;\n const HTMLAttributes = getRenderedAttributes(this.node, extensionAttributes);\n attrsObj = this.options.attrs({ node: this.node, HTMLAttributes });\n }\n else {\n attrsObj = this.options.attrs;\n }\n this.renderer.updateAttributes(attrsObj);\n }\n }\n}\n/**\n * Create a React node view renderer.\n */\nfunction ReactNodeViewRenderer(component, options) {\n return props => {\n // try to get the parent component\n // this is important for vue devtools to show the component hierarchy correctly\n // maybe it’s `undefined` because isn’t rendered yet\n if (!props.editor.contentComponent) {\n return {};\n }\n return new ReactNodeView(component, props, options);\n };\n}\n\nexport { BubbleMenu, EditorConsumer, EditorContent, EditorContext, EditorProvider, FloatingMenu, NodeViewContent, NodeViewWrapper, PureEditorContent, ReactNodeView, ReactNodeViewContext, ReactNodeViewRenderer, ReactRenderer, useCurrentEditor, useEditor, useEditorState, useReactNodeView };\n//# sourceMappingURL=index.js.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { EditorContent } from '@tiptap/react';\nimport { factory, useProps, TypographyStylesProvider, Box } from '@mantine/core';\nimport { useRichTextEditorContext } from '../RichTextEditor.context.mjs';\nimport classes from '../RichTextEditor.module.css.mjs';\n\nconst defaultProps = {};\nconst RichTextEditorContent = factory((_props, ref) => {\n const props = useProps(\"RichTextEditorContent\", defaultProps, _props);\n const { classNames, className, style, styles, vars, ...others } = props;\n const ctx = useRichTextEditorContext();\n if (ctx.withTypographyStyles) {\n return /* @__PURE__ */ jsx(\n TypographyStylesProvider,\n {\n ...ctx.getStyles(\"typographyStylesProvider\", { className, style, styles, classNames }),\n unstyled: ctx.unstyled,\n ref,\n children: /* @__PURE__ */ jsx(\n Box,\n {\n component: EditorContent,\n editor: ctx.editor,\n ...ctx.getStyles(\"content\", { classNames, styles }),\n ...others\n }\n )\n }\n );\n }\n return /* @__PURE__ */ jsx(\n Box,\n {\n component: EditorContent,\n editor: ctx.editor,\n ...ctx.getStyles(\"content\", { classNames, styles, className, style }),\n ...others\n }\n );\n});\nRichTextEditorContent.classes = classes;\nRichTextEditorContent.displayName = \"@mantine/tiptap/RichTextEditorContent\";\n\nexport { RichTextEditorContent };\n//# sourceMappingURL=RichTextEditorContent.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\n\nfunction IconBase(props) {\n return /* @__PURE__ */ jsx(\n \"svg\",\n {\n ...props,\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 24 24\",\n strokeWidth: \"1.5\",\n stroke: \"currentColor\",\n fill: \"none\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n }\n );\n}\nfunction IconBold(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M7 5h6a3.5 3.5 0 0 1 0 7h-6z\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M13 12h1a3.5 3.5 0 0 1 0 7h-7v-7\" })\n ] });\n}\nfunction IconItalic(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 5l6 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M7 19l6 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M14 5l-4 14\" })\n ] });\n}\nfunction IconUnderline(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M7 5v5a5 5 0 0 0 10 0v-5\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 19h14\" })\n ] });\n}\nfunction IconStrikethrough(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 12l14 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M16 6.5a4 2 0 0 0 -4 -1.5h-1a3.5 3.5 0 0 0 0 7h2a3.5 3.5 0 0 1 0 7h-1.5a4 2 0 0 1 -4 -1.5\" })\n ] });\n}\nfunction IconClearFormatting(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M17 15l4 4m0 -4l-4 4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M7 6v-1h11v1\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M7 19l4 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M13 5l-4 14\" })\n ] });\n}\nfunction IconH1(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M19 18v-8l-2 2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 12h8\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 6h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6h2\" })\n ] });\n}\nfunction IconH2(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M17 12a2 2 0 1 1 4 0c0 .591 -.417 1.318 -.816 1.858l-3.184 4.143l4 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 12h8\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 6h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6h2\" })\n ] });\n}\nfunction IconH3(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M19 14a2 2 0 1 0 -2 -2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M17 16a2 2 0 1 0 2 -2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 12h8\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 6h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6h2\" })\n ] });\n}\nfunction IconH4(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20 18v-8l-4 6h5\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 12h8\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 6h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6h2\" })\n ] });\n}\nfunction IconH5(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M17 18h2a2 2 0 1 0 0 -4h-2v-4h4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 12h8\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 6h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6h2\" })\n ] });\n}\nfunction IconH6(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M19 14a2 2 0 1 0 0 4a2 2 0 0 0 0 -4z\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M21 12a2 2 0 1 0 -4 0v4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 6v12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 18h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 12h8\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 6h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6h2\" })\n ] });\n}\nfunction IconList(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M9 6l11 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M9 12l11 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M9 18l11 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 6l0 .01\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 12l0 .01\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 18l0 .01\" })\n ] });\n}\nfunction IconListNumbers(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6h9\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 12h9\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 18h8\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 16a2 2 0 1 1 4 0c0 .591 -.5 1 -1 1.5l-3 2.5h4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M6 10v-6l-2 2\" })\n ] });\n}\nfunction IconUnlink(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M17 22v-2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M9 15l6 -6\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6l.463 -.536a5 5 0 0 1 7.071 7.072l-.534 .464\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20 17h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M2 7h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M7 2v2\" })\n ] });\n}\nfunction IconBlockquote(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M6 15h15\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M21 19h-15\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M15 11h6\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M21 7h-6\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M9 9h1a1 1 0 1 1 -1 1v-2.5a2 2 0 0 1 2 -2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 9h1a1 1 0 1 1 -1 1v-2.5a2 2 0 0 1 2 -2\" })\n ] });\n}\nfunction IconAlignLeft(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6l16 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 12l10 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 18l14 0\" })\n ] });\n}\nfunction IconAlignRight(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6l16 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M10 12l10 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M6 18l14 0\" })\n ] });\n}\nfunction IconAlignCenter(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6l16 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M8 12l8 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M6 18l12 0\" })\n ] });\n}\nfunction IconAlignJustified(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 6l16 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 12l16 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 18l12 0\" })\n ] });\n}\nfunction IconSubscript(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 7l8 10m-8 0l8 -10\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M21 20h-4l3.5 -4a1.73 1.73 0 0 0 -3.5 -2\" })\n ] });\n}\nfunction IconSuperscript(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 7l8 10m-8 0l8 -10\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M21 11h-4l3.5 -4a1.73 1.73 0 0 0 -3.5 -2\" })\n ] });\n}\nfunction IconCode(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M7 8l-4 4l4 4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M17 8l4 4l-4 4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M14 4l-4 16\" })\n ] });\n}\nfunction IconHighlight(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 19h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12.5 5.5l4 4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4.5 13.5l4 4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M21 15v4h-8l4 -4z\" })\n ] });\n}\nfunction IconLineDashed(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 12h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M17 12h2\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 12h2\" })\n ] });\n}\nfunction IconCircleOff(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20.042 16.045a9 9 0 0 0 -12.087 -12.087m-2.318 1.677a9 9 0 1 0 12.725 12.73\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3 3l18 18\" })\n ] });\n}\nfunction IconColorPicker(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 7l6 6\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 16l11.7 -11.7a1 1 0 0 1 1.4 0l2.6 2.6a1 1 0 0 1 0 1.4l-11.7 11.7h-4v-4z\" })\n ] });\n}\nfunction IconX(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M18 6l-12 12\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M6 6l12 12\" })\n ] });\n}\nfunction IconPalette(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 21a9 9 0 0 1 0 -18c4.97 0 9 3.582 9 8c0 1.06 -.474 2.078 -1.318 2.828c-.844 .75 -1.989 1.172 -3.182 1.172h-2.5a2 2 0 0 0 -1 3.75a1.3 1.3 0 0 1 -1 2.25\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M8.5 10.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12.5 7.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M16.5 10.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\" })\n ] });\n}\nfunction IconCheck(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 12l5 5l10 -10\" })\n ] });\n}\nfunction IconLink(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M9 15l6 -6\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6l.463 -.536a5 5 0 0 1 7.071 7.072l-.534 .464\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463\" })\n ] });\n}\nfunction IconExternalLink(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M12 6h-6a2 2 0 0 0 -2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-6\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 13l9 -9\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M15 4h5v5\" })\n ] });\n}\nfunction IconArrowBackUp(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M9 14l-4 -4l4 -4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M5 10h11a4 4 0 1 1 0 8h-1\" })\n ] });\n}\nfunction IconArrowForwardUp(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M15 14l4 -4l-4 -4\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M19 10h-11a4 4 0 1 0 0 8h1\" })\n ] });\n}\nfunction IconListCheck(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3.5 5.5l1.5 1.5l2.5 -2.5\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3.5 11.5l1.5 1.5l2.5 -2.5\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M3.5 17.5l1.5 1.5l2.5 -2.5\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 6l9 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 12l9 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M11 18l9 0\" })\n ] });\n}\nfunction IconIndentIncrease(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20 6l-11 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20 12l-7 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20 18l-11 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M4 8l4 4l-4 4\" })\n ] });\n}\nfunction IconIndentDecrease(props) {\n return /* @__PURE__ */ jsxs(IconBase, { ...props, children: [\n /* @__PURE__ */ jsx(\"path\", { stroke: \"none\", d: \"M0 0h24v24H0z\", fill: \"none\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20 6l-7 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20 12l-9 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M20 18l-7 0\" }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M8 8l-4 4l4 4\" })\n ] });\n}\n\nexport { IconAlignCenter, IconAlignJustified, IconAlignLeft, IconAlignRight, IconArrowBackUp, IconArrowForwardUp, IconBase, IconBlockquote, IconBold, IconCheck, IconCircleOff, IconClearFormatting, IconCode, IconColorPicker, IconExternalLink, IconH1, IconH2, IconH3, IconH4, IconH5, IconH6, IconHighlight, IconIndentDecrease, IconIndentIncrease, IconItalic, IconLineDashed, IconLink, IconList, IconListCheck, IconListNumbers, IconPalette, IconStrikethrough, IconSubscript, IconSuperscript, IconUnderline, IconUnlink, IconX };\n//# sourceMappingURL=Icons.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport { factory, useProps, UnstyledButton } from '@mantine/core';\nimport { useRichTextEditorContext } from '../RichTextEditor.context.mjs';\nimport classes from '../RichTextEditor.module.css.mjs';\n\nconst defaultProps = {\n interactive: true\n};\nconst RichTextEditorControl = factory((_props, ref) => {\n const props = useProps(\"RichTextEditorControl\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n vars,\n interactive,\n active,\n onMouseDown,\n disabled,\n ...others\n } = props;\n const ctx = useRichTextEditorContext();\n return /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ...others,\n ...ctx.getStyles(\"control\", { className, style, classNames, styles }),\n disabled,\n \"data-rich-text-editor-control\": true,\n tabIndex: interactive ? 0 : -1,\n \"data-interactive\": interactive || void 0,\n \"data-disabled\": disabled || void 0,\n \"data-active\": active || void 0,\n \"aria-pressed\": active && interactive || void 0,\n \"aria-hidden\": !interactive || void 0,\n ref,\n unstyled: ctx.unstyled,\n variant: ctx.variant || \"default\",\n onMouseDown: (event) => {\n event.preventDefault();\n onMouseDown?.(event);\n }\n }\n );\n});\nRichTextEditorControl.classes = classes;\nRichTextEditorControl.displayName = \"@mantine/tiptap/RichTextEditorControl\";\nconst RichTextEditorControlBase = forwardRef(({ className, icon: Icon, ...others }, ref) => {\n const ctx = useRichTextEditorContext();\n return /* @__PURE__ */ jsx(RichTextEditorControl, { ref, ...others, children: /* @__PURE__ */ jsx(Icon, { ...ctx.getStyles(\"controlIcon\") }) });\n});\nRichTextEditorControlBase.displayName = \"@mantine/tiptap/RichTextEditorControlBase\";\nfunction createControl({\n label,\n isActive,\n operation,\n icon,\n isDisabled\n}) {\n const Control = forwardRef((props, ref) => {\n const { editor, labels } = useRichTextEditorContext();\n const _label = labels[label];\n return /* @__PURE__ */ jsx(\n RichTextEditorControlBase,\n {\n ...props,\n \"aria-label\": _label,\n title: _label,\n active: isActive?.name ? editor?.isActive(isActive.name, isActive.attributes) : false,\n ref,\n onClick: () => editor?.chain().focus()[operation.name](operation.attributes).run(),\n icon: props.icon || icon,\n disabled: isDisabled?.(editor) || false\n }\n );\n });\n Control.displayName = `@mantine/tiptap/${label}`;\n return Control;\n}\n\nexport { RichTextEditorControl, RichTextEditorControlBase, createControl };\n//# sourceMappingURL=RichTextEditorControl.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { IconBold, IconItalic, IconUnderline, IconStrikethrough, IconClearFormatting, IconUnlink, IconList, IconListNumbers, IconH1, IconH2, IconH3, IconH4, IconH5, IconH6, IconBlockquote, IconAlignLeft, IconAlignRight, IconAlignCenter, IconAlignJustified, IconSubscript, IconSuperscript, IconCode, IconHighlight, IconLineDashed, IconCircleOff, IconArrowBackUp, IconArrowForwardUp, IconListCheck, IconIndentIncrease, IconIndentDecrease } from '../icons/Icons.mjs';\nimport { createControl } from './RichTextEditorControl.mjs';\n\nconst BoldControl = createControl({\n label: \"boldControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconBold, { ...props }),\n isActive: { name: \"bold\" },\n operation: { name: \"toggleBold\" }\n});\nconst ItalicControl = createControl({\n label: \"italicControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconItalic, { ...props }),\n isActive: { name: \"italic\" },\n operation: { name: \"toggleItalic\" }\n});\nconst UnderlineControl = createControl({\n label: \"underlineControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconUnderline, { ...props }),\n isActive: { name: \"underline\" },\n operation: { name: \"toggleUnderline\" }\n});\nconst StrikeThroughControl = createControl({\n label: \"strikeControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconStrikethrough, { ...props }),\n isActive: { name: \"strike\" },\n operation: { name: \"toggleStrike\" }\n});\nconst ClearFormattingControl = createControl({\n label: \"clearFormattingControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconClearFormatting, { ...props }),\n operation: { name: \"unsetAllMarks\" }\n});\nconst UnlinkControl = createControl({\n label: \"unlinkControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconUnlink, { ...props }),\n operation: { name: \"unsetLink\" }\n});\nconst BulletListControl = createControl({\n label: \"bulletListControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconList, { ...props }),\n isActive: { name: \"bulletList\" },\n operation: { name: \"toggleBulletList\" }\n});\nconst OrderedListControl = createControl({\n label: \"orderedListControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconListNumbers, { ...props }),\n isActive: { name: \"orderedList\" },\n operation: { name: \"toggleOrderedList\" }\n});\nconst H1Control = createControl({\n label: \"h1ControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconH1, { ...props }),\n isActive: { name: \"heading\", attributes: { level: 1 } },\n operation: { name: \"toggleHeading\", attributes: { level: 1 } }\n});\nconst H2Control = createControl({\n label: \"h2ControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconH2, { ...props }),\n isActive: { name: \"heading\", attributes: { level: 2 } },\n operation: { name: \"toggleHeading\", attributes: { level: 2 } }\n});\nconst H3Control = createControl({\n label: \"h3ControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconH3, { ...props }),\n isActive: { name: \"heading\", attributes: { level: 3 } },\n operation: { name: \"toggleHeading\", attributes: { level: 3 } }\n});\nconst H4Control = createControl({\n label: \"h4ControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconH4, { ...props }),\n isActive: { name: \"heading\", attributes: { level: 4 } },\n operation: { name: \"toggleHeading\", attributes: { level: 4 } }\n});\nconst H5Control = createControl({\n label: \"h5ControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconH5, { ...props }),\n isActive: { name: \"heading\", attributes: { level: 5 } },\n operation: { name: \"toggleHeading\", attributes: { level: 5 } }\n});\nconst H6Control = createControl({\n label: \"h6ControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconH6, { ...props }),\n isActive: { name: \"heading\", attributes: { level: 6 } },\n operation: { name: \"toggleHeading\", attributes: { level: 6 } }\n});\nconst BlockquoteControl = createControl({\n label: \"blockquoteControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconBlockquote, { ...props }),\n isActive: { name: \"blockquote\" },\n operation: { name: \"toggleBlockquote\" }\n});\nconst AlignLeftControl = createControl({\n label: \"alignLeftControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconAlignLeft, { ...props }),\n operation: { name: \"setTextAlign\", attributes: \"left\" }\n});\nconst AlignRightControl = createControl({\n label: \"alignRightControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconAlignRight, { ...props }),\n operation: { name: \"setTextAlign\", attributes: \"right\" }\n});\nconst AlignCenterControl = createControl({\n label: \"alignCenterControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconAlignCenter, { ...props }),\n operation: { name: \"setTextAlign\", attributes: \"center\" }\n});\nconst AlignJustifyControl = createControl({\n label: \"alignJustifyControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconAlignJustified, { ...props }),\n operation: { name: \"setTextAlign\", attributes: \"justify\" }\n});\nconst SubscriptControl = createControl({\n label: \"subscriptControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconSubscript, { ...props }),\n isActive: { name: \"subscript\" },\n operation: { name: \"toggleSubscript\" }\n});\nconst SuperscriptControl = createControl({\n label: \"superscriptControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconSuperscript, { ...props }),\n isActive: { name: \"superscript\" },\n operation: { name: \"toggleSuperscript\" }\n});\nconst CodeControl = createControl({\n label: \"codeControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconCode, { ...props }),\n isActive: { name: \"code\" },\n operation: { name: \"toggleCode\" }\n});\nconst CodeBlockControl = createControl({\n label: \"codeBlockControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconCode, { ...props }),\n isActive: { name: \"codeBlock\" },\n operation: { name: \"toggleCodeBlock\" }\n});\nconst HighlightControl = createControl({\n label: \"highlightControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconHighlight, { ...props }),\n isActive: { name: \"highlight\" },\n operation: { name: \"toggleHighlight\" }\n});\nconst HrControl = createControl({\n label: \"hrControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconLineDashed, { ...props }),\n operation: { name: \"setHorizontalRule\" }\n});\nconst UnsetColorControl = createControl({\n label: \"unsetColorControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconCircleOff, { ...props }),\n operation: { name: \"unsetColor\" }\n});\nconst UndoControl = createControl({\n label: \"undoControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconArrowBackUp, { ...props }),\n isDisabled: (editor) => !editor?.can().undo(),\n operation: { name: \"undo\" }\n});\nconst RedoControl = createControl({\n label: \"redoControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconArrowForwardUp, { ...props }),\n isDisabled: (editor) => !editor?.can().redo(),\n operation: { name: \"redo\" }\n});\nconst TaskListControl = createControl({\n label: \"tasksControlLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconListCheck, { ...props }),\n isActive: { name: \"taskList\" },\n operation: { name: \"toggleTaskList\" }\n});\nconst TaskListSinkControl = createControl({\n label: \"tasksSinkLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconIndentIncrease, { ...props }),\n operation: { name: \"sinkListItem\", attributes: \"taskItem\" },\n isDisabled: (editor) => !editor?.can().sinkListItem(\"taskItem\")\n});\nconst TaskListLiftControl = createControl({\n label: \"tasksLiftLabel\",\n icon: (props) => /* @__PURE__ */ jsx(IconIndentDecrease, { ...props }),\n operation: { name: \"liftListItem\", attributes: \"taskItem\" },\n isDisabled: (editor) => !editor?.can().liftListItem(\"taskItem\")\n});\n\nexport { AlignCenterControl, AlignJustifyControl, AlignLeftControl, AlignRightControl, BlockquoteControl, BoldControl, BulletListControl, ClearFormattingControl, CodeBlockControl, CodeControl, H1Control, H2Control, H3Control, H4Control, H5Control, H6Control, HighlightControl, HrControl, ItalicControl, OrderedListControl, RedoControl, StrikeThroughControl, SubscriptControl, SuperscriptControl, TaskListControl, TaskListLiftControl, TaskListSinkControl, UnderlineControl, UndoControl, UnlinkControl, UnsetColorControl };\n//# sourceMappingURL=controls.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { useState } from 'react';\nimport { factory, useProps, useResolvedStylesApi, Popover, TextInput, Tooltip, UnstyledButton, rem, Button } from '@mantine/core';\nimport { useInputState, useDisclosure, useWindowEvent } from '@mantine/hooks';\nimport { IconExternalLink, IconLink } from '../icons/Icons.mjs';\nimport { useRichTextEditorContext } from '../RichTextEditor.context.mjs';\nimport { RichTextEditorControlBase } from './RichTextEditorControl.mjs';\nimport classes from '../RichTextEditor.module.css.mjs';\n\nconst LinkIcon = (props) => /* @__PURE__ */ jsx(IconLink, { ...props });\nconst defaultProps = {};\nconst RichTextEditorLinkControl = factory(\n (_props, ref) => {\n const props = useProps(\"RichTextEditorLinkControl\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n vars,\n icon,\n popoverProps,\n disableTooltips,\n initialExternal,\n ...others\n } = props;\n const ctx = useRichTextEditorContext();\n const stylesApiProps = { classNames, styles };\n const [url, setUrl] = useInputState(\"\");\n const [external, setExternal] = useState(initialExternal);\n const [opened, { open, close }] = useDisclosure(false);\n const handleOpen = () => {\n open();\n const linkData = ctx.editor?.getAttributes(\"link\");\n setUrl(linkData?.href || \"\");\n setExternal(linkData?.href ? linkData?.target === \"_blank\" : initialExternal);\n };\n const handleClose = () => {\n close();\n setUrl(\"\");\n setExternal(initialExternal);\n };\n const setLink = () => {\n handleClose();\n url === \"\" ? ctx.editor?.chain().focus().extendMarkRange(\"link\").unsetLink().run() : ctx.editor?.chain().focus().extendMarkRange(\"link\").setLink({ href: url, target: external ? \"_blank\" : null }).run();\n };\n const handleInputKeydown = (event) => {\n if (event.key === \"Enter\") {\n event.preventDefault();\n setLink();\n }\n };\n useWindowEvent(\"edit-link\", handleOpen, false);\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({ classNames, styles, props });\n return /* @__PURE__ */ jsxs(\n Popover,\n {\n trapFocus: true,\n shadow: \"md\",\n withinPortal: true,\n opened,\n onChange: (_opened) => !_opened && handleClose(),\n offset: -44,\n zIndex: 1e4,\n ...popoverProps,\n children: [\n /* @__PURE__ */ jsx(Popover.Target, { children: /* @__PURE__ */ jsx(\n RichTextEditorControlBase,\n {\n icon: icon || LinkIcon,\n ...others,\n \"aria-label\": ctx.labels.linkControlLabel,\n title: ctx.labels.linkControlLabel,\n onClick: handleOpen,\n active: ctx.editor?.isActive(\"link\"),\n ref,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n className,\n style,\n variant: ctx.variant\n }\n ) }),\n /* @__PURE__ */ jsx(Popover.Dropdown, { ...ctx.getStyles(\"linkEditorDropdown\", stylesApiProps), children: /* @__PURE__ */ jsxs(\"div\", { ...ctx.getStyles(\"linkEditor\", stylesApiProps), children: [\n /* @__PURE__ */ jsx(\n TextInput,\n {\n placeholder: ctx.labels.linkEditorInputPlaceholder,\n \"aria-label\": ctx.labels.linkEditorInputLabel,\n type: \"url\",\n value: url,\n onChange: setUrl,\n classNames: { input: ctx.getStyles(\"linkEditorInput\", stylesApiProps).className },\n onKeyDown: handleInputKeydown,\n rightSection: /* @__PURE__ */ jsx(\n Tooltip,\n {\n label: external ? ctx.labels.linkEditorExternalLink : ctx.labels.linkEditorInternalLink,\n events: { hover: true, focus: true, touch: true },\n withinPortal: true,\n withArrow: true,\n disabled: disableTooltips,\n zIndex: 1e4,\n children: /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n onClick: () => setExternal((e) => !e),\n \"data-active\": external || void 0,\n ...ctx.getStyles(\"linkEditorExternalControl\", stylesApiProps),\n children: /* @__PURE__ */ jsx(IconExternalLink, { style: { width: rem(14), height: rem(14) } })\n }\n )\n }\n )\n }\n ),\n /* @__PURE__ */ jsx(\n Button,\n {\n variant: \"default\",\n onClick: setLink,\n ...ctx.getStyles(\"linkEditorSave\", stylesApiProps),\n children: ctx.labels.linkEditorSave\n }\n )\n ] }) })\n ]\n }\n );\n }\n);\nRichTextEditorLinkControl.classes = classes;\nRichTextEditorLinkControl.displayName = \"@mantine/tiptap/RichTextEditorLinkControl\";\n\nexport { RichTextEditorLinkControl };\n//# sourceMappingURL=RichTextEditorLinkControl.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { forwardRef, useState } from 'react';\nimport { useProps, ColorSwatch, Popover, SimpleGrid, ColorPicker, Tooltip, Group, ActionIcon, rem } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { IconX, IconCircleOff, IconColorPicker, IconPalette, IconCheck } from '../icons/Icons.mjs';\nimport { useRichTextEditorContext } from '../RichTextEditor.context.mjs';\nimport { RichTextEditorControl } from './RichTextEditorControl.mjs';\n\nconst defaultProps = {};\nconst RichTextEditorColorPickerControl = forwardRef((props, ref) => {\n const { popoverProps, colors, colorPickerProps, ...others } = useProps(\n \"RichTextEditorColorPickerControl\",\n defaultProps,\n props\n );\n const { editor, labels, getStyles, variant } = useRichTextEditorContext();\n const [opened, { toggle, close }] = useDisclosure(false);\n const [state, setState] = useState(\"palette\");\n const currentColor = editor?.getAttributes(\"textStyle\").color || \"var(--mantine-color-text)\";\n const handleChange = (value, shouldClose = true) => {\n (editor?.chain()).focus().setColor(value).run();\n shouldClose && close();\n };\n const handleClear = () => {\n (editor?.chain()).focus().unsetColor().run();\n close();\n };\n const controls = colors.map((color, index) => /* @__PURE__ */ jsx(\n ColorSwatch,\n {\n component: \"button\",\n color,\n onClick: () => handleChange(color),\n size: 26,\n radius: \"xs\",\n style: { cursor: \"pointer\" },\n title: labels.colorPickerColorLabel(color),\n \"aria-label\": labels.colorPickerColorLabel(color)\n },\n index\n ));\n return /* @__PURE__ */ jsxs(\n Popover,\n {\n opened,\n withinPortal: true,\n trapFocus: true,\n onChange: (_opened) => !_opened && close(),\n ...popoverProps,\n children: [\n /* @__PURE__ */ jsx(Popover.Target, { children: /* @__PURE__ */ jsx(\n RichTextEditorControl,\n {\n ...others,\n variant,\n \"aria-label\": labels.colorPickerControlLabel,\n title: labels.colorPickerControlLabel,\n ref,\n onClick: toggle,\n children: /* @__PURE__ */ jsx(ColorSwatch, { color: currentColor, size: 14 })\n }\n ) }),\n /* @__PURE__ */ jsxs(Popover.Dropdown, { ...getStyles(\"linkEditorDropdown\"), children: [\n state === \"palette\" && /* @__PURE__ */ jsx(SimpleGrid, { cols: 7, spacing: 2, children: controls }),\n state === \"colorPicker\" && /* @__PURE__ */ jsx(\n ColorPicker,\n {\n defaultValue: currentColor,\n onChange: (value) => handleChange(value, false),\n ...colorPickerProps\n }\n ),\n /* @__PURE__ */ jsx(Tooltip.Group, { closeDelay: 200, children: /* @__PURE__ */ jsxs(Group, { justify: \"flex-end\", gap: \"xs\", mt: \"sm\", children: [\n state === \"palette\" && /* @__PURE__ */ jsx(\n ActionIcon,\n {\n variant: \"default\",\n onClick: close,\n title: labels.colorPickerCancel,\n \"aria-label\": labels.colorPickerCancel,\n children: /* @__PURE__ */ jsx(IconX, { style: { width: rem(16), height: rem(16) } })\n }\n ),\n /* @__PURE__ */ jsx(\n ActionIcon,\n {\n variant: \"default\",\n onClick: handleClear,\n title: labels.colorPickerClear,\n \"aria-label\": labels.colorPickerClear,\n children: /* @__PURE__ */ jsx(IconCircleOff, { style: { width: rem(16), height: rem(16) } })\n }\n ),\n state === \"palette\" ? /* @__PURE__ */ jsx(\n ActionIcon,\n {\n variant: \"default\",\n onClick: () => setState(\"colorPicker\"),\n title: labels.colorPickerColorPicker,\n \"aria-label\": labels.colorPickerColorPicker,\n children: /* @__PURE__ */ jsx(IconColorPicker, { style: { width: rem(16), height: rem(16) } })\n }\n ) : /* @__PURE__ */ jsx(\n ActionIcon,\n {\n variant: \"default\",\n onClick: () => setState(\"palette\"),\n \"aria-label\": labels.colorPickerPalette,\n title: labels.colorPickerPalette,\n children: /* @__PURE__ */ jsx(IconPalette, { style: { width: rem(16), height: rem(16) } })\n }\n ),\n state === \"colorPicker\" && /* @__PURE__ */ jsx(\n ActionIcon,\n {\n variant: \"default\",\n onClick: close,\n title: labels.colorPickerSave,\n \"aria-label\": labels.colorPickerSave,\n children: /* @__PURE__ */ jsx(IconCheck, { style: { width: rem(16), height: rem(16) } })\n }\n )\n ] }) })\n ] })\n ]\n }\n );\n});\nRichTextEditorColorPickerControl.displayName = \"@mantine/tiptap/ColorPickerControl\";\n\nexport { RichTextEditorColorPickerControl };\n//# sourceMappingURL=RichTextEditorColorPickerControl.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { forwardRef } from 'react';\nimport { useProps, ColorSwatch } from '@mantine/core';\nimport { useRichTextEditorContext } from '../RichTextEditor.context.mjs';\nimport { RichTextEditorControl } from './RichTextEditorControl.mjs';\n\nconst defaultProps = {};\nconst RichTextEditorColorControl = forwardRef((props, ref) => {\n const { color, ...others } = useProps(\"RichTextEditorColorControl\", defaultProps, props);\n const { editor, labels, variant } = useRichTextEditorContext();\n const currentColor = editor?.getAttributes(\"textStyle\").color || null;\n const label = labels.colorControlLabel(color);\n return /* @__PURE__ */ jsx(\n RichTextEditorControl,\n {\n ...others,\n variant,\n active: currentColor === color,\n \"aria-label\": label,\n title: label,\n onClick: () => (editor?.chain()).focus().setColor(color).run(),\n ref,\n children: /* @__PURE__ */ jsx(ColorSwatch, { color, size: 14 })\n }\n );\n});\nRichTextEditorColorControl.displayName = \"@mantine/tiptap/RichTextEditorColorControl\";\n\nexport { RichTextEditorColorControl };\n//# sourceMappingURL=RichTextEditorColorControl.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { factory, useProps, Box } from '@mantine/core';\nimport { useRichTextEditorContext } from '../RichTextEditor.context.mjs';\nimport classes from '../RichTextEditor.module.css.mjs';\n\nconst defaultProps = {};\nconst RichTextEditorControlsGroup = factory(\n (_props, ref) => {\n const props = useProps(\"RichTextEditorControlsGroup\", defaultProps, _props);\n const { classNames, className, style, styles, vars, variant, ...others } = props;\n const ctx = useRichTextEditorContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n variant: variant || ctx.variant,\n ...ctx.getStyles(\"controlsGroup\", { className, style, styles, classNames }),\n ...others\n }\n );\n }\n);\nRichTextEditorControlsGroup.classes = classes;\nRichTextEditorControlsGroup.displayName = \"@mantine/tiptap/RichTextEditorControlsGroup\";\n\nexport { RichTextEditorControlsGroup };\n//# sourceMappingURL=RichTextEditorControlsGroup.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { factory, useProps, Box, rem } from '@mantine/core';\nimport { useRichTextEditorContext } from '../RichTextEditor.context.mjs';\nimport classes from '../RichTextEditor.module.css.mjs';\n\nconst defaultProps = {};\nconst RichTextEditorToolbar = factory((_props, ref) => {\n const props = useProps(\"RichTextEditorToolbar\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n vars,\n sticky,\n stickyOffset,\n mod,\n variant,\n ...others\n } = props;\n const ctx = useRichTextEditorContext();\n return /* @__PURE__ */ jsx(\n Box,\n {\n ref,\n mod: [{ sticky }, mod],\n variant: variant || ctx.variant,\n ...ctx.getStyles(\"toolbar\", { className, style, styles, classNames }),\n ...others,\n __vars: { \"--rte-sticky-offset\": rem(stickyOffset) }\n }\n );\n});\nRichTextEditorToolbar.classes = classes;\nRichTextEditorToolbar.displayName = \"@mantine/tiptap/RichTextEditorToolbar\";\n\nexport { RichTextEditorToolbar };\n//# sourceMappingURL=RichTextEditorToolbar.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useMemo } from 'react';\nimport { factory, useProps, useStyles, Box } from '@mantine/core';\nimport { DEFAULT_LABELS } from './labels.mjs';\nimport { RichTextEditorProvider } from './RichTextEditor.context.mjs';\nimport { RichTextEditorContent } from './RichTextEditorContent/RichTextEditorContent.mjs';\nimport { BoldControl, ItalicControl, StrikeThroughControl, UnderlineControl, ClearFormattingControl, H1Control, H2Control, H3Control, H4Control, H5Control, H6Control, BulletListControl, OrderedListControl, UnlinkControl, BlockquoteControl, AlignLeftControl, AlignRightControl, AlignCenterControl, AlignJustifyControl, SuperscriptControl, SubscriptControl, CodeControl, CodeBlockControl, HighlightControl, HrControl, UnsetColorControl, UndoControl, RedoControl, TaskListControl, TaskListSinkControl, TaskListLiftControl } from './RichTextEditorControl/controls.mjs';\nimport { RichTextEditorLinkControl } from './RichTextEditorControl/RichTextEditorLinkControl.mjs';\nimport { RichTextEditorColorPickerControl } from './RichTextEditorControl/RichTextEditorColorPickerControl.mjs';\nimport { RichTextEditorColorControl } from './RichTextEditorControl/RichTextEditorColorControl.mjs';\nimport { RichTextEditorControl } from './RichTextEditorControl/RichTextEditorControl.mjs';\nimport { RichTextEditorControlsGroup } from './RichTextEditorControlsGroup/RichTextEditorControlsGroup.mjs';\nimport { RichTextEditorToolbar } from './RichTextEditorToolbar/RichTextEditorToolbar.mjs';\nimport classes from './RichTextEditor.module.css.mjs';\n\nconst defaultProps = {\n withCodeHighlightStyles: true,\n withTypographyStyles: true,\n variant: \"default\"\n};\nconst RichTextEditor = factory((_props, ref) => {\n const props = useProps(\"RichTextEditor\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n editor,\n withCodeHighlightStyles,\n withTypographyStyles,\n labels,\n children,\n variant,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"RichTextEditor\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars\n });\n const mergedLabels = useMemo(() => ({ ...DEFAULT_LABELS, ...labels }), [labels]);\n return /* @__PURE__ */ jsx(\n RichTextEditorProvider,\n {\n value: {\n editor,\n getStyles,\n labels: mergedLabels,\n withCodeHighlightStyles,\n withTypographyStyles,\n unstyled,\n variant\n },\n children: /* @__PURE__ */ jsx(Box, { ...getStyles(\"root\"), ...others, ref, children })\n }\n );\n});\nRichTextEditor.classes = classes;\nRichTextEditor.displayName = \"@mantine/tiptap/RichTextEditor\";\nRichTextEditor.Content = RichTextEditorContent;\nRichTextEditor.Control = RichTextEditorControl;\nRichTextEditor.Toolbar = RichTextEditorToolbar;\nRichTextEditor.ControlsGroup = RichTextEditorControlsGroup;\nRichTextEditor.Bold = BoldControl;\nRichTextEditor.Italic = ItalicControl;\nRichTextEditor.Strikethrough = StrikeThroughControl;\nRichTextEditor.Underline = UnderlineControl;\nRichTextEditor.ClearFormatting = ClearFormattingControl;\nRichTextEditor.H1 = H1Control;\nRichTextEditor.H2 = H2Control;\nRichTextEditor.H3 = H3Control;\nRichTextEditor.H4 = H4Control;\nRichTextEditor.H5 = H5Control;\nRichTextEditor.H6 = H6Control;\nRichTextEditor.BulletList = BulletListControl;\nRichTextEditor.OrderedList = OrderedListControl;\nRichTextEditor.Link = RichTextEditorLinkControl;\nRichTextEditor.Unlink = UnlinkControl;\nRichTextEditor.Blockquote = BlockquoteControl;\nRichTextEditor.AlignLeft = AlignLeftControl;\nRichTextEditor.AlignRight = AlignRightControl;\nRichTextEditor.AlignCenter = AlignCenterControl;\nRichTextEditor.AlignJustify = AlignJustifyControl;\nRichTextEditor.Superscript = SuperscriptControl;\nRichTextEditor.Subscript = SubscriptControl;\nRichTextEditor.Code = CodeControl;\nRichTextEditor.CodeBlock = CodeBlockControl;\nRichTextEditor.ColorPicker = RichTextEditorColorPickerControl;\nRichTextEditor.Color = RichTextEditorColorControl;\nRichTextEditor.Highlight = HighlightControl;\nRichTextEditor.Hr = HrControl;\nRichTextEditor.UnsetColor = UnsetColorControl;\nRichTextEditor.Undo = UndoControl;\nRichTextEditor.Redo = RedoControl;\nRichTextEditor.TaskList = TaskListControl;\nRichTextEditor.TaskListSink = TaskListSinkControl;\nRichTextEditor.TaskListLift = TaskListLiftControl;\n\nexport { RichTextEditor };\n//# sourceMappingURL=RichTextEditor.mjs.map\n","import { Mark, mergeAttributes, markInputRule, markPasteRule } from '@tiptap/core';\n\n/**\n * Matches a highlight to a ==highlight== on input.\n */\nconst inputRegex = /(?:^|\\s)(==(?!\\s+==)((?:[^=]+))==(?!\\s+==))$/;\n/**\n * Matches a highlight to a ==highlight== on paste.\n */\nconst pasteRegex = /(?:^|\\s)(==(?!\\s+==)((?:[^=]+))==(?!\\s+==))/g;\n/**\n * This extension allows you to highlight text.\n * @see https://www.tiptap.dev/api/marks/highlight\n */\nconst Highlight = Mark.create({\n name: 'highlight',\n addOptions() {\n return {\n multicolor: false,\n HTMLAttributes: {},\n };\n },\n addAttributes() {\n if (!this.options.multicolor) {\n return {};\n }\n return {\n color: {\n default: null,\n parseHTML: element => element.getAttribute('data-color') || element.style.backgroundColor,\n renderHTML: attributes => {\n if (!attributes.color) {\n return {};\n }\n return {\n 'data-color': attributes.color,\n style: `background-color: ${attributes.color}; color: inherit`,\n };\n },\n },\n };\n },\n parseHTML() {\n return [\n {\n tag: 'mark',\n },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['mark', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setHighlight: attributes => ({ commands }) => {\n return commands.setMark(this.name, attributes);\n },\n toggleHighlight: attributes => ({ commands }) => {\n return commands.toggleMark(this.name, attributes);\n },\n unsetHighlight: () => ({ commands }) => {\n return commands.unsetMark(this.name);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-h': () => this.editor.commands.toggleHighlight(),\n };\n },\n addInputRules() {\n return [\n markInputRule({\n find: inputRegex,\n type: this.type,\n }),\n ];\n },\n addPasteRules() {\n return [\n markPasteRule({\n find: pasteRegex,\n type: this.type,\n }),\n ];\n },\n});\n\nexport { Highlight, Highlight as default, inputRegex, pasteRegex };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes, wrappingInputRule } from '@tiptap/core';\n\n/**\n * Matches a blockquote to a `>` as input.\n */\nconst inputRegex = /^\\s*>\\s$/;\n/**\n * This extension allows you to create blockquotes.\n * @see https://tiptap.dev/api/nodes/blockquote\n */\nconst Blockquote = Node.create({\n name: 'blockquote',\n addOptions() {\n return {\n HTMLAttributes: {},\n };\n },\n content: 'block+',\n group: 'block',\n defining: true,\n parseHTML() {\n return [\n { tag: 'blockquote' },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['blockquote', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setBlockquote: () => ({ commands }) => {\n return commands.wrapIn(this.name);\n },\n toggleBlockquote: () => ({ commands }) => {\n return commands.toggleWrap(this.name);\n },\n unsetBlockquote: () => ({ commands }) => {\n return commands.lift(this.name);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-b': () => this.editor.commands.toggleBlockquote(),\n };\n },\n addInputRules() {\n return [\n wrappingInputRule({\n find: inputRegex,\n type: this.type,\n }),\n ];\n },\n});\n\nexport { Blockquote, Blockquote as default, inputRegex };\n//# sourceMappingURL=index.js.map\n","import { Mark, mergeAttributes, markInputRule, markPasteRule } from '@tiptap/core';\n\n/**\n * Matches bold text via `**` as input.\n */\nconst starInputRegex = /(?:^|\\s)(\\*\\*(?!\\s+\\*\\*)((?:[^*]+))\\*\\*(?!\\s+\\*\\*))$/;\n/**\n * Matches bold text via `**` while pasting.\n */\nconst starPasteRegex = /(?:^|\\s)(\\*\\*(?!\\s+\\*\\*)((?:[^*]+))\\*\\*(?!\\s+\\*\\*))/g;\n/**\n * Matches bold text via `__` as input.\n */\nconst underscoreInputRegex = /(?:^|\\s)(__(?!\\s+__)((?:[^_]+))__(?!\\s+__))$/;\n/**\n * Matches bold text via `__` while pasting.\n */\nconst underscorePasteRegex = /(?:^|\\s)(__(?!\\s+__)((?:[^_]+))__(?!\\s+__))/g;\n/**\n * This extension allows you to mark text as bold.\n * @see https://tiptap.dev/api/marks/bold\n */\nconst Bold = Mark.create({\n name: 'bold',\n addOptions() {\n return {\n HTMLAttributes: {},\n };\n },\n parseHTML() {\n return [\n {\n tag: 'strong',\n },\n {\n tag: 'b',\n getAttrs: node => node.style.fontWeight !== 'normal' && null,\n },\n {\n style: 'font-weight=400',\n clearMark: mark => mark.type.name === this.name,\n },\n {\n style: 'font-weight',\n getAttrs: value => /^(bold(er)?|[5-9]\\d{2,})$/.test(value) && null,\n },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['strong', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setBold: () => ({ commands }) => {\n return commands.setMark(this.name);\n },\n toggleBold: () => ({ commands }) => {\n return commands.toggleMark(this.name);\n },\n unsetBold: () => ({ commands }) => {\n return commands.unsetMark(this.name);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-b': () => this.editor.commands.toggleBold(),\n 'Mod-B': () => this.editor.commands.toggleBold(),\n };\n },\n addInputRules() {\n return [\n markInputRule({\n find: starInputRegex,\n type: this.type,\n }),\n markInputRule({\n find: underscoreInputRegex,\n type: this.type,\n }),\n ];\n },\n addPasteRules() {\n return [\n markPasteRule({\n find: starPasteRegex,\n type: this.type,\n }),\n markPasteRule({\n find: underscorePasteRegex,\n type: this.type,\n }),\n ];\n },\n});\n\nexport { Bold, Bold as default, starInputRegex, starPasteRegex, underscoreInputRegex, underscorePasteRegex };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes, wrappingInputRule } from '@tiptap/core';\n\nconst ListItemName = 'listItem';\nconst TextStyleName = 'textStyle';\n/**\n * Matches a bullet list to a dash or asterisk.\n */\nconst inputRegex = /^\\s*([-+*])\\s$/;\n/**\n * This extension allows you to create bullet lists.\n * This requires the ListItem extension\n * @see https://tiptap.dev/api/nodes/bullet-list\n * @see https://tiptap.dev/api/nodes/list-item.\n */\nconst BulletList = Node.create({\n name: 'bulletList',\n addOptions() {\n return {\n itemTypeName: 'listItem',\n HTMLAttributes: {},\n keepMarks: false,\n keepAttributes: false,\n };\n },\n group: 'block list',\n content() {\n return `${this.options.itemTypeName}+`;\n },\n parseHTML() {\n return [\n { tag: 'ul' },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['ul', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n toggleBulletList: () => ({ commands, chain }) => {\n if (this.options.keepAttributes) {\n return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run();\n }\n return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-8': () => this.editor.commands.toggleBulletList(),\n };\n },\n addInputRules() {\n let inputRule = wrappingInputRule({\n find: inputRegex,\n type: this.type,\n });\n if (this.options.keepMarks || this.options.keepAttributes) {\n inputRule = wrappingInputRule({\n find: inputRegex,\n type: this.type,\n keepMarks: this.options.keepMarks,\n keepAttributes: this.options.keepAttributes,\n getAttributes: () => { return this.editor.getAttributes(TextStyleName); },\n editor: this.editor,\n });\n }\n return [\n inputRule,\n ];\n },\n});\n\nexport { BulletList, BulletList as default, inputRegex };\n//# sourceMappingURL=index.js.map\n","import { Mark, mergeAttributes, markInputRule, markPasteRule } from '@tiptap/core';\n\n/**\n * Regular expressions to match inline code blocks enclosed in backticks.\n * It matches:\n * - An opening backtick, followed by\n * - Any text that doesn't include a backtick (captured for marking), followed by\n * - A closing backtick.\n * This ensures that any text between backticks is formatted as code,\n * regardless of the surrounding characters (exception being another backtick).\n */\nconst inputRegex = /(^|[^`])`([^`]+)`(?!`)/;\n/**\n * Matches inline code while pasting.\n */\nconst pasteRegex = /(^|[^`])`([^`]+)`(?!`)/g;\n/**\n * This extension allows you to mark text as inline code.\n * @see https://tiptap.dev/api/marks/code\n */\nconst Code = Mark.create({\n name: 'code',\n addOptions() {\n return {\n HTMLAttributes: {},\n };\n },\n excludes: '_',\n code: true,\n exitable: true,\n parseHTML() {\n return [\n { tag: 'code' },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['code', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setCode: () => ({ commands }) => {\n return commands.setMark(this.name);\n },\n toggleCode: () => ({ commands }) => {\n return commands.toggleMark(this.name);\n },\n unsetCode: () => ({ commands }) => {\n return commands.unsetMark(this.name);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-e': () => this.editor.commands.toggleCode(),\n };\n },\n addInputRules() {\n return [\n markInputRule({\n find: inputRegex,\n type: this.type,\n }),\n ];\n },\n addPasteRules() {\n return [\n markPasteRule({\n find: pasteRegex,\n type: this.type,\n }),\n ];\n },\n});\n\nexport { Code, Code as default, inputRegex, pasteRegex };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes, textblockTypeInputRule } from '@tiptap/core';\nimport { Selection, Plugin, PluginKey, TextSelection } from '@tiptap/pm/state';\n\n/**\n * Matches a code block with backticks.\n */\nconst backtickInputRegex = /^```([a-z]+)?[\\s\\n]$/;\n/**\n * Matches a code block with tildes.\n */\nconst tildeInputRegex = /^~~~([a-z]+)?[\\s\\n]$/;\n/**\n * This extension allows you to create code blocks.\n * @see https://tiptap.dev/api/nodes/code-block\n */\nconst CodeBlock = Node.create({\n name: 'codeBlock',\n addOptions() {\n return {\n languageClassPrefix: 'language-',\n exitOnTripleEnter: true,\n exitOnArrowDown: true,\n defaultLanguage: null,\n HTMLAttributes: {},\n };\n },\n content: 'text*',\n marks: '',\n group: 'block',\n code: true,\n defining: true,\n addAttributes() {\n return {\n language: {\n default: this.options.defaultLanguage,\n parseHTML: element => {\n var _a;\n const { languageClassPrefix } = this.options;\n const classNames = [...(((_a = element.firstElementChild) === null || _a === void 0 ? void 0 : _a.classList) || [])];\n const languages = classNames\n .filter(className => className.startsWith(languageClassPrefix))\n .map(className => className.replace(languageClassPrefix, ''));\n const language = languages[0];\n if (!language) {\n return null;\n }\n return language;\n },\n rendered: false,\n },\n };\n },\n parseHTML() {\n return [\n {\n tag: 'pre',\n preserveWhitespace: 'full',\n },\n ];\n },\n renderHTML({ node, HTMLAttributes }) {\n return [\n 'pre',\n mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),\n [\n 'code',\n {\n class: node.attrs.language\n ? this.options.languageClassPrefix + node.attrs.language\n : null,\n },\n 0,\n ],\n ];\n },\n addCommands() {\n return {\n setCodeBlock: attributes => ({ commands }) => {\n return commands.setNode(this.name, attributes);\n },\n toggleCodeBlock: attributes => ({ commands }) => {\n return commands.toggleNode(this.name, 'paragraph', attributes);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Alt-c': () => this.editor.commands.toggleCodeBlock(),\n // remove code block when at start of document or code block is empty\n Backspace: () => {\n const { empty, $anchor } = this.editor.state.selection;\n const isAtStart = $anchor.pos === 1;\n if (!empty || $anchor.parent.type.name !== this.name) {\n return false;\n }\n if (isAtStart || !$anchor.parent.textContent.length) {\n return this.editor.commands.clearNodes();\n }\n return false;\n },\n // exit node on triple enter\n Enter: ({ editor }) => {\n if (!this.options.exitOnTripleEnter) {\n return false;\n }\n const { state } = editor;\n const { selection } = state;\n const { $from, empty } = selection;\n if (!empty || $from.parent.type !== this.type) {\n return false;\n }\n const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;\n const endsWithDoubleNewline = $from.parent.textContent.endsWith('\\n\\n');\n if (!isAtEnd || !endsWithDoubleNewline) {\n return false;\n }\n return editor\n .chain()\n .command(({ tr }) => {\n tr.delete($from.pos - 2, $from.pos);\n return true;\n })\n .exitCode()\n .run();\n },\n // exit node on arrow down\n ArrowDown: ({ editor }) => {\n if (!this.options.exitOnArrowDown) {\n return false;\n }\n const { state } = editor;\n const { selection, doc } = state;\n const { $from, empty } = selection;\n if (!empty || $from.parent.type !== this.type) {\n return false;\n }\n const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;\n if (!isAtEnd) {\n return false;\n }\n const after = $from.after();\n if (after === undefined) {\n return false;\n }\n const nodeAfter = doc.nodeAt(after);\n if (nodeAfter) {\n return editor.commands.command(({ tr }) => {\n tr.setSelection(Selection.near(doc.resolve(after)));\n return true;\n });\n }\n return editor.commands.exitCode();\n },\n };\n },\n addInputRules() {\n return [\n textblockTypeInputRule({\n find: backtickInputRegex,\n type: this.type,\n getAttributes: match => ({\n language: match[1],\n }),\n }),\n textblockTypeInputRule({\n find: tildeInputRegex,\n type: this.type,\n getAttributes: match => ({\n language: match[1],\n }),\n }),\n ];\n },\n addProseMirrorPlugins() {\n return [\n // this plugin creates a code block for pasted content from VS Code\n // we can also detect the copied code language\n new Plugin({\n key: new PluginKey('codeBlockVSCodeHandler'),\n props: {\n handlePaste: (view, event) => {\n if (!event.clipboardData) {\n return false;\n }\n // don’t create a new code block within code blocks\n if (this.editor.isActive(this.type.name)) {\n return false;\n }\n const text = event.clipboardData.getData('text/plain');\n const vscode = event.clipboardData.getData('vscode-editor-data');\n const vscodeData = vscode ? JSON.parse(vscode) : undefined;\n const language = vscodeData === null || vscodeData === void 0 ? void 0 : vscodeData.mode;\n if (!text || !language) {\n return false;\n }\n const { tr, schema } = view.state;\n // prepare a text node\n // strip carriage return chars from text pasted as code\n // see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd\n const textNode = schema.text(text.replace(/\\r\\n?/g, '\\n'));\n // create a code block with the text node\n // replace selection with the code block\n tr.replaceSelectionWith(this.type.create({ language }, textNode));\n if (tr.selection.$from.parent.type !== this.type) {\n // put cursor inside the newly created code block\n tr.setSelection(TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))));\n }\n // store meta information\n // this is useful for other plugins that depends on the paste event\n // like the paste rule plugin\n tr.setMeta('paste', true);\n view.dispatch(tr);\n return true;\n },\n },\n }),\n ];\n },\n});\n\nexport { CodeBlock, backtickInputRegex, CodeBlock as default, tildeInputRegex };\n//# sourceMappingURL=index.js.map\n","import { Node } from '@tiptap/core';\n\n/**\n * The default document node which represents the top level node of the editor.\n * @see https://tiptap.dev/api/nodes/document\n */\nconst Document = Node.create({\n name: 'doc',\n topNode: true,\n content: 'block+',\n});\n\nexport { Document, Document as default };\n//# sourceMappingURL=index.js.map\n","import { Plugin } from 'prosemirror-state';\nimport { dropPoint } from 'prosemirror-transform';\n\n/**\nCreate a plugin that, when added to a ProseMirror instance,\ncauses a decoration to show up at the drop position when something\nis dragged over the editor.\n\nNodes may add a `disableDropCursor` property to their spec to\ncontrol the showing of a drop cursor inside them. This may be a\nboolean or a function, which will be called with a view and a\nposition, and should return a boolean.\n*/\nfunction dropCursor(options = {}) {\n return new Plugin({\n view(editorView) { return new DropCursorView(editorView, options); }\n });\n}\nclass DropCursorView {\n constructor(editorView, options) {\n var _a;\n this.editorView = editorView;\n this.cursorPos = null;\n this.element = null;\n this.timeout = -1;\n this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1;\n this.color = options.color === false ? undefined : (options.color || \"black\");\n this.class = options.class;\n this.handlers = [\"dragover\", \"dragend\", \"drop\", \"dragleave\"].map(name => {\n let handler = (e) => { this[name](e); };\n editorView.dom.addEventListener(name, handler);\n return { name, handler };\n });\n }\n destroy() {\n this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler));\n }\n update(editorView, prevState) {\n if (this.cursorPos != null && prevState.doc != editorView.state.doc) {\n if (this.cursorPos > editorView.state.doc.content.size)\n this.setCursor(null);\n else\n this.updateOverlay();\n }\n }\n setCursor(pos) {\n if (pos == this.cursorPos)\n return;\n this.cursorPos = pos;\n if (pos == null) {\n this.element.parentNode.removeChild(this.element);\n this.element = null;\n }\n else {\n this.updateOverlay();\n }\n }\n updateOverlay() {\n let $pos = this.editorView.state.doc.resolve(this.cursorPos);\n let isBlock = !$pos.parent.inlineContent, rect;\n if (isBlock) {\n let before = $pos.nodeBefore, after = $pos.nodeAfter;\n if (before || after) {\n let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));\n if (node) {\n let nodeRect = node.getBoundingClientRect();\n let top = before ? nodeRect.bottom : nodeRect.top;\n if (before && after)\n top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;\n rect = { left: nodeRect.left, right: nodeRect.right, top: top - this.width / 2, bottom: top + this.width / 2 };\n }\n }\n }\n if (!rect) {\n let coords = this.editorView.coordsAtPos(this.cursorPos);\n rect = { left: coords.left - this.width / 2, right: coords.left + this.width / 2, top: coords.top, bottom: coords.bottom };\n }\n let parent = this.editorView.dom.offsetParent;\n if (!this.element) {\n this.element = parent.appendChild(document.createElement(\"div\"));\n if (this.class)\n this.element.className = this.class;\n this.element.style.cssText = \"position: absolute; z-index: 50; pointer-events: none;\";\n if (this.color) {\n this.element.style.backgroundColor = this.color;\n }\n }\n this.element.classList.toggle(\"prosemirror-dropcursor-block\", isBlock);\n this.element.classList.toggle(\"prosemirror-dropcursor-inline\", !isBlock);\n let parentLeft, parentTop;\n if (!parent || parent == document.body && getComputedStyle(parent).position == \"static\") {\n parentLeft = -pageXOffset;\n parentTop = -pageYOffset;\n }\n else {\n let rect = parent.getBoundingClientRect();\n parentLeft = rect.left - parent.scrollLeft;\n parentTop = rect.top - parent.scrollTop;\n }\n this.element.style.left = (rect.left - parentLeft) + \"px\";\n this.element.style.top = (rect.top - parentTop) + \"px\";\n this.element.style.width = (rect.right - rect.left) + \"px\";\n this.element.style.height = (rect.bottom - rect.top) + \"px\";\n }\n scheduleRemoval(timeout) {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(() => this.setCursor(null), timeout);\n }\n dragover(event) {\n if (!this.editorView.editable)\n return;\n let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });\n let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);\n let disableDropCursor = node && node.type.spec.disableDropCursor;\n let disabled = typeof disableDropCursor == \"function\" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor;\n if (pos && !disabled) {\n let target = pos.pos;\n if (this.editorView.dragging && this.editorView.dragging.slice) {\n let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);\n if (point != null)\n target = point;\n }\n this.setCursor(target);\n this.scheduleRemoval(5000);\n }\n }\n dragend() {\n this.scheduleRemoval(20);\n }\n drop() {\n this.scheduleRemoval(20);\n }\n dragleave(event) {\n if (event.target == this.editorView.dom || !this.editorView.dom.contains(event.relatedTarget))\n this.setCursor(null);\n }\n}\n\nexport { dropCursor };\n","import { Extension } from '@tiptap/core';\nimport { dropCursor } from '@tiptap/pm/dropcursor';\n\n/**\n * This extension allows you to add a drop cursor to your editor.\n * A drop cursor is a line that appears when you drag and drop content\n * inbetween nodes.\n * @see https://tiptap.dev/api/extensions/dropcursor\n */\nconst Dropcursor = Extension.create({\n name: 'dropCursor',\n addOptions() {\n return {\n color: 'currentColor',\n width: 1,\n class: undefined,\n };\n },\n addProseMirrorPlugins() {\n return [\n dropCursor(this.options),\n ];\n },\n});\n\nexport { Dropcursor, Dropcursor as default };\n//# sourceMappingURL=index.js.map\n","import { keydownHandler } from 'prosemirror-keymap';\nimport { Selection, NodeSelection, TextSelection, Plugin } from 'prosemirror-state';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { DecorationSet, Decoration } from 'prosemirror-view';\n\n/**\nGap cursor selections are represented using this class. Its\n`$anchor` and `$head` properties both point at the cursor position.\n*/\nclass GapCursor extends Selection {\n /**\n Create a gap cursor.\n */\n constructor($pos) {\n super($pos, $pos);\n }\n map(doc, mapping) {\n let $pos = doc.resolve(mapping.map(this.head));\n return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n }\n content() { return Slice.empty; }\n eq(other) {\n return other instanceof GapCursor && other.head == this.head;\n }\n toJSON() {\n return { type: \"gapcursor\", pos: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for GapCursor.fromJSON\");\n return new GapCursor(doc.resolve(json.pos));\n }\n /**\n @internal\n */\n getBookmark() { return new GapBookmark(this.anchor); }\n /**\n @internal\n */\n static valid($pos) {\n let parent = $pos.parent;\n if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos))\n return false;\n let override = parent.type.spec.allowGapCursor;\n if (override != null)\n return override;\n let deflt = parent.contentMatchAt($pos.index()).defaultType;\n return deflt && deflt.isTextblock;\n }\n /**\n @internal\n */\n static findGapCursorFrom($pos, dir, mustMove = false) {\n search: for (;;) {\n if (!mustMove && GapCursor.valid($pos))\n return $pos;\n let pos = $pos.pos, next = null;\n // Scan up from this position\n for (let d = $pos.depth;; d--) {\n let parent = $pos.node(d);\n if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {\n next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);\n break;\n }\n else if (d == 0) {\n return null;\n }\n pos += dir;\n let $cur = $pos.doc.resolve(pos);\n if (GapCursor.valid($cur))\n return $cur;\n }\n // And then down into the next node\n for (;;) {\n let inside = dir > 0 ? next.firstChild : next.lastChild;\n if (!inside) {\n if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {\n $pos = $pos.doc.resolve(pos + next.nodeSize * dir);\n mustMove = false;\n continue search;\n }\n break;\n }\n next = inside;\n pos += dir;\n let $cur = $pos.doc.resolve(pos);\n if (GapCursor.valid($cur))\n return $cur;\n }\n return null;\n }\n }\n}\nGapCursor.prototype.visible = false;\nGapCursor.findFrom = GapCursor.findGapCursorFrom;\nSelection.jsonID(\"gapcursor\", GapCursor);\nclass GapBookmark {\n constructor(pos) {\n this.pos = pos;\n }\n map(mapping) {\n return new GapBookmark(mapping.map(this.pos));\n }\n resolve(doc) {\n let $pos = doc.resolve(this.pos);\n return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n }\n}\nfunction closedBefore($pos) {\n for (let d = $pos.depth; d >= 0; d--) {\n let index = $pos.index(d), parent = $pos.node(d);\n // At the start of this parent, look at next one\n if (index == 0) {\n if (parent.type.spec.isolating)\n return true;\n continue;\n }\n // See if the node before (or its first ancestor) is closed\n for (let before = parent.child(index - 1);; before = before.lastChild) {\n if ((before.childCount == 0 && !before.inlineContent) || before.isAtom || before.type.spec.isolating)\n return true;\n if (before.inlineContent)\n return false;\n }\n }\n // Hit start of document\n return true;\n}\nfunction closedAfter($pos) {\n for (let d = $pos.depth; d >= 0; d--) {\n let index = $pos.indexAfter(d), parent = $pos.node(d);\n if (index == parent.childCount) {\n if (parent.type.spec.isolating)\n return true;\n continue;\n }\n for (let after = parent.child(index);; after = after.firstChild) {\n if ((after.childCount == 0 && !after.inlineContent) || after.isAtom || after.type.spec.isolating)\n return true;\n if (after.inlineContent)\n return false;\n }\n }\n return true;\n}\n\n/**\nCreate a gap cursor plugin. When enabled, this will capture clicks\nnear and arrow-key-motion past places that don't have a normally\nselectable position nearby, and create a gap cursor selection for\nthem. The cursor is drawn as an element with class\n`ProseMirror-gapcursor`. You can either include\n`style/gapcursor.css` from the package's directory or add your own\nstyles to make it visible.\n*/\nfunction gapCursor() {\n return new Plugin({\n props: {\n decorations: drawGapCursor,\n createSelectionBetween(_view, $anchor, $head) {\n return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;\n },\n handleClick,\n handleKeyDown,\n handleDOMEvents: { beforeinput: beforeinput }\n }\n });\n}\nconst handleKeyDown = keydownHandler({\n \"ArrowLeft\": arrow(\"horiz\", -1),\n \"ArrowRight\": arrow(\"horiz\", 1),\n \"ArrowUp\": arrow(\"vert\", -1),\n \"ArrowDown\": arrow(\"vert\", 1)\n});\nfunction arrow(axis, dir) {\n const dirStr = axis == \"vert\" ? (dir > 0 ? \"down\" : \"up\") : (dir > 0 ? \"right\" : \"left\");\n return function (state, dispatch, view) {\n let sel = state.selection;\n let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;\n if (sel instanceof TextSelection) {\n if (!view.endOfTextblock(dirStr) || $start.depth == 0)\n return false;\n mustMove = false;\n $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());\n }\n let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);\n if (!$found)\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(new GapCursor($found)));\n return true;\n };\n}\nfunction handleClick(view, pos, event) {\n if (!view || !view.editable)\n return false;\n let $pos = view.state.doc.resolve(pos);\n if (!GapCursor.valid($pos))\n return false;\n let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });\n if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))\n return false;\n view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));\n return true;\n}\n// This is a hack that, when a composition starts while a gap cursor\n// is active, quickly creates an inline context for the composition to\n// happen in, to avoid it being aborted by the DOM selection being\n// moved into a valid position.\nfunction beforeinput(view, event) {\n if (event.inputType != \"insertCompositionText\" || !(view.state.selection instanceof GapCursor))\n return false;\n let { $from } = view.state.selection;\n let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);\n if (!insert)\n return false;\n let frag = Fragment.empty;\n for (let i = insert.length - 1; i >= 0; i--)\n frag = Fragment.from(insert[i].createAndFill(null, frag));\n let tr = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));\n tr.setSelection(TextSelection.near(tr.doc.resolve($from.pos + 1)));\n view.dispatch(tr);\n return false;\n}\nfunction drawGapCursor(state) {\n if (!(state.selection instanceof GapCursor))\n return null;\n let node = document.createElement(\"div\");\n node.className = \"ProseMirror-gapcursor\";\n return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: \"gapcursor\" })]);\n}\n\nexport { GapCursor, gapCursor };\n","import { Extension, callOrReturn, getExtensionField } from '@tiptap/core';\nimport { gapCursor } from '@tiptap/pm/gapcursor';\n\n/**\n * This extension allows you to add a gap cursor to your editor.\n * A gap cursor is a cursor that appears when you click on a place\n * where no content is present, for example inbetween nodes.\n * @see https://tiptap.dev/api/extensions/gapcursor\n */\nconst Gapcursor = Extension.create({\n name: 'gapCursor',\n addProseMirrorPlugins() {\n return [\n gapCursor(),\n ];\n },\n extendNodeSchema(extension) {\n var _a;\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n };\n return {\n allowGapCursor: (_a = callOrReturn(getExtensionField(extension, 'allowGapCursor', context))) !== null && _a !== void 0 ? _a : null,\n };\n },\n});\n\nexport { Gapcursor, Gapcursor as default };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes } from '@tiptap/core';\n\n/**\n * This extension allows you to insert hard breaks.\n * @see https://www.tiptap.dev/api/nodes/hard-break\n */\nconst HardBreak = Node.create({\n name: 'hardBreak',\n addOptions() {\n return {\n keepMarks: true,\n HTMLAttributes: {},\n };\n },\n inline: true,\n group: 'inline',\n selectable: false,\n linebreakReplacement: true,\n parseHTML() {\n return [\n { tag: 'br' },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['br', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)];\n },\n renderText() {\n return '\\n';\n },\n addCommands() {\n return {\n setHardBreak: () => ({ commands, chain, state, editor, }) => {\n return commands.first([\n () => commands.exitCode(),\n () => commands.command(() => {\n const { selection, storedMarks } = state;\n if (selection.$from.parent.type.spec.isolating) {\n return false;\n }\n const { keepMarks } = this.options;\n const { splittableMarks } = editor.extensionManager;\n const marks = storedMarks\n || (selection.$to.parentOffset && selection.$from.marks());\n return chain()\n .insertContent({ type: this.name })\n .command(({ tr, dispatch }) => {\n if (dispatch && marks && keepMarks) {\n const filteredMarks = marks\n .filter(mark => splittableMarks.includes(mark.type.name));\n tr.ensureMarks(filteredMarks);\n }\n return true;\n })\n .run();\n }),\n ]);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Enter': () => this.editor.commands.setHardBreak(),\n 'Shift-Enter': () => this.editor.commands.setHardBreak(),\n };\n },\n});\n\nexport { HardBreak, HardBreak as default };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes, textblockTypeInputRule } from '@tiptap/core';\n\n/**\n * This extension allows you to create headings.\n * @see https://www.tiptap.dev/api/nodes/heading\n */\nconst Heading = Node.create({\n name: 'heading',\n addOptions() {\n return {\n levels: [1, 2, 3, 4, 5, 6],\n HTMLAttributes: {},\n };\n },\n content: 'inline*',\n group: 'block',\n defining: true,\n addAttributes() {\n return {\n level: {\n default: 1,\n rendered: false,\n },\n };\n },\n parseHTML() {\n return this.options.levels\n .map((level) => ({\n tag: `h${level}`,\n attrs: { level },\n }));\n },\n renderHTML({ node, HTMLAttributes }) {\n const hasLevel = this.options.levels.includes(node.attrs.level);\n const level = hasLevel\n ? node.attrs.level\n : this.options.levels[0];\n return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setHeading: attributes => ({ commands }) => {\n if (!this.options.levels.includes(attributes.level)) {\n return false;\n }\n return commands.setNode(this.name, attributes);\n },\n toggleHeading: attributes => ({ commands }) => {\n if (!this.options.levels.includes(attributes.level)) {\n return false;\n }\n return commands.toggleNode(this.name, 'paragraph', attributes);\n },\n };\n },\n addKeyboardShortcuts() {\n return this.options.levels.reduce((items, level) => ({\n ...items,\n ...{\n [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level }),\n },\n }), {});\n },\n addInputRules() {\n return this.options.levels.map(level => {\n return textblockTypeInputRule({\n find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\\\s$`),\n type: this.type,\n getAttributes: {\n level,\n },\n });\n });\n },\n});\n\nexport { Heading, Heading as default };\n//# sourceMappingURL=index.js.map\n","var GOOD_LEAF_SIZE = 200;\n\n// :: class A rope sequence is a persistent sequence data structure\n// that supports appending, prepending, and slicing without doing a\n// full copy. It is represented as a mostly-balanced tree.\nvar RopeSequence = function RopeSequence () {};\n\nRopeSequence.prototype.append = function append (other) {\n if (!other.length) { return this }\n other = RopeSequence.from(other);\n\n return (!this.length && other) ||\n (other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) ||\n (this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) ||\n this.appendInner(other)\n};\n\n// :: (union<[T], RopeSequence>) → RopeSequence\n// Prepend an array or other rope to this one, returning a new rope.\nRopeSequence.prototype.prepend = function prepend (other) {\n if (!other.length) { return this }\n return RopeSequence.from(other).append(this)\n};\n\nRopeSequence.prototype.appendInner = function appendInner (other) {\n return new Append(this, other)\n};\n\n// :: (?number, ?number) → RopeSequence\n// Create a rope repesenting a sub-sequence of this rope.\nRopeSequence.prototype.slice = function slice (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from >= to) { return RopeSequence.empty }\n return this.sliceInner(Math.max(0, from), Math.min(this.length, to))\n};\n\n// :: (number) → T\n// Retrieve the element at the given position from this rope.\nRopeSequence.prototype.get = function get (i) {\n if (i < 0 || i >= this.length) { return undefined }\n return this.getInner(i)\n};\n\n// :: ((element: T, index: number) → ?bool, ?number, ?number)\n// Call the given function for each element between the given\n// indices. This tends to be more efficient than looping over the\n// indices and calling `get`, because it doesn't have to descend the\n// tree for every element.\nRopeSequence.prototype.forEach = function forEach (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from <= to)\n { this.forEachInner(f, from, to, 0); }\n else\n { this.forEachInvertedInner(f, from, to, 0); }\n};\n\n// :: ((element: T, index: number) → U, ?number, ?number) → [U]\n// Map the given functions over the elements of the rope, producing\n// a flat array.\nRopeSequence.prototype.map = function map (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n var result = [];\n this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to);\n return result\n};\n\n// :: (?union<[T], RopeSequence>) → RopeSequence\n// Create a rope representing the given array, or return the rope\n// itself if a rope was given.\nRopeSequence.from = function from (values) {\n if (values instanceof RopeSequence) { return values }\n return values && values.length ? new Leaf(values) : RopeSequence.empty\n};\n\nvar Leaf = /*@__PURE__*/(function (RopeSequence) {\n function Leaf(values) {\n RopeSequence.call(this);\n this.values = values;\n }\n\n if ( RopeSequence ) Leaf.__proto__ = RopeSequence;\n Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Leaf.prototype.constructor = Leaf;\n\n var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } };\n\n Leaf.prototype.flatten = function flatten () {\n return this.values\n };\n\n Leaf.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n return new Leaf(this.values.slice(from, to))\n };\n\n Leaf.prototype.getInner = function getInner (i) {\n return this.values[i]\n };\n\n Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) {\n for (var i = from; i < to; i++)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n for (var i = from - 1; i >= to; i--)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.leafAppend = function leafAppend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(this.values.concat(other.flatten())) }\n };\n\n Leaf.prototype.leafPrepend = function leafPrepend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(other.flatten().concat(this.values)) }\n };\n\n prototypeAccessors.length.get = function () { return this.values.length };\n\n prototypeAccessors.depth.get = function () { return 0 };\n\n Object.defineProperties( Leaf.prototype, prototypeAccessors );\n\n return Leaf;\n}(RopeSequence));\n\n// :: RopeSequence\n// The empty rope sequence.\nRopeSequence.empty = new Leaf([]);\n\nvar Append = /*@__PURE__*/(function (RopeSequence) {\n function Append(left, right) {\n RopeSequence.call(this);\n this.left = left;\n this.right = right;\n this.length = left.length + right.length;\n this.depth = Math.max(left.depth, right.depth) + 1;\n }\n\n if ( RopeSequence ) Append.__proto__ = RopeSequence;\n Append.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Append.prototype.constructor = Append;\n\n Append.prototype.flatten = function flatten () {\n return this.left.flatten().concat(this.right.flatten())\n };\n\n Append.prototype.getInner = function getInner (i) {\n return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length)\n };\n\n Append.prototype.forEachInner = function forEachInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from < leftLen &&\n this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)\n { return false }\n if (to > leftLen &&\n this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)\n { return false }\n };\n\n Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from > leftLen &&\n this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)\n { return false }\n if (to < leftLen &&\n this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)\n { return false }\n };\n\n Append.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n var leftLen = this.left.length;\n if (to <= leftLen) { return this.left.slice(from, to) }\n if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) }\n return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen))\n };\n\n Append.prototype.leafAppend = function leafAppend (other) {\n var inner = this.right.leafAppend(other);\n if (inner) { return new Append(this.left, inner) }\n };\n\n Append.prototype.leafPrepend = function leafPrepend (other) {\n var inner = this.left.leafPrepend(other);\n if (inner) { return new Append(inner, this.right) }\n };\n\n Append.prototype.appendInner = function appendInner (other) {\n if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)\n { return new Append(this.left, new Append(this.right, other)) }\n return new Append(this, other)\n };\n\n return Append;\n}(RopeSequence));\n\nexport default RopeSequence;\n","import RopeSequence from 'rope-sequence';\nimport { Mapping } from 'prosemirror-transform';\nimport { PluginKey, Plugin } from 'prosemirror-state';\n\n// ProseMirror's history isn't simply a way to roll back to a previous\n// state, because ProseMirror supports applying changes without adding\n// them to the history (for example during collaboration).\n//\n// To this end, each 'Branch' (one for the undo history and one for\n// the redo history) keeps an array of 'Items', which can optionally\n// hold a step (an actual undoable change), and always hold a position\n// map (which is needed to move changes below them to apply to the\n// current document).\n//\n// An item that has both a step and a selection bookmark is the start\n// of an 'event' — a group of changes that will be undone or redone at\n// once. (It stores only the bookmark, since that way we don't have to\n// provide a document until the selection is actually applied, which\n// is useful when compressing.)\n// Used to schedule history compression\nconst max_empty_items = 500;\nclass Branch {\n constructor(items, eventCount) {\n this.items = items;\n this.eventCount = eventCount;\n }\n // Pop the latest event off the branch's history and apply it\n // to a document transform.\n popEvent(state, preserveItems) {\n if (this.eventCount == 0)\n return null;\n let end = this.items.length;\n for (;; end--) {\n let next = this.items.get(end - 1);\n if (next.selection) {\n --end;\n break;\n }\n }\n let remap, mapFrom;\n if (preserveItems) {\n remap = this.remapping(end, this.items.length);\n mapFrom = remap.maps.length;\n }\n let transform = state.tr;\n let selection, remaining;\n let addAfter = [], addBefore = [];\n this.items.forEach((item, i) => {\n if (!item.step) {\n if (!remap) {\n remap = this.remapping(end, i + 1);\n mapFrom = remap.maps.length;\n }\n mapFrom--;\n addBefore.push(item);\n return;\n }\n if (remap) {\n addBefore.push(new Item(item.map));\n let step = item.step.map(remap.slice(mapFrom)), map;\n if (step && transform.maybeStep(step).doc) {\n map = transform.mapping.maps[transform.mapping.maps.length - 1];\n addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length));\n }\n mapFrom--;\n if (map)\n remap.appendMap(map, mapFrom);\n }\n else {\n transform.maybeStep(item.step);\n }\n if (item.selection) {\n selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;\n remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);\n return false;\n }\n }, this.items.length, 0);\n return { remaining: remaining, transform, selection: selection };\n }\n // Create a new branch with the given transform added.\n addTransform(transform, selection, histOptions, preserveItems) {\n let newItems = [], eventCount = this.eventCount;\n let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;\n for (let i = 0; i < transform.steps.length; i++) {\n let step = transform.steps[i].invert(transform.docs[i]);\n let item = new Item(transform.mapping.maps[i], step, selection), merged;\n if (merged = lastItem && lastItem.merge(item)) {\n item = merged;\n if (i)\n newItems.pop();\n else\n oldItems = oldItems.slice(0, oldItems.length - 1);\n }\n newItems.push(item);\n if (selection) {\n eventCount++;\n selection = undefined;\n }\n if (!preserveItems)\n lastItem = item;\n }\n let overflow = eventCount - histOptions.depth;\n if (overflow > DEPTH_OVERFLOW) {\n oldItems = cutOffEvents(oldItems, overflow);\n eventCount -= overflow;\n }\n return new Branch(oldItems.append(newItems), eventCount);\n }\n remapping(from, to) {\n let maps = new Mapping;\n this.items.forEach((item, i) => {\n let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from\n ? maps.maps.length - item.mirrorOffset : undefined;\n maps.appendMap(item.map, mirrorPos);\n }, from, to);\n return maps;\n }\n addMaps(array) {\n if (this.eventCount == 0)\n return this;\n return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount);\n }\n // When the collab module receives remote changes, the history has\n // to know about those, so that it can adjust the steps that were\n // rebased on top of the remote changes, and include the position\n // maps for the remote changes in its array of items.\n rebased(rebasedTransform, rebasedCount) {\n if (!this.eventCount)\n return this;\n let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount);\n let mapping = rebasedTransform.mapping;\n let newUntil = rebasedTransform.steps.length;\n let eventCount = this.eventCount;\n this.items.forEach(item => { if (item.selection)\n eventCount--; }, start);\n let iRebased = rebasedCount;\n this.items.forEach(item => {\n let pos = mapping.getMirror(--iRebased);\n if (pos == null)\n return;\n newUntil = Math.min(newUntil, pos);\n let map = mapping.maps[pos];\n if (item.step) {\n let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);\n let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));\n if (selection)\n eventCount++;\n rebasedItems.push(new Item(map, step, selection));\n }\n else {\n rebasedItems.push(new Item(map));\n }\n }, start);\n let newMaps = [];\n for (let i = rebasedCount; i < newUntil; i++)\n newMaps.push(new Item(mapping.maps[i]));\n let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);\n let branch = new Branch(items, eventCount);\n if (branch.emptyItemCount() > max_empty_items)\n branch = branch.compress(this.items.length - rebasedItems.length);\n return branch;\n }\n emptyItemCount() {\n let count = 0;\n this.items.forEach(item => { if (!item.step)\n count++; });\n return count;\n }\n // Compressing a branch means rewriting it to push the air (map-only\n // items) out. During collaboration, these naturally accumulate\n // because each remote change adds one. The `upto` argument is used\n // to ensure that only the items below a given level are compressed,\n // because `rebased` relies on a clean, untouched set of items in\n // order to associate old items with rebased steps.\n compress(upto = this.items.length) {\n let remap = this.remapping(0, upto), mapFrom = remap.maps.length;\n let items = [], events = 0;\n this.items.forEach((item, i) => {\n if (i >= upto) {\n items.push(item);\n if (item.selection)\n events++;\n }\n else if (item.step) {\n let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap();\n mapFrom--;\n if (map)\n remap.appendMap(map, mapFrom);\n if (step) {\n let selection = item.selection && item.selection.map(remap.slice(mapFrom));\n if (selection)\n events++;\n let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1;\n if (merged = items.length && items[last].merge(newItem))\n items[last] = merged;\n else\n items.push(newItem);\n }\n }\n else if (item.map) {\n mapFrom--;\n }\n }, this.items.length, 0);\n return new Branch(RopeSequence.from(items.reverse()), events);\n }\n}\nBranch.empty = new Branch(RopeSequence.empty, 0);\nfunction cutOffEvents(items, n) {\n let cutPoint;\n items.forEach((item, i) => {\n if (item.selection && (n-- == 0)) {\n cutPoint = i;\n return false;\n }\n });\n return items.slice(cutPoint);\n}\nclass Item {\n constructor(\n // The (forward) step map for this item.\n map, \n // The inverted step\n step, \n // If this is non-null, this item is the start of a group, and\n // this selection is the starting selection for the group (the one\n // that was active before the first step was applied)\n selection, \n // If this item is the inverse of a previous mapping on the stack,\n // this points at the inverse's offset\n mirrorOffset) {\n this.map = map;\n this.step = step;\n this.selection = selection;\n this.mirrorOffset = mirrorOffset;\n }\n merge(other) {\n if (this.step && other.step && !other.selection) {\n let step = other.step.merge(this.step);\n if (step)\n return new Item(step.getMap().invert(), step, this.selection);\n }\n }\n}\n// The value of the state field that tracks undo/redo history for that\n// state. Will be stored in the plugin state when the history plugin\n// is active.\nclass HistoryState {\n constructor(done, undone, prevRanges, prevTime, prevComposition) {\n this.done = done;\n this.undone = undone;\n this.prevRanges = prevRanges;\n this.prevTime = prevTime;\n this.prevComposition = prevComposition;\n }\n}\nconst DEPTH_OVERFLOW = 20;\n// Record a transformation in undo history.\nfunction applyTransaction(history, state, tr, options) {\n let historyTr = tr.getMeta(historyKey), rebased;\n if (historyTr)\n return historyTr.historyState;\n if (tr.getMeta(closeHistoryKey))\n history = new HistoryState(history.done, history.undone, null, 0, -1);\n let appended = tr.getMeta(\"appendedTransaction\");\n if (tr.steps.length == 0) {\n return history;\n }\n else if (appended && appended.getMeta(historyKey)) {\n if (appended.getMeta(historyKey).redo)\n return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition);\n else\n return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition);\n }\n else if (tr.getMeta(\"addToHistory\") !== false && !(appended && appended.getMeta(\"addToHistory\") === false)) {\n // Group transforms that occur in quick succession into one event.\n let composition = tr.getMeta(\"composition\");\n let newGroup = history.prevTime == 0 ||\n (!appended && history.prevComposition != composition &&\n (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges)));\n let prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);\n return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition);\n }\n else if (rebased = tr.getMeta(\"rebased\")) {\n // Used by the collab module to tell the history that some of its\n // content has been rebased.\n return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n else {\n return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n}\nfunction isAdjacentTo(transform, prevRanges) {\n if (!prevRanges)\n return false;\n if (!transform.docChanged)\n return true;\n let adjacent = false;\n transform.mapping.maps[0].forEach((start, end) => {\n for (let i = 0; i < prevRanges.length; i += 2)\n if (start <= prevRanges[i + 1] && end >= prevRanges[i])\n adjacent = true;\n });\n return adjacent;\n}\nfunction rangesFor(maps) {\n let result = [];\n for (let i = maps.length - 1; i >= 0 && result.length == 0; i--)\n maps[i].forEach((_from, _to, from, to) => result.push(from, to));\n return result;\n}\nfunction mapRanges(ranges, mapping) {\n if (!ranges)\n return null;\n let result = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);\n if (from <= to)\n result.push(from, to);\n }\n return result;\n}\n// Apply the latest event from one branch to the document and shift the event\n// onto the other branch.\nfunction histTransaction(history, state, redo) {\n let preserveItems = mustPreserveItems(state);\n let histOptions = historyKey.get(state).spec.config;\n let pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n if (!pop)\n return null;\n let selection = pop.selection.resolve(pop.transform.doc);\n let added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);\n let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1);\n return pop.transform.setSelection(selection).setMeta(historyKey, { redo, historyState: newHist });\n}\nlet cachedPreserveItems = false, cachedPreserveItemsPlugins = null;\n// Check whether any plugin in the given state has a\n// `historyPreserveItems` property in its spec, in which case we must\n// preserve steps exactly as they came in, so that they can be\n// rebased.\nfunction mustPreserveItems(state) {\n let plugins = state.plugins;\n if (cachedPreserveItemsPlugins != plugins) {\n cachedPreserveItems = false;\n cachedPreserveItemsPlugins = plugins;\n for (let i = 0; i < plugins.length; i++)\n if (plugins[i].spec.historyPreserveItems) {\n cachedPreserveItems = true;\n break;\n }\n }\n return cachedPreserveItems;\n}\n/**\nSet a flag on the given transaction that will prevent further steps\nfrom being appended to an existing history event (so that they\nrequire a separate undo command to undo).\n*/\nfunction closeHistory(tr) {\n return tr.setMeta(closeHistoryKey, true);\n}\nconst historyKey = new PluginKey(\"history\");\nconst closeHistoryKey = new PluginKey(\"closeHistory\");\n/**\nReturns a plugin that enables the undo history for an editor. The\nplugin will track undo and redo stacks, which can be used with the\n[`undo`](https://prosemirror.net/docs/ref/#history.undo) and [`redo`](https://prosemirror.net/docs/ref/#history.redo) commands.\n\nYou can set an `\"addToHistory\"` [metadata\nproperty](https://prosemirror.net/docs/ref/#state.Transaction.setMeta) of `false` on a transaction\nto prevent it from being rolled back by undo.\n*/\nfunction history(config = {}) {\n config = { depth: config.depth || 100,\n newGroupDelay: config.newGroupDelay || 500 };\n return new Plugin({\n key: historyKey,\n state: {\n init() {\n return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);\n },\n apply(tr, hist, state) {\n return applyTransaction(hist, state, tr, config);\n }\n },\n config,\n props: {\n handleDOMEvents: {\n beforeinput(view, e) {\n let inputType = e.inputType;\n let command = inputType == \"historyUndo\" ? undo : inputType == \"historyRedo\" ? redo : null;\n if (!command)\n return false;\n e.preventDefault();\n return command(view.state, view.dispatch);\n }\n }\n }\n });\n}\nfunction buildCommand(redo, scroll) {\n return (state, dispatch) => {\n let hist = historyKey.getState(state);\n if (!hist || (redo ? hist.undone : hist.done).eventCount == 0)\n return false;\n if (dispatch) {\n let tr = histTransaction(hist, state, redo);\n if (tr)\n dispatch(scroll ? tr.scrollIntoView() : tr);\n }\n return true;\n };\n}\n/**\nA command function that undoes the last change, if any.\n*/\nconst undo = buildCommand(false, true);\n/**\nA command function that redoes the last undone change, if any.\n*/\nconst redo = buildCommand(true, true);\n/**\nA command function that undoes the last change. Don't scroll the\nselection into view.\n*/\nconst undoNoScroll = buildCommand(false, false);\n/**\nA command function that redoes the last undone change. Don't\nscroll the selection into view.\n*/\nconst redoNoScroll = buildCommand(true, false);\n/**\nThe amount of undoable events available in a given state.\n*/\nfunction undoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.done.eventCount : 0;\n}\n/**\nThe amount of redoable events available in a given editor state.\n*/\nfunction redoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.undone.eventCount : 0;\n}\n\nexport { closeHistory, history, redo, redoDepth, redoNoScroll, undo, undoDepth, undoNoScroll };\n","import { Extension } from '@tiptap/core';\nimport { undo, redo, history } from '@tiptap/pm/history';\n\n/**\n * This extension allows you to undo and redo recent changes.\n * @see https://www.tiptap.dev/api/extensions/history\n *\n * **Important**: If the `@tiptap/extension-collaboration` package is used, make sure to remove\n * the `history` extension, as it is not compatible with the `collaboration` extension.\n *\n * `@tiptap/extension-collaboration` uses its own history implementation.\n */\nconst History = Extension.create({\n name: 'history',\n addOptions() {\n return {\n depth: 100,\n newGroupDelay: 500,\n };\n },\n addCommands() {\n return {\n undo: () => ({ state, dispatch }) => {\n return undo(state, dispatch);\n },\n redo: () => ({ state, dispatch }) => {\n return redo(state, dispatch);\n },\n };\n },\n addProseMirrorPlugins() {\n return [\n history(this.options),\n ];\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-z': () => this.editor.commands.undo(),\n 'Shift-Mod-z': () => this.editor.commands.redo(),\n 'Mod-y': () => this.editor.commands.redo(),\n // Russian keyboard layouts\n 'Mod-я': () => this.editor.commands.undo(),\n 'Shift-Mod-я': () => this.editor.commands.redo(),\n };\n },\n});\n\nexport { History, History as default };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes, isNodeSelection, nodeInputRule } from '@tiptap/core';\nimport { TextSelection, NodeSelection } from '@tiptap/pm/state';\n\n/**\n * This extension allows you to insert horizontal rules.\n * @see https://www.tiptap.dev/api/nodes/horizontal-rule\n */\nconst HorizontalRule = Node.create({\n name: 'horizontalRule',\n addOptions() {\n return {\n HTMLAttributes: {},\n };\n },\n group: 'block',\n parseHTML() {\n return [{ tag: 'hr' }];\n },\n renderHTML({ HTMLAttributes }) {\n return ['hr', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)];\n },\n addCommands() {\n return {\n setHorizontalRule: () => ({ chain, state }) => {\n const { selection } = state;\n const { $from: $originFrom, $to: $originTo } = selection;\n const currentChain = chain();\n if ($originFrom.parentOffset === 0) {\n currentChain.insertContentAt({\n from: Math.max($originFrom.pos - 1, 0),\n to: $originTo.pos,\n }, {\n type: this.name,\n });\n }\n else if (isNodeSelection(selection)) {\n currentChain.insertContentAt($originTo.pos, {\n type: this.name,\n });\n }\n else {\n currentChain.insertContent({ type: this.name });\n }\n return (currentChain\n // set cursor after horizontal rule\n .command(({ tr, dispatch }) => {\n var _a;\n if (dispatch) {\n const { $to } = tr.selection;\n const posAfter = $to.end();\n if ($to.nodeAfter) {\n if ($to.nodeAfter.isTextblock) {\n tr.setSelection(TextSelection.create(tr.doc, $to.pos + 1));\n }\n else if ($to.nodeAfter.isBlock) {\n tr.setSelection(NodeSelection.create(tr.doc, $to.pos));\n }\n else {\n tr.setSelection(TextSelection.create(tr.doc, $to.pos));\n }\n }\n else {\n // add node after horizontal rule if it’s the end of the document\n const node = (_a = $to.parent.type.contentMatch.defaultType) === null || _a === void 0 ? void 0 : _a.create();\n if (node) {\n tr.insert(posAfter, node);\n tr.setSelection(TextSelection.create(tr.doc, posAfter + 1));\n }\n }\n tr.scrollIntoView();\n }\n return true;\n })\n .run());\n },\n };\n },\n addInputRules() {\n return [\n nodeInputRule({\n find: /^(?:---|—-|___\\s|\\*\\*\\*\\s)$/,\n type: this.type,\n }),\n ];\n },\n});\n\nexport { HorizontalRule, HorizontalRule as default };\n//# sourceMappingURL=index.js.map\n","import { Mark, mergeAttributes, markInputRule, markPasteRule } from '@tiptap/core';\n\n/**\n * Matches an italic to a *italic* on input.\n */\nconst starInputRegex = /(?:^|\\s)(\\*(?!\\s+\\*)((?:[^*]+))\\*(?!\\s+\\*))$/;\n/**\n * Matches an italic to a *italic* on paste.\n */\nconst starPasteRegex = /(?:^|\\s)(\\*(?!\\s+\\*)((?:[^*]+))\\*(?!\\s+\\*))/g;\n/**\n * Matches an italic to a _italic_ on input.\n */\nconst underscoreInputRegex = /(?:^|\\s)(_(?!\\s+_)((?:[^_]+))_(?!\\s+_))$/;\n/**\n * Matches an italic to a _italic_ on paste.\n */\nconst underscorePasteRegex = /(?:^|\\s)(_(?!\\s+_)((?:[^_]+))_(?!\\s+_))/g;\n/**\n * This extension allows you to create italic text.\n * @see https://www.tiptap.dev/api/marks/italic\n */\nconst Italic = Mark.create({\n name: 'italic',\n addOptions() {\n return {\n HTMLAttributes: {},\n };\n },\n parseHTML() {\n return [\n {\n tag: 'em',\n },\n {\n tag: 'i',\n getAttrs: node => node.style.fontStyle !== 'normal' && null,\n },\n {\n style: 'font-style=normal',\n clearMark: mark => mark.type.name === this.name,\n },\n {\n style: 'font-style=italic',\n },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['em', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setItalic: () => ({ commands }) => {\n return commands.setMark(this.name);\n },\n toggleItalic: () => ({ commands }) => {\n return commands.toggleMark(this.name);\n },\n unsetItalic: () => ({ commands }) => {\n return commands.unsetMark(this.name);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-i': () => this.editor.commands.toggleItalic(),\n 'Mod-I': () => this.editor.commands.toggleItalic(),\n };\n },\n addInputRules() {\n return [\n markInputRule({\n find: starInputRegex,\n type: this.type,\n }),\n markInputRule({\n find: underscoreInputRegex,\n type: this.type,\n }),\n ];\n },\n addPasteRules() {\n return [\n markPasteRule({\n find: starPasteRegex,\n type: this.type,\n }),\n markPasteRule({\n find: underscorePasteRegex,\n type: this.type,\n }),\n ];\n },\n});\n\nexport { Italic, Italic as default, starInputRegex, starPasteRegex, underscoreInputRegex, underscorePasteRegex };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes } from '@tiptap/core';\n\n/**\n * This extension allows you to create list items.\n * @see https://www.tiptap.dev/api/nodes/list-item\n */\nconst ListItem = Node.create({\n name: 'listItem',\n addOptions() {\n return {\n HTMLAttributes: {},\n bulletListTypeName: 'bulletList',\n orderedListTypeName: 'orderedList',\n };\n },\n content: 'paragraph block*',\n defining: true,\n parseHTML() {\n return [\n {\n tag: 'li',\n },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['li', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addKeyboardShortcuts() {\n return {\n Enter: () => this.editor.commands.splitListItem(this.name),\n Tab: () => this.editor.commands.sinkListItem(this.name),\n 'Shift-Tab': () => this.editor.commands.liftListItem(this.name),\n };\n },\n});\n\nexport { ListItem, ListItem as default };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes, wrappingInputRule } from '@tiptap/core';\n\nconst ListItemName = 'listItem';\nconst TextStyleName = 'textStyle';\n/**\n * Matches an ordered list to a 1. on input (or any number followed by a dot).\n */\nconst inputRegex = /^(\\d+)\\.\\s$/;\n/**\n * This extension allows you to create ordered lists.\n * This requires the ListItem extension\n * @see https://www.tiptap.dev/api/nodes/ordered-list\n * @see https://www.tiptap.dev/api/nodes/list-item\n */\nconst OrderedList = Node.create({\n name: 'orderedList',\n addOptions() {\n return {\n itemTypeName: 'listItem',\n HTMLAttributes: {},\n keepMarks: false,\n keepAttributes: false,\n };\n },\n group: 'block list',\n content() {\n return `${this.options.itemTypeName}+`;\n },\n addAttributes() {\n return {\n start: {\n default: 1,\n parseHTML: element => {\n return element.hasAttribute('start')\n ? parseInt(element.getAttribute('start') || '', 10)\n : 1;\n },\n },\n type: {\n default: undefined,\n parseHTML: element => element.getAttribute('type'),\n },\n };\n },\n parseHTML() {\n return [\n {\n tag: 'ol',\n },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n const { start, ...attributesWithoutStart } = HTMLAttributes;\n return start === 1\n ? ['ol', mergeAttributes(this.options.HTMLAttributes, attributesWithoutStart), 0]\n : ['ol', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n toggleOrderedList: () => ({ commands, chain }) => {\n if (this.options.keepAttributes) {\n return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run();\n }\n return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-7': () => this.editor.commands.toggleOrderedList(),\n };\n },\n addInputRules() {\n let inputRule = wrappingInputRule({\n find: inputRegex,\n type: this.type,\n getAttributes: match => ({ start: +match[1] }),\n joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1],\n });\n if (this.options.keepMarks || this.options.keepAttributes) {\n inputRule = wrappingInputRule({\n find: inputRegex,\n type: this.type,\n keepMarks: this.options.keepMarks,\n keepAttributes: this.options.keepAttributes,\n getAttributes: match => ({ start: +match[1], ...this.editor.getAttributes(TextStyleName) }),\n joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1],\n editor: this.editor,\n });\n }\n return [\n inputRule,\n ];\n },\n});\n\nexport { OrderedList, OrderedList as default, inputRegex };\n//# sourceMappingURL=index.js.map\n","import { Node, mergeAttributes } from '@tiptap/core';\n\n/**\n * This extension allows you to create paragraphs.\n * @see https://www.tiptap.dev/api/nodes/paragraph\n */\nconst Paragraph = Node.create({\n name: 'paragraph',\n priority: 1000,\n addOptions() {\n return {\n HTMLAttributes: {},\n };\n },\n group: 'block',\n content: 'inline*',\n parseHTML() {\n return [\n { tag: 'p' },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['p', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setParagraph: () => ({ commands }) => {\n return commands.setNode(this.name);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Alt-0': () => this.editor.commands.setParagraph(),\n };\n },\n});\n\nexport { Paragraph, Paragraph as default };\n//# sourceMappingURL=index.js.map\n","import { Mark, mergeAttributes, markInputRule, markPasteRule } from '@tiptap/core';\n\n/**\n * Matches a strike to a ~~strike~~ on input.\n */\nconst inputRegex = /(?:^|\\s)(~~(?!\\s+~~)((?:[^~]+))~~(?!\\s+~~))$/;\n/**\n * Matches a strike to a ~~strike~~ on paste.\n */\nconst pasteRegex = /(?:^|\\s)(~~(?!\\s+~~)((?:[^~]+))~~(?!\\s+~~))/g;\n/**\n * This extension allows you to create strike text.\n * @see https://www.tiptap.dev/api/marks/strike\n */\nconst Strike = Mark.create({\n name: 'strike',\n addOptions() {\n return {\n HTMLAttributes: {},\n };\n },\n parseHTML() {\n return [\n {\n tag: 's',\n },\n {\n tag: 'del',\n },\n {\n tag: 'strike',\n },\n {\n style: 'text-decoration',\n consuming: false,\n getAttrs: style => (style.includes('line-through') ? {} : false),\n },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['s', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setStrike: () => ({ commands }) => {\n return commands.setMark(this.name);\n },\n toggleStrike: () => ({ commands }) => {\n return commands.toggleMark(this.name);\n },\n unsetStrike: () => ({ commands }) => {\n return commands.unsetMark(this.name);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-s': () => this.editor.commands.toggleStrike(),\n };\n },\n addInputRules() {\n return [\n markInputRule({\n find: inputRegex,\n type: this.type,\n }),\n ];\n },\n addPasteRules() {\n return [\n markPasteRule({\n find: pasteRegex,\n type: this.type,\n }),\n ];\n },\n});\n\nexport { Strike, Strike as default, inputRegex, pasteRegex };\n//# sourceMappingURL=index.js.map\n","import { Node } from '@tiptap/core';\n\n/**\n * This extension allows you to create text nodes.\n * @see https://www.tiptap.dev/api/nodes/text\n */\nconst Text = Node.create({\n name: 'text',\n group: 'inline',\n});\n\nexport { Text, Text as default };\n//# sourceMappingURL=index.js.map\n","import { Extension } from '@tiptap/core';\nimport { Blockquote } from '@tiptap/extension-blockquote';\nimport { Bold } from '@tiptap/extension-bold';\nimport { BulletList } from '@tiptap/extension-bullet-list';\nimport { Code } from '@tiptap/extension-code';\nimport { CodeBlock } from '@tiptap/extension-code-block';\nimport { Document } from '@tiptap/extension-document';\nimport { Dropcursor } from '@tiptap/extension-dropcursor';\nimport { Gapcursor } from '@tiptap/extension-gapcursor';\nimport { HardBreak } from '@tiptap/extension-hard-break';\nimport { Heading } from '@tiptap/extension-heading';\nimport { History } from '@tiptap/extension-history';\nimport { HorizontalRule } from '@tiptap/extension-horizontal-rule';\nimport { Italic } from '@tiptap/extension-italic';\nimport { ListItem } from '@tiptap/extension-list-item';\nimport { OrderedList } from '@tiptap/extension-ordered-list';\nimport { Paragraph } from '@tiptap/extension-paragraph';\nimport { Strike } from '@tiptap/extension-strike';\nimport { Text } from '@tiptap/extension-text';\n\n/**\n * The starter kit is a collection of essential editor extensions.\n *\n * It’s a good starting point for building your own editor.\n */\nconst StarterKit = Extension.create({\n name: 'starterKit',\n addExtensions() {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;\n const extensions = [];\n if (this.options.bold !== false) {\n extensions.push(Bold.configure((_a = this.options) === null || _a === void 0 ? void 0 : _a.bold));\n }\n if (this.options.blockquote !== false) {\n extensions.push(Blockquote.configure((_b = this.options) === null || _b === void 0 ? void 0 : _b.blockquote));\n }\n if (this.options.bulletList !== false) {\n extensions.push(BulletList.configure((_c = this.options) === null || _c === void 0 ? void 0 : _c.bulletList));\n }\n if (this.options.code !== false) {\n extensions.push(Code.configure((_d = this.options) === null || _d === void 0 ? void 0 : _d.code));\n }\n if (this.options.codeBlock !== false) {\n extensions.push(CodeBlock.configure((_e = this.options) === null || _e === void 0 ? void 0 : _e.codeBlock));\n }\n if (this.options.document !== false) {\n extensions.push(Document.configure((_f = this.options) === null || _f === void 0 ? void 0 : _f.document));\n }\n if (this.options.dropcursor !== false) {\n extensions.push(Dropcursor.configure((_g = this.options) === null || _g === void 0 ? void 0 : _g.dropcursor));\n }\n if (this.options.gapcursor !== false) {\n extensions.push(Gapcursor.configure((_h = this.options) === null || _h === void 0 ? void 0 : _h.gapcursor));\n }\n if (this.options.hardBreak !== false) {\n extensions.push(HardBreak.configure((_j = this.options) === null || _j === void 0 ? void 0 : _j.hardBreak));\n }\n if (this.options.heading !== false) {\n extensions.push(Heading.configure((_k = this.options) === null || _k === void 0 ? void 0 : _k.heading));\n }\n if (this.options.history !== false) {\n extensions.push(History.configure((_l = this.options) === null || _l === void 0 ? void 0 : _l.history));\n }\n if (this.options.horizontalRule !== false) {\n extensions.push(HorizontalRule.configure((_m = this.options) === null || _m === void 0 ? void 0 : _m.horizontalRule));\n }\n if (this.options.italic !== false) {\n extensions.push(Italic.configure((_o = this.options) === null || _o === void 0 ? void 0 : _o.italic));\n }\n if (this.options.listItem !== false) {\n extensions.push(ListItem.configure((_p = this.options) === null || _p === void 0 ? void 0 : _p.listItem));\n }\n if (this.options.orderedList !== false) {\n extensions.push(OrderedList.configure((_q = this.options) === null || _q === void 0 ? void 0 : _q.orderedList));\n }\n if (this.options.paragraph !== false) {\n extensions.push(Paragraph.configure((_r = this.options) === null || _r === void 0 ? void 0 : _r.paragraph));\n }\n if (this.options.strike !== false) {\n extensions.push(Strike.configure((_s = this.options) === null || _s === void 0 ? void 0 : _s.strike));\n }\n if (this.options.text !== false) {\n extensions.push(Text.configure((_t = this.options) === null || _t === void 0 ? void 0 : _t.text));\n }\n return extensions;\n },\n});\n\nexport { StarterKit, StarterKit as default };\n//# sourceMappingURL=index.js.map\n","import { Mark, mergeAttributes } from '@tiptap/core';\n\n/**\n * This extension allows you to create underline text.\n * @see https://www.tiptap.dev/api/marks/underline\n */\nconst Underline = Mark.create({\n name: 'underline',\n addOptions() {\n return {\n HTMLAttributes: {},\n };\n },\n parseHTML() {\n return [\n {\n tag: 'u',\n },\n {\n style: 'text-decoration',\n consuming: false,\n getAttrs: style => (style.includes('underline') ? {} : false),\n },\n ];\n },\n renderHTML({ HTMLAttributes }) {\n return ['u', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];\n },\n addCommands() {\n return {\n setUnderline: () => ({ commands }) => {\n return commands.setMark(this.name);\n },\n toggleUnderline: () => ({ commands }) => {\n return commands.toggleMark(this.name);\n },\n unsetUnderline: () => ({ commands }) => {\n return commands.unsetMark(this.name);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-u': () => this.editor.commands.toggleUnderline(),\n 'Mod-U': () => this.editor.commands.toggleUnderline(),\n };\n },\n});\n\nexport { Underline, Underline as default };\n//# sourceMappingURL=index.js.map\n","import { Extension } from '@tiptap/core';\n\n/**\n * This extension allows you to align text.\n * @see https://www.tiptap.dev/api/extensions/text-align\n */\nconst TextAlign = Extension.create({\n name: 'textAlign',\n addOptions() {\n return {\n types: [],\n alignments: ['left', 'center', 'right', 'justify'],\n defaultAlignment: null,\n };\n },\n addGlobalAttributes() {\n return [\n {\n types: this.options.types,\n attributes: {\n textAlign: {\n default: this.options.defaultAlignment,\n parseHTML: element => {\n const alignment = element.style.textAlign;\n return this.options.alignments.includes(alignment) ? alignment : this.options.defaultAlignment;\n },\n renderHTML: attributes => {\n if (!attributes.textAlign) {\n return {};\n }\n return { style: `text-align: ${attributes.textAlign}` };\n },\n },\n },\n },\n ];\n },\n addCommands() {\n return {\n setTextAlign: (alignment) => ({ commands }) => {\n if (!this.options.alignments.includes(alignment)) {\n return false;\n }\n return this.options.types\n .map(type => commands.updateAttributes(type, { textAlign: alignment }))\n .every(response => response);\n },\n unsetTextAlign: () => ({ commands }) => {\n return this.options.types\n .map(type => commands.resetAttributes(type, 'textAlign'))\n .every(response => response);\n },\n };\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-l': () => this.editor.commands.setTextAlign('left'),\n 'Mod-Shift-e': () => this.editor.commands.setTextAlign('center'),\n 'Mod-Shift-r': () => this.editor.commands.setTextAlign('right'),\n 'Mod-Shift-j': () => this.editor.commands.setTextAlign('justify'),\n };\n },\n});\n\nexport { TextAlign, TextAlign as default };\n//# sourceMappingURL=index.js.map\n","const COMMON_MIME_TYPES = /* @__PURE__ */ new Map([\n // https://github.com/guzzle/psr7/blob/2d9260799e713f1c475d3c5fdc3d6561ff7441b2/src/MimeType.php\n [\"1km\", \"application/vnd.1000minds.decision-model+xml\"],\n [\"3dml\", \"text/vnd.in3d.3dml\"],\n [\"3ds\", \"image/x-3ds\"],\n [\"3g2\", \"video/3gpp2\"],\n [\"3gp\", \"video/3gp\"],\n [\"3gpp\", \"video/3gpp\"],\n [\"3mf\", \"model/3mf\"],\n [\"7z\", \"application/x-7z-compressed\"],\n [\"7zip\", \"application/x-7z-compressed\"],\n [\"123\", \"application/vnd.lotus-1-2-3\"],\n [\"aab\", \"application/x-authorware-bin\"],\n [\"aac\", \"audio/x-acc\"],\n [\"aam\", \"application/x-authorware-map\"],\n [\"aas\", \"application/x-authorware-seg\"],\n [\"abw\", \"application/x-abiword\"],\n [\"ac\", \"application/vnd.nokia.n-gage.ac+xml\"],\n [\"ac3\", \"audio/ac3\"],\n [\"acc\", \"application/vnd.americandynamics.acc\"],\n [\"ace\", \"application/x-ace-compressed\"],\n [\"acu\", \"application/vnd.acucobol\"],\n [\"acutc\", \"application/vnd.acucorp\"],\n [\"adp\", \"audio/adpcm\"],\n [\"aep\", \"application/vnd.audiograph\"],\n [\"afm\", \"application/x-font-type1\"],\n [\"afp\", \"application/vnd.ibm.modcap\"],\n [\"ahead\", \"application/vnd.ahead.space\"],\n [\"ai\", \"application/pdf\"],\n [\"aif\", \"audio/x-aiff\"],\n [\"aifc\", \"audio/x-aiff\"],\n [\"aiff\", \"audio/x-aiff\"],\n [\"air\", \"application/vnd.adobe.air-application-installer-package+zip\"],\n [\"ait\", \"application/vnd.dvb.ait\"],\n [\"ami\", \"application/vnd.amiga.ami\"],\n [\"amr\", \"audio/amr\"],\n [\"apk\", \"application/vnd.android.package-archive\"],\n [\"apng\", \"image/apng\"],\n [\"appcache\", \"text/cache-manifest\"],\n [\"application\", \"application/x-ms-application\"],\n [\"apr\", \"application/vnd.lotus-approach\"],\n [\"arc\", \"application/x-freearc\"],\n [\"arj\", \"application/x-arj\"],\n [\"asc\", \"application/pgp-signature\"],\n [\"asf\", \"video/x-ms-asf\"],\n [\"asm\", \"text/x-asm\"],\n [\"aso\", \"application/vnd.accpac.simply.aso\"],\n [\"asx\", \"video/x-ms-asf\"],\n [\"atc\", \"application/vnd.acucorp\"],\n [\"atom\", \"application/atom+xml\"],\n [\"atomcat\", \"application/atomcat+xml\"],\n [\"atomdeleted\", \"application/atomdeleted+xml\"],\n [\"atomsvc\", \"application/atomsvc+xml\"],\n [\"atx\", \"application/vnd.antix.game-component\"],\n [\"au\", \"audio/x-au\"],\n [\"avi\", \"video/x-msvideo\"],\n [\"avif\", \"image/avif\"],\n [\"aw\", \"application/applixware\"],\n [\"azf\", \"application/vnd.airzip.filesecure.azf\"],\n [\"azs\", \"application/vnd.airzip.filesecure.azs\"],\n [\"azv\", \"image/vnd.airzip.accelerator.azv\"],\n [\"azw\", \"application/vnd.amazon.ebook\"],\n [\"b16\", \"image/vnd.pco.b16\"],\n [\"bat\", \"application/x-msdownload\"],\n [\"bcpio\", \"application/x-bcpio\"],\n [\"bdf\", \"application/x-font-bdf\"],\n [\"bdm\", \"application/vnd.syncml.dm+wbxml\"],\n [\"bdoc\", \"application/x-bdoc\"],\n [\"bed\", \"application/vnd.realvnc.bed\"],\n [\"bh2\", \"application/vnd.fujitsu.oasysprs\"],\n [\"bin\", \"application/octet-stream\"],\n [\"blb\", \"application/x-blorb\"],\n [\"blorb\", \"application/x-blorb\"],\n [\"bmi\", \"application/vnd.bmi\"],\n [\"bmml\", \"application/vnd.balsamiq.bmml+xml\"],\n [\"bmp\", \"image/bmp\"],\n [\"book\", \"application/vnd.framemaker\"],\n [\"box\", \"application/vnd.previewsystems.box\"],\n [\"boz\", \"application/x-bzip2\"],\n [\"bpk\", \"application/octet-stream\"],\n [\"bpmn\", \"application/octet-stream\"],\n [\"bsp\", \"model/vnd.valve.source.compiled-map\"],\n [\"btif\", \"image/prs.btif\"],\n [\"buffer\", \"application/octet-stream\"],\n [\"bz\", \"application/x-bzip\"],\n [\"bz2\", \"application/x-bzip2\"],\n [\"c\", \"text/x-c\"],\n [\"c4d\", \"application/vnd.clonk.c4group\"],\n [\"c4f\", \"application/vnd.clonk.c4group\"],\n [\"c4g\", \"application/vnd.clonk.c4group\"],\n [\"c4p\", \"application/vnd.clonk.c4group\"],\n [\"c4u\", \"application/vnd.clonk.c4group\"],\n [\"c11amc\", \"application/vnd.cluetrust.cartomobile-config\"],\n [\"c11amz\", \"application/vnd.cluetrust.cartomobile-config-pkg\"],\n [\"cab\", \"application/vnd.ms-cab-compressed\"],\n [\"caf\", \"audio/x-caf\"],\n [\"cap\", \"application/vnd.tcpdump.pcap\"],\n [\"car\", \"application/vnd.curl.car\"],\n [\"cat\", \"application/vnd.ms-pki.seccat\"],\n [\"cb7\", \"application/x-cbr\"],\n [\"cba\", \"application/x-cbr\"],\n [\"cbr\", \"application/x-cbr\"],\n [\"cbt\", \"application/x-cbr\"],\n [\"cbz\", \"application/x-cbr\"],\n [\"cc\", \"text/x-c\"],\n [\"cco\", \"application/x-cocoa\"],\n [\"cct\", \"application/x-director\"],\n [\"ccxml\", \"application/ccxml+xml\"],\n [\"cdbcmsg\", \"application/vnd.contact.cmsg\"],\n [\"cda\", \"application/x-cdf\"],\n [\"cdf\", \"application/x-netcdf\"],\n [\"cdfx\", \"application/cdfx+xml\"],\n [\"cdkey\", \"application/vnd.mediastation.cdkey\"],\n [\"cdmia\", \"application/cdmi-capability\"],\n [\"cdmic\", \"application/cdmi-container\"],\n [\"cdmid\", \"application/cdmi-domain\"],\n [\"cdmio\", \"application/cdmi-object\"],\n [\"cdmiq\", \"application/cdmi-queue\"],\n [\"cdr\", \"application/cdr\"],\n [\"cdx\", \"chemical/x-cdx\"],\n [\"cdxml\", \"application/vnd.chemdraw+xml\"],\n [\"cdy\", \"application/vnd.cinderella\"],\n [\"cer\", \"application/pkix-cert\"],\n [\"cfs\", \"application/x-cfs-compressed\"],\n [\"cgm\", \"image/cgm\"],\n [\"chat\", \"application/x-chat\"],\n [\"chm\", \"application/vnd.ms-htmlhelp\"],\n [\"chrt\", \"application/vnd.kde.kchart\"],\n [\"cif\", \"chemical/x-cif\"],\n [\"cii\", \"application/vnd.anser-web-certificate-issue-initiation\"],\n [\"cil\", \"application/vnd.ms-artgalry\"],\n [\"cjs\", \"application/node\"],\n [\"cla\", \"application/vnd.claymore\"],\n [\"class\", \"application/octet-stream\"],\n [\"clkk\", \"application/vnd.crick.clicker.keyboard\"],\n [\"clkp\", \"application/vnd.crick.clicker.palette\"],\n [\"clkt\", \"application/vnd.crick.clicker.template\"],\n [\"clkw\", \"application/vnd.crick.clicker.wordbank\"],\n [\"clkx\", \"application/vnd.crick.clicker\"],\n [\"clp\", \"application/x-msclip\"],\n [\"cmc\", \"application/vnd.cosmocaller\"],\n [\"cmdf\", \"chemical/x-cmdf\"],\n [\"cml\", \"chemical/x-cml\"],\n [\"cmp\", \"application/vnd.yellowriver-custom-menu\"],\n [\"cmx\", \"image/x-cmx\"],\n [\"cod\", \"application/vnd.rim.cod\"],\n [\"coffee\", \"text/coffeescript\"],\n [\"com\", \"application/x-msdownload\"],\n [\"conf\", \"text/plain\"],\n [\"cpio\", \"application/x-cpio\"],\n [\"cpp\", \"text/x-c\"],\n [\"cpt\", \"application/mac-compactpro\"],\n [\"crd\", \"application/x-mscardfile\"],\n [\"crl\", \"application/pkix-crl\"],\n [\"crt\", \"application/x-x509-ca-cert\"],\n [\"crx\", \"application/x-chrome-extension\"],\n [\"cryptonote\", \"application/vnd.rig.cryptonote\"],\n [\"csh\", \"application/x-csh\"],\n [\"csl\", \"application/vnd.citationstyles.style+xml\"],\n [\"csml\", \"chemical/x-csml\"],\n [\"csp\", \"application/vnd.commonspace\"],\n [\"csr\", \"application/octet-stream\"],\n [\"css\", \"text/css\"],\n [\"cst\", \"application/x-director\"],\n [\"csv\", \"text/csv\"],\n [\"cu\", \"application/cu-seeme\"],\n [\"curl\", \"text/vnd.curl\"],\n [\"cww\", \"application/prs.cww\"],\n [\"cxt\", \"application/x-director\"],\n [\"cxx\", \"text/x-c\"],\n [\"dae\", \"model/vnd.collada+xml\"],\n [\"daf\", \"application/vnd.mobius.daf\"],\n [\"dart\", \"application/vnd.dart\"],\n [\"dataless\", \"application/vnd.fdsn.seed\"],\n [\"davmount\", \"application/davmount+xml\"],\n [\"dbf\", \"application/vnd.dbf\"],\n [\"dbk\", \"application/docbook+xml\"],\n [\"dcr\", \"application/x-director\"],\n [\"dcurl\", \"text/vnd.curl.dcurl\"],\n [\"dd2\", \"application/vnd.oma.dd2+xml\"],\n [\"ddd\", \"application/vnd.fujixerox.ddd\"],\n [\"ddf\", \"application/vnd.syncml.dmddf+xml\"],\n [\"dds\", \"image/vnd.ms-dds\"],\n [\"deb\", \"application/x-debian-package\"],\n [\"def\", \"text/plain\"],\n [\"deploy\", \"application/octet-stream\"],\n [\"der\", \"application/x-x509-ca-cert\"],\n [\"dfac\", \"application/vnd.dreamfactory\"],\n [\"dgc\", \"application/x-dgc-compressed\"],\n [\"dic\", \"text/x-c\"],\n [\"dir\", \"application/x-director\"],\n [\"dis\", \"application/vnd.mobius.dis\"],\n [\"disposition-notification\", \"message/disposition-notification\"],\n [\"dist\", \"application/octet-stream\"],\n [\"distz\", \"application/octet-stream\"],\n [\"djv\", \"image/vnd.djvu\"],\n [\"djvu\", \"image/vnd.djvu\"],\n [\"dll\", \"application/octet-stream\"],\n [\"dmg\", \"application/x-apple-diskimage\"],\n [\"dmn\", \"application/octet-stream\"],\n [\"dmp\", \"application/vnd.tcpdump.pcap\"],\n [\"dms\", \"application/octet-stream\"],\n [\"dna\", \"application/vnd.dna\"],\n [\"doc\", \"application/msword\"],\n [\"docm\", \"application/vnd.ms-word.template.macroEnabled.12\"],\n [\n \"docx\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n ],\n [\"dot\", \"application/msword\"],\n [\"dotm\", \"application/vnd.ms-word.template.macroEnabled.12\"],\n [\n \"dotx\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.template\"\n ],\n [\"dp\", \"application/vnd.osgi.dp\"],\n [\"dpg\", \"application/vnd.dpgraph\"],\n [\"dra\", \"audio/vnd.dra\"],\n [\"drle\", \"image/dicom-rle\"],\n [\"dsc\", \"text/prs.lines.tag\"],\n [\"dssc\", \"application/dssc+der\"],\n [\"dtb\", \"application/x-dtbook+xml\"],\n [\"dtd\", \"application/xml-dtd\"],\n [\"dts\", \"audio/vnd.dts\"],\n [\"dtshd\", \"audio/vnd.dts.hd\"],\n [\"dump\", \"application/octet-stream\"],\n [\"dvb\", \"video/vnd.dvb.file\"],\n [\"dvi\", \"application/x-dvi\"],\n [\"dwd\", \"application/atsc-dwd+xml\"],\n [\"dwf\", \"model/vnd.dwf\"],\n [\"dwg\", \"image/vnd.dwg\"],\n [\"dxf\", \"image/vnd.dxf\"],\n [\"dxp\", \"application/vnd.spotfire.dxp\"],\n [\"dxr\", \"application/x-director\"],\n [\"ear\", \"application/java-archive\"],\n [\"ecelp4800\", \"audio/vnd.nuera.ecelp4800\"],\n [\"ecelp7470\", \"audio/vnd.nuera.ecelp7470\"],\n [\"ecelp9600\", \"audio/vnd.nuera.ecelp9600\"],\n [\"ecma\", \"application/ecmascript\"],\n [\"edm\", \"application/vnd.novadigm.edm\"],\n [\"edx\", \"application/vnd.novadigm.edx\"],\n [\"efif\", \"application/vnd.picsel\"],\n [\"ei6\", \"application/vnd.pg.osasli\"],\n [\"elc\", \"application/octet-stream\"],\n [\"emf\", \"image/emf\"],\n [\"eml\", \"message/rfc822\"],\n [\"emma\", \"application/emma+xml\"],\n [\"emotionml\", \"application/emotionml+xml\"],\n [\"emz\", \"application/x-msmetafile\"],\n [\"eol\", \"audio/vnd.digital-winds\"],\n [\"eot\", \"application/vnd.ms-fontobject\"],\n [\"eps\", \"application/postscript\"],\n [\"epub\", \"application/epub+zip\"],\n [\"es\", \"application/ecmascript\"],\n [\"es3\", \"application/vnd.eszigno3+xml\"],\n [\"esa\", \"application/vnd.osgi.subsystem\"],\n [\"esf\", \"application/vnd.epson.esf\"],\n [\"et3\", \"application/vnd.eszigno3+xml\"],\n [\"etx\", \"text/x-setext\"],\n [\"eva\", \"application/x-eva\"],\n [\"evy\", \"application/x-envoy\"],\n [\"exe\", \"application/octet-stream\"],\n [\"exi\", \"application/exi\"],\n [\"exp\", \"application/express\"],\n [\"exr\", \"image/aces\"],\n [\"ext\", \"application/vnd.novadigm.ext\"],\n [\"ez\", \"application/andrew-inset\"],\n [\"ez2\", \"application/vnd.ezpix-album\"],\n [\"ez3\", \"application/vnd.ezpix-package\"],\n [\"f\", \"text/x-fortran\"],\n [\"f4v\", \"video/mp4\"],\n [\"f77\", \"text/x-fortran\"],\n [\"f90\", \"text/x-fortran\"],\n [\"fbs\", \"image/vnd.fastbidsheet\"],\n [\"fcdt\", \"application/vnd.adobe.formscentral.fcdt\"],\n [\"fcs\", \"application/vnd.isac.fcs\"],\n [\"fdf\", \"application/vnd.fdf\"],\n [\"fdt\", \"application/fdt+xml\"],\n [\"fe_launch\", \"application/vnd.denovo.fcselayout-link\"],\n [\"fg5\", \"application/vnd.fujitsu.oasysgp\"],\n [\"fgd\", \"application/x-director\"],\n [\"fh\", \"image/x-freehand\"],\n [\"fh4\", \"image/x-freehand\"],\n [\"fh5\", \"image/x-freehand\"],\n [\"fh7\", \"image/x-freehand\"],\n [\"fhc\", \"image/x-freehand\"],\n [\"fig\", \"application/x-xfig\"],\n [\"fits\", \"image/fits\"],\n [\"flac\", \"audio/x-flac\"],\n [\"fli\", \"video/x-fli\"],\n [\"flo\", \"application/vnd.micrografx.flo\"],\n [\"flv\", \"video/x-flv\"],\n [\"flw\", \"application/vnd.kde.kivio\"],\n [\"flx\", \"text/vnd.fmi.flexstor\"],\n [\"fly\", \"text/vnd.fly\"],\n [\"fm\", \"application/vnd.framemaker\"],\n [\"fnc\", \"application/vnd.frogans.fnc\"],\n [\"fo\", \"application/vnd.software602.filler.form+xml\"],\n [\"for\", \"text/x-fortran\"],\n [\"fpx\", \"image/vnd.fpx\"],\n [\"frame\", \"application/vnd.framemaker\"],\n [\"fsc\", \"application/vnd.fsc.weblaunch\"],\n [\"fst\", \"image/vnd.fst\"],\n [\"ftc\", \"application/vnd.fluxtime.clip\"],\n [\"fti\", \"application/vnd.anser-web-funds-transfer-initiation\"],\n [\"fvt\", \"video/vnd.fvt\"],\n [\"fxp\", \"application/vnd.adobe.fxp\"],\n [\"fxpl\", \"application/vnd.adobe.fxp\"],\n [\"fzs\", \"application/vnd.fuzzysheet\"],\n [\"g2w\", \"application/vnd.geoplan\"],\n [\"g3\", \"image/g3fax\"],\n [\"g3w\", \"application/vnd.geospace\"],\n [\"gac\", \"application/vnd.groove-account\"],\n [\"gam\", \"application/x-tads\"],\n [\"gbr\", \"application/rpki-ghostbusters\"],\n [\"gca\", \"application/x-gca-compressed\"],\n [\"gdl\", \"model/vnd.gdl\"],\n [\"gdoc\", \"application/vnd.google-apps.document\"],\n [\"geo\", \"application/vnd.dynageo\"],\n [\"geojson\", \"application/geo+json\"],\n [\"gex\", \"application/vnd.geometry-explorer\"],\n [\"ggb\", \"application/vnd.geogebra.file\"],\n [\"ggt\", \"application/vnd.geogebra.tool\"],\n [\"ghf\", \"application/vnd.groove-help\"],\n [\"gif\", \"image/gif\"],\n [\"gim\", \"application/vnd.groove-identity-message\"],\n [\"glb\", \"model/gltf-binary\"],\n [\"gltf\", \"model/gltf+json\"],\n [\"gml\", \"application/gml+xml\"],\n [\"gmx\", \"application/vnd.gmx\"],\n [\"gnumeric\", \"application/x-gnumeric\"],\n [\"gpg\", \"application/gpg-keys\"],\n [\"gph\", \"application/vnd.flographit\"],\n [\"gpx\", \"application/gpx+xml\"],\n [\"gqf\", \"application/vnd.grafeq\"],\n [\"gqs\", \"application/vnd.grafeq\"],\n [\"gram\", \"application/srgs\"],\n [\"gramps\", \"application/x-gramps-xml\"],\n [\"gre\", \"application/vnd.geometry-explorer\"],\n [\"grv\", \"application/vnd.groove-injector\"],\n [\"grxml\", \"application/srgs+xml\"],\n [\"gsf\", \"application/x-font-ghostscript\"],\n [\"gsheet\", \"application/vnd.google-apps.spreadsheet\"],\n [\"gslides\", \"application/vnd.google-apps.presentation\"],\n [\"gtar\", \"application/x-gtar\"],\n [\"gtm\", \"application/vnd.groove-tool-message\"],\n [\"gtw\", \"model/vnd.gtw\"],\n [\"gv\", \"text/vnd.graphviz\"],\n [\"gxf\", \"application/gxf\"],\n [\"gxt\", \"application/vnd.geonext\"],\n [\"gz\", \"application/gzip\"],\n [\"gzip\", \"application/gzip\"],\n [\"h\", \"text/x-c\"],\n [\"h261\", \"video/h261\"],\n [\"h263\", \"video/h263\"],\n [\"h264\", \"video/h264\"],\n [\"hal\", \"application/vnd.hal+xml\"],\n [\"hbci\", \"application/vnd.hbci\"],\n [\"hbs\", \"text/x-handlebars-template\"],\n [\"hdd\", \"application/x-virtualbox-hdd\"],\n [\"hdf\", \"application/x-hdf\"],\n [\"heic\", \"image/heic\"],\n [\"heics\", \"image/heic-sequence\"],\n [\"heif\", \"image/heif\"],\n [\"heifs\", \"image/heif-sequence\"],\n [\"hej2\", \"image/hej2k\"],\n [\"held\", \"application/atsc-held+xml\"],\n [\"hh\", \"text/x-c\"],\n [\"hjson\", \"application/hjson\"],\n [\"hlp\", \"application/winhlp\"],\n [\"hpgl\", \"application/vnd.hp-hpgl\"],\n [\"hpid\", \"application/vnd.hp-hpid\"],\n [\"hps\", \"application/vnd.hp-hps\"],\n [\"hqx\", \"application/mac-binhex40\"],\n [\"hsj2\", \"image/hsj2\"],\n [\"htc\", \"text/x-component\"],\n [\"htke\", \"application/vnd.kenameaapp\"],\n [\"htm\", \"text/html\"],\n [\"html\", \"text/html\"],\n [\"hvd\", \"application/vnd.yamaha.hv-dic\"],\n [\"hvp\", \"application/vnd.yamaha.hv-voice\"],\n [\"hvs\", \"application/vnd.yamaha.hv-script\"],\n [\"i2g\", \"application/vnd.intergeo\"],\n [\"icc\", \"application/vnd.iccprofile\"],\n [\"ice\", \"x-conference/x-cooltalk\"],\n [\"icm\", \"application/vnd.iccprofile\"],\n [\"ico\", \"image/x-icon\"],\n [\"ics\", \"text/calendar\"],\n [\"ief\", \"image/ief\"],\n [\"ifb\", \"text/calendar\"],\n [\"ifm\", \"application/vnd.shana.informed.formdata\"],\n [\"iges\", \"model/iges\"],\n [\"igl\", \"application/vnd.igloader\"],\n [\"igm\", \"application/vnd.insors.igm\"],\n [\"igs\", \"model/iges\"],\n [\"igx\", \"application/vnd.micrografx.igx\"],\n [\"iif\", \"application/vnd.shana.informed.interchange\"],\n [\"img\", \"application/octet-stream\"],\n [\"imp\", \"application/vnd.accpac.simply.imp\"],\n [\"ims\", \"application/vnd.ms-ims\"],\n [\"in\", \"text/plain\"],\n [\"ini\", \"text/plain\"],\n [\"ink\", \"application/inkml+xml\"],\n [\"inkml\", \"application/inkml+xml\"],\n [\"install\", \"application/x-install-instructions\"],\n [\"iota\", \"application/vnd.astraea-software.iota\"],\n [\"ipfix\", \"application/ipfix\"],\n [\"ipk\", \"application/vnd.shana.informed.package\"],\n [\"irm\", \"application/vnd.ibm.rights-management\"],\n [\"irp\", \"application/vnd.irepository.package+xml\"],\n [\"iso\", \"application/x-iso9660-image\"],\n [\"itp\", \"application/vnd.shana.informed.formtemplate\"],\n [\"its\", \"application/its+xml\"],\n [\"ivp\", \"application/vnd.immervision-ivp\"],\n [\"ivu\", \"application/vnd.immervision-ivu\"],\n [\"jad\", \"text/vnd.sun.j2me.app-descriptor\"],\n [\"jade\", \"text/jade\"],\n [\"jam\", \"application/vnd.jam\"],\n [\"jar\", \"application/java-archive\"],\n [\"jardiff\", \"application/x-java-archive-diff\"],\n [\"java\", \"text/x-java-source\"],\n [\"jhc\", \"image/jphc\"],\n [\"jisp\", \"application/vnd.jisp\"],\n [\"jls\", \"image/jls\"],\n [\"jlt\", \"application/vnd.hp-jlyt\"],\n [\"jng\", \"image/x-jng\"],\n [\"jnlp\", \"application/x-java-jnlp-file\"],\n [\"joda\", \"application/vnd.joost.joda-archive\"],\n [\"jp2\", \"image/jp2\"],\n [\"jpe\", \"image/jpeg\"],\n [\"jpeg\", \"image/jpeg\"],\n [\"jpf\", \"image/jpx\"],\n [\"jpg\", \"image/jpeg\"],\n [\"jpg2\", \"image/jp2\"],\n [\"jpgm\", \"video/jpm\"],\n [\"jpgv\", \"video/jpeg\"],\n [\"jph\", \"image/jph\"],\n [\"jpm\", \"video/jpm\"],\n [\"jpx\", \"image/jpx\"],\n [\"js\", \"application/javascript\"],\n [\"json\", \"application/json\"],\n [\"json5\", \"application/json5\"],\n [\"jsonld\", \"application/ld+json\"],\n // https://jsonlines.org/\n [\"jsonl\", \"application/jsonl\"],\n [\"jsonml\", \"application/jsonml+json\"],\n [\"jsx\", \"text/jsx\"],\n [\"jxr\", \"image/jxr\"],\n [\"jxra\", \"image/jxra\"],\n [\"jxrs\", \"image/jxrs\"],\n [\"jxs\", \"image/jxs\"],\n [\"jxsc\", \"image/jxsc\"],\n [\"jxsi\", \"image/jxsi\"],\n [\"jxss\", \"image/jxss\"],\n [\"kar\", \"audio/midi\"],\n [\"karbon\", \"application/vnd.kde.karbon\"],\n [\"kdb\", \"application/octet-stream\"],\n [\"kdbx\", \"application/x-keepass2\"],\n [\"key\", \"application/x-iwork-keynote-sffkey\"],\n [\"kfo\", \"application/vnd.kde.kformula\"],\n [\"kia\", \"application/vnd.kidspiration\"],\n [\"kml\", \"application/vnd.google-earth.kml+xml\"],\n [\"kmz\", \"application/vnd.google-earth.kmz\"],\n [\"kne\", \"application/vnd.kinar\"],\n [\"knp\", \"application/vnd.kinar\"],\n [\"kon\", \"application/vnd.kde.kontour\"],\n [\"kpr\", \"application/vnd.kde.kpresenter\"],\n [\"kpt\", \"application/vnd.kde.kpresenter\"],\n [\"kpxx\", \"application/vnd.ds-keypoint\"],\n [\"ksp\", \"application/vnd.kde.kspread\"],\n [\"ktr\", \"application/vnd.kahootz\"],\n [\"ktx\", \"image/ktx\"],\n [\"ktx2\", \"image/ktx2\"],\n [\"ktz\", \"application/vnd.kahootz\"],\n [\"kwd\", \"application/vnd.kde.kword\"],\n [\"kwt\", \"application/vnd.kde.kword\"],\n [\"lasxml\", \"application/vnd.las.las+xml\"],\n [\"latex\", \"application/x-latex\"],\n [\"lbd\", \"application/vnd.llamagraphics.life-balance.desktop\"],\n [\"lbe\", \"application/vnd.llamagraphics.life-balance.exchange+xml\"],\n [\"les\", \"application/vnd.hhe.lesson-player\"],\n [\"less\", \"text/less\"],\n [\"lgr\", \"application/lgr+xml\"],\n [\"lha\", \"application/octet-stream\"],\n [\"link66\", \"application/vnd.route66.link66+xml\"],\n [\"list\", \"text/plain\"],\n [\"list3820\", \"application/vnd.ibm.modcap\"],\n [\"listafp\", \"application/vnd.ibm.modcap\"],\n [\"litcoffee\", \"text/coffeescript\"],\n [\"lnk\", \"application/x-ms-shortcut\"],\n [\"log\", \"text/plain\"],\n [\"lostxml\", \"application/lost+xml\"],\n [\"lrf\", \"application/octet-stream\"],\n [\"lrm\", \"application/vnd.ms-lrm\"],\n [\"ltf\", \"application/vnd.frogans.ltf\"],\n [\"lua\", \"text/x-lua\"],\n [\"luac\", \"application/x-lua-bytecode\"],\n [\"lvp\", \"audio/vnd.lucent.voice\"],\n [\"lwp\", \"application/vnd.lotus-wordpro\"],\n [\"lzh\", \"application/octet-stream\"],\n [\"m1v\", \"video/mpeg\"],\n [\"m2a\", \"audio/mpeg\"],\n [\"m2v\", \"video/mpeg\"],\n [\"m3a\", \"audio/mpeg\"],\n [\"m3u\", \"text/plain\"],\n [\"m3u8\", \"application/vnd.apple.mpegurl\"],\n [\"m4a\", \"audio/x-m4a\"],\n [\"m4p\", \"application/mp4\"],\n [\"m4s\", \"video/iso.segment\"],\n [\"m4u\", \"application/vnd.mpegurl\"],\n [\"m4v\", \"video/x-m4v\"],\n [\"m13\", \"application/x-msmediaview\"],\n [\"m14\", \"application/x-msmediaview\"],\n [\"m21\", \"application/mp21\"],\n [\"ma\", \"application/mathematica\"],\n [\"mads\", \"application/mads+xml\"],\n [\"maei\", \"application/mmt-aei+xml\"],\n [\"mag\", \"application/vnd.ecowin.chart\"],\n [\"maker\", \"application/vnd.framemaker\"],\n [\"man\", \"text/troff\"],\n [\"manifest\", \"text/cache-manifest\"],\n [\"map\", \"application/json\"],\n [\"mar\", \"application/octet-stream\"],\n [\"markdown\", \"text/markdown\"],\n [\"mathml\", \"application/mathml+xml\"],\n [\"mb\", \"application/mathematica\"],\n [\"mbk\", \"application/vnd.mobius.mbk\"],\n [\"mbox\", \"application/mbox\"],\n [\"mc1\", \"application/vnd.medcalcdata\"],\n [\"mcd\", \"application/vnd.mcd\"],\n [\"mcurl\", \"text/vnd.curl.mcurl\"],\n [\"md\", \"text/markdown\"],\n [\"mdb\", \"application/x-msaccess\"],\n [\"mdi\", \"image/vnd.ms-modi\"],\n [\"mdx\", \"text/mdx\"],\n [\"me\", \"text/troff\"],\n [\"mesh\", \"model/mesh\"],\n [\"meta4\", \"application/metalink4+xml\"],\n [\"metalink\", \"application/metalink+xml\"],\n [\"mets\", \"application/mets+xml\"],\n [\"mfm\", \"application/vnd.mfmp\"],\n [\"mft\", \"application/rpki-manifest\"],\n [\"mgp\", \"application/vnd.osgeo.mapguide.package\"],\n [\"mgz\", \"application/vnd.proteus.magazine\"],\n [\"mid\", \"audio/midi\"],\n [\"midi\", \"audio/midi\"],\n [\"mie\", \"application/x-mie\"],\n [\"mif\", \"application/vnd.mif\"],\n [\"mime\", \"message/rfc822\"],\n [\"mj2\", \"video/mj2\"],\n [\"mjp2\", \"video/mj2\"],\n [\"mjs\", \"application/javascript\"],\n [\"mk3d\", \"video/x-matroska\"],\n [\"mka\", \"audio/x-matroska\"],\n [\"mkd\", \"text/x-markdown\"],\n [\"mks\", \"video/x-matroska\"],\n [\"mkv\", \"video/x-matroska\"],\n [\"mlp\", \"application/vnd.dolby.mlp\"],\n [\"mmd\", \"application/vnd.chipnuts.karaoke-mmd\"],\n [\"mmf\", \"application/vnd.smaf\"],\n [\"mml\", \"text/mathml\"],\n [\"mmr\", \"image/vnd.fujixerox.edmics-mmr\"],\n [\"mng\", \"video/x-mng\"],\n [\"mny\", \"application/x-msmoney\"],\n [\"mobi\", \"application/x-mobipocket-ebook\"],\n [\"mods\", \"application/mods+xml\"],\n [\"mov\", \"video/quicktime\"],\n [\"movie\", \"video/x-sgi-movie\"],\n [\"mp2\", \"audio/mpeg\"],\n [\"mp2a\", \"audio/mpeg\"],\n [\"mp3\", \"audio/mpeg\"],\n [\"mp4\", \"video/mp4\"],\n [\"mp4a\", \"audio/mp4\"],\n [\"mp4s\", \"application/mp4\"],\n [\"mp4v\", \"video/mp4\"],\n [\"mp21\", \"application/mp21\"],\n [\"mpc\", \"application/vnd.mophun.certificate\"],\n [\"mpd\", \"application/dash+xml\"],\n [\"mpe\", \"video/mpeg\"],\n [\"mpeg\", \"video/mpeg\"],\n [\"mpg\", \"video/mpeg\"],\n [\"mpg4\", \"video/mp4\"],\n [\"mpga\", \"audio/mpeg\"],\n [\"mpkg\", \"application/vnd.apple.installer+xml\"],\n [\"mpm\", \"application/vnd.blueice.multipass\"],\n [\"mpn\", \"application/vnd.mophun.application\"],\n [\"mpp\", \"application/vnd.ms-project\"],\n [\"mpt\", \"application/vnd.ms-project\"],\n [\"mpy\", \"application/vnd.ibm.minipay\"],\n [\"mqy\", \"application/vnd.mobius.mqy\"],\n [\"mrc\", \"application/marc\"],\n [\"mrcx\", \"application/marcxml+xml\"],\n [\"ms\", \"text/troff\"],\n [\"mscml\", \"application/mediaservercontrol+xml\"],\n [\"mseed\", \"application/vnd.fdsn.mseed\"],\n [\"mseq\", \"application/vnd.mseq\"],\n [\"msf\", \"application/vnd.epson.msf\"],\n [\"msg\", \"application/vnd.ms-outlook\"],\n [\"msh\", \"model/mesh\"],\n [\"msi\", \"application/x-msdownload\"],\n [\"msl\", \"application/vnd.mobius.msl\"],\n [\"msm\", \"application/octet-stream\"],\n [\"msp\", \"application/octet-stream\"],\n [\"msty\", \"application/vnd.muvee.style\"],\n [\"mtl\", \"model/mtl\"],\n [\"mts\", \"model/vnd.mts\"],\n [\"mus\", \"application/vnd.musician\"],\n [\"musd\", \"application/mmt-usd+xml\"],\n [\"musicxml\", \"application/vnd.recordare.musicxml+xml\"],\n [\"mvb\", \"application/x-msmediaview\"],\n [\"mvt\", \"application/vnd.mapbox-vector-tile\"],\n [\"mwf\", \"application/vnd.mfer\"],\n [\"mxf\", \"application/mxf\"],\n [\"mxl\", \"application/vnd.recordare.musicxml\"],\n [\"mxmf\", \"audio/mobile-xmf\"],\n [\"mxml\", \"application/xv+xml\"],\n [\"mxs\", \"application/vnd.triscape.mxs\"],\n [\"mxu\", \"video/vnd.mpegurl\"],\n [\"n-gage\", \"application/vnd.nokia.n-gage.symbian.install\"],\n [\"n3\", \"text/n3\"],\n [\"nb\", \"application/mathematica\"],\n [\"nbp\", \"application/vnd.wolfram.player\"],\n [\"nc\", \"application/x-netcdf\"],\n [\"ncx\", \"application/x-dtbncx+xml\"],\n [\"nfo\", \"text/x-nfo\"],\n [\"ngdat\", \"application/vnd.nokia.n-gage.data\"],\n [\"nitf\", \"application/vnd.nitf\"],\n [\"nlu\", \"application/vnd.neurolanguage.nlu\"],\n [\"nml\", \"application/vnd.enliven\"],\n [\"nnd\", \"application/vnd.noblenet-directory\"],\n [\"nns\", \"application/vnd.noblenet-sealer\"],\n [\"nnw\", \"application/vnd.noblenet-web\"],\n [\"npx\", \"image/vnd.net-fpx\"],\n [\"nq\", \"application/n-quads\"],\n [\"nsc\", \"application/x-conference\"],\n [\"nsf\", \"application/vnd.lotus-notes\"],\n [\"nt\", \"application/n-triples\"],\n [\"ntf\", \"application/vnd.nitf\"],\n [\"numbers\", \"application/x-iwork-numbers-sffnumbers\"],\n [\"nzb\", \"application/x-nzb\"],\n [\"oa2\", \"application/vnd.fujitsu.oasys2\"],\n [\"oa3\", \"application/vnd.fujitsu.oasys3\"],\n [\"oas\", \"application/vnd.fujitsu.oasys\"],\n [\"obd\", \"application/x-msbinder\"],\n [\"obgx\", \"application/vnd.openblox.game+xml\"],\n [\"obj\", \"model/obj\"],\n [\"oda\", \"application/oda\"],\n [\"odb\", \"application/vnd.oasis.opendocument.database\"],\n [\"odc\", \"application/vnd.oasis.opendocument.chart\"],\n [\"odf\", \"application/vnd.oasis.opendocument.formula\"],\n [\"odft\", \"application/vnd.oasis.opendocument.formula-template\"],\n [\"odg\", \"application/vnd.oasis.opendocument.graphics\"],\n [\"odi\", \"application/vnd.oasis.opendocument.image\"],\n [\"odm\", \"application/vnd.oasis.opendocument.text-master\"],\n [\"odp\", \"application/vnd.oasis.opendocument.presentation\"],\n [\"ods\", \"application/vnd.oasis.opendocument.spreadsheet\"],\n [\"odt\", \"application/vnd.oasis.opendocument.text\"],\n [\"oga\", \"audio/ogg\"],\n [\"ogex\", \"model/vnd.opengex\"],\n [\"ogg\", \"audio/ogg\"],\n [\"ogv\", \"video/ogg\"],\n [\"ogx\", \"application/ogg\"],\n [\"omdoc\", \"application/omdoc+xml\"],\n [\"onepkg\", \"application/onenote\"],\n [\"onetmp\", \"application/onenote\"],\n [\"onetoc\", \"application/onenote\"],\n [\"onetoc2\", \"application/onenote\"],\n [\"opf\", \"application/oebps-package+xml\"],\n [\"opml\", \"text/x-opml\"],\n [\"oprc\", \"application/vnd.palm\"],\n [\"opus\", \"audio/ogg\"],\n [\"org\", \"text/x-org\"],\n [\"osf\", \"application/vnd.yamaha.openscoreformat\"],\n [\"osfpvg\", \"application/vnd.yamaha.openscoreformat.osfpvg+xml\"],\n [\"osm\", \"application/vnd.openstreetmap.data+xml\"],\n [\"otc\", \"application/vnd.oasis.opendocument.chart-template\"],\n [\"otf\", \"font/otf\"],\n [\"otg\", \"application/vnd.oasis.opendocument.graphics-template\"],\n [\"oth\", \"application/vnd.oasis.opendocument.text-web\"],\n [\"oti\", \"application/vnd.oasis.opendocument.image-template\"],\n [\"otp\", \"application/vnd.oasis.opendocument.presentation-template\"],\n [\"ots\", \"application/vnd.oasis.opendocument.spreadsheet-template\"],\n [\"ott\", \"application/vnd.oasis.opendocument.text-template\"],\n [\"ova\", \"application/x-virtualbox-ova\"],\n [\"ovf\", \"application/x-virtualbox-ovf\"],\n [\"owl\", \"application/rdf+xml\"],\n [\"oxps\", \"application/oxps\"],\n [\"oxt\", \"application/vnd.openofficeorg.extension\"],\n [\"p\", \"text/x-pascal\"],\n [\"p7a\", \"application/x-pkcs7-signature\"],\n [\"p7b\", \"application/x-pkcs7-certificates\"],\n [\"p7c\", \"application/pkcs7-mime\"],\n [\"p7m\", \"application/pkcs7-mime\"],\n [\"p7r\", \"application/x-pkcs7-certreqresp\"],\n [\"p7s\", \"application/pkcs7-signature\"],\n [\"p8\", \"application/pkcs8\"],\n [\"p10\", \"application/x-pkcs10\"],\n [\"p12\", \"application/x-pkcs12\"],\n [\"pac\", \"application/x-ns-proxy-autoconfig\"],\n [\"pages\", \"application/x-iwork-pages-sffpages\"],\n [\"pas\", \"text/x-pascal\"],\n [\"paw\", \"application/vnd.pawaafile\"],\n [\"pbd\", \"application/vnd.powerbuilder6\"],\n [\"pbm\", \"image/x-portable-bitmap\"],\n [\"pcap\", \"application/vnd.tcpdump.pcap\"],\n [\"pcf\", \"application/x-font-pcf\"],\n [\"pcl\", \"application/vnd.hp-pcl\"],\n [\"pclxl\", \"application/vnd.hp-pclxl\"],\n [\"pct\", \"image/x-pict\"],\n [\"pcurl\", \"application/vnd.curl.pcurl\"],\n [\"pcx\", \"image/x-pcx\"],\n [\"pdb\", \"application/x-pilot\"],\n [\"pde\", \"text/x-processing\"],\n [\"pdf\", \"application/pdf\"],\n [\"pem\", \"application/x-x509-user-cert\"],\n [\"pfa\", \"application/x-font-type1\"],\n [\"pfb\", \"application/x-font-type1\"],\n [\"pfm\", \"application/x-font-type1\"],\n [\"pfr\", \"application/font-tdpfr\"],\n [\"pfx\", \"application/x-pkcs12\"],\n [\"pgm\", \"image/x-portable-graymap\"],\n [\"pgn\", \"application/x-chess-pgn\"],\n [\"pgp\", \"application/pgp\"],\n [\"php\", \"application/x-httpd-php\"],\n [\"php3\", \"application/x-httpd-php\"],\n [\"php4\", \"application/x-httpd-php\"],\n [\"phps\", \"application/x-httpd-php-source\"],\n [\"phtml\", \"application/x-httpd-php\"],\n [\"pic\", \"image/x-pict\"],\n [\"pkg\", \"application/octet-stream\"],\n [\"pki\", \"application/pkixcmp\"],\n [\"pkipath\", \"application/pkix-pkipath\"],\n [\"pkpass\", \"application/vnd.apple.pkpass\"],\n [\"pl\", \"application/x-perl\"],\n [\"plb\", \"application/vnd.3gpp.pic-bw-large\"],\n [\"plc\", \"application/vnd.mobius.plc\"],\n [\"plf\", \"application/vnd.pocketlearn\"],\n [\"pls\", \"application/pls+xml\"],\n [\"pm\", \"application/x-perl\"],\n [\"pml\", \"application/vnd.ctc-posml\"],\n [\"png\", \"image/png\"],\n [\"pnm\", \"image/x-portable-anymap\"],\n [\"portpkg\", \"application/vnd.macports.portpkg\"],\n [\"pot\", \"application/vnd.ms-powerpoint\"],\n [\"potm\", \"application/vnd.ms-powerpoint.presentation.macroEnabled.12\"],\n [\n \"potx\",\n \"application/vnd.openxmlformats-officedocument.presentationml.template\"\n ],\n [\"ppa\", \"application/vnd.ms-powerpoint\"],\n [\"ppam\", \"application/vnd.ms-powerpoint.addin.macroEnabled.12\"],\n [\"ppd\", \"application/vnd.cups-ppd\"],\n [\"ppm\", \"image/x-portable-pixmap\"],\n [\"pps\", \"application/vnd.ms-powerpoint\"],\n [\"ppsm\", \"application/vnd.ms-powerpoint.slideshow.macroEnabled.12\"],\n [\n \"ppsx\",\n \"application/vnd.openxmlformats-officedocument.presentationml.slideshow\"\n ],\n [\"ppt\", \"application/powerpoint\"],\n [\"pptm\", \"application/vnd.ms-powerpoint.presentation.macroEnabled.12\"],\n [\n \"pptx\",\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\"\n ],\n [\"pqa\", \"application/vnd.palm\"],\n [\"prc\", \"application/x-pilot\"],\n [\"pre\", \"application/vnd.lotus-freelance\"],\n [\"prf\", \"application/pics-rules\"],\n [\"provx\", \"application/provenance+xml\"],\n [\"ps\", \"application/postscript\"],\n [\"psb\", \"application/vnd.3gpp.pic-bw-small\"],\n [\"psd\", \"application/x-photoshop\"],\n [\"psf\", \"application/x-font-linux-psf\"],\n [\"pskcxml\", \"application/pskc+xml\"],\n [\"pti\", \"image/prs.pti\"],\n [\"ptid\", \"application/vnd.pvi.ptid1\"],\n [\"pub\", \"application/x-mspublisher\"],\n [\"pvb\", \"application/vnd.3gpp.pic-bw-var\"],\n [\"pwn\", \"application/vnd.3m.post-it-notes\"],\n [\"pya\", \"audio/vnd.ms-playready.media.pya\"],\n [\"pyv\", \"video/vnd.ms-playready.media.pyv\"],\n [\"qam\", \"application/vnd.epson.quickanime\"],\n [\"qbo\", \"application/vnd.intu.qbo\"],\n [\"qfx\", \"application/vnd.intu.qfx\"],\n [\"qps\", \"application/vnd.publishare-delta-tree\"],\n [\"qt\", \"video/quicktime\"],\n [\"qwd\", \"application/vnd.quark.quarkxpress\"],\n [\"qwt\", \"application/vnd.quark.quarkxpress\"],\n [\"qxb\", \"application/vnd.quark.quarkxpress\"],\n [\"qxd\", \"application/vnd.quark.quarkxpress\"],\n [\"qxl\", \"application/vnd.quark.quarkxpress\"],\n [\"qxt\", \"application/vnd.quark.quarkxpress\"],\n [\"ra\", \"audio/x-realaudio\"],\n [\"ram\", \"audio/x-pn-realaudio\"],\n [\"raml\", \"application/raml+yaml\"],\n [\"rapd\", \"application/route-apd+xml\"],\n [\"rar\", \"application/x-rar\"],\n [\"ras\", \"image/x-cmu-raster\"],\n [\"rcprofile\", \"application/vnd.ipunplugged.rcprofile\"],\n [\"rdf\", \"application/rdf+xml\"],\n [\"rdz\", \"application/vnd.data-vision.rdz\"],\n [\"relo\", \"application/p2p-overlay+xml\"],\n [\"rep\", \"application/vnd.businessobjects\"],\n [\"res\", \"application/x-dtbresource+xml\"],\n [\"rgb\", \"image/x-rgb\"],\n [\"rif\", \"application/reginfo+xml\"],\n [\"rip\", \"audio/vnd.rip\"],\n [\"ris\", \"application/x-research-info-systems\"],\n [\"rl\", \"application/resource-lists+xml\"],\n [\"rlc\", \"image/vnd.fujixerox.edmics-rlc\"],\n [\"rld\", \"application/resource-lists-diff+xml\"],\n [\"rm\", \"audio/x-pn-realaudio\"],\n [\"rmi\", \"audio/midi\"],\n [\"rmp\", \"audio/x-pn-realaudio-plugin\"],\n [\"rms\", \"application/vnd.jcp.javame.midlet-rms\"],\n [\"rmvb\", \"application/vnd.rn-realmedia-vbr\"],\n [\"rnc\", \"application/relax-ng-compact-syntax\"],\n [\"rng\", \"application/xml\"],\n [\"roa\", \"application/rpki-roa\"],\n [\"roff\", \"text/troff\"],\n [\"rp9\", \"application/vnd.cloanto.rp9\"],\n [\"rpm\", \"audio/x-pn-realaudio-plugin\"],\n [\"rpss\", \"application/vnd.nokia.radio-presets\"],\n [\"rpst\", \"application/vnd.nokia.radio-preset\"],\n [\"rq\", \"application/sparql-query\"],\n [\"rs\", \"application/rls-services+xml\"],\n [\"rsa\", \"application/x-pkcs7\"],\n [\"rsat\", \"application/atsc-rsat+xml\"],\n [\"rsd\", \"application/rsd+xml\"],\n [\"rsheet\", \"application/urc-ressheet+xml\"],\n [\"rss\", \"application/rss+xml\"],\n [\"rtf\", \"text/rtf\"],\n [\"rtx\", \"text/richtext\"],\n [\"run\", \"application/x-makeself\"],\n [\"rusd\", \"application/route-usd+xml\"],\n [\"rv\", \"video/vnd.rn-realvideo\"],\n [\"s\", \"text/x-asm\"],\n [\"s3m\", \"audio/s3m\"],\n [\"saf\", \"application/vnd.yamaha.smaf-audio\"],\n [\"sass\", \"text/x-sass\"],\n [\"sbml\", \"application/sbml+xml\"],\n [\"sc\", \"application/vnd.ibm.secure-container\"],\n [\"scd\", \"application/x-msschedule\"],\n [\"scm\", \"application/vnd.lotus-screencam\"],\n [\"scq\", \"application/scvp-cv-request\"],\n [\"scs\", \"application/scvp-cv-response\"],\n [\"scss\", \"text/x-scss\"],\n [\"scurl\", \"text/vnd.curl.scurl\"],\n [\"sda\", \"application/vnd.stardivision.draw\"],\n [\"sdc\", \"application/vnd.stardivision.calc\"],\n [\"sdd\", \"application/vnd.stardivision.impress\"],\n [\"sdkd\", \"application/vnd.solent.sdkm+xml\"],\n [\"sdkm\", \"application/vnd.solent.sdkm+xml\"],\n [\"sdp\", \"application/sdp\"],\n [\"sdw\", \"application/vnd.stardivision.writer\"],\n [\"sea\", \"application/octet-stream\"],\n [\"see\", \"application/vnd.seemail\"],\n [\"seed\", \"application/vnd.fdsn.seed\"],\n [\"sema\", \"application/vnd.sema\"],\n [\"semd\", \"application/vnd.semd\"],\n [\"semf\", \"application/vnd.semf\"],\n [\"senmlx\", \"application/senml+xml\"],\n [\"sensmlx\", \"application/sensml+xml\"],\n [\"ser\", \"application/java-serialized-object\"],\n [\"setpay\", \"application/set-payment-initiation\"],\n [\"setreg\", \"application/set-registration-initiation\"],\n [\"sfd-hdstx\", \"application/vnd.hydrostatix.sof-data\"],\n [\"sfs\", \"application/vnd.spotfire.sfs\"],\n [\"sfv\", \"text/x-sfv\"],\n [\"sgi\", \"image/sgi\"],\n [\"sgl\", \"application/vnd.stardivision.writer-global\"],\n [\"sgm\", \"text/sgml\"],\n [\"sgml\", \"text/sgml\"],\n [\"sh\", \"application/x-sh\"],\n [\"shar\", \"application/x-shar\"],\n [\"shex\", \"text/shex\"],\n [\"shf\", \"application/shf+xml\"],\n [\"shtml\", \"text/html\"],\n [\"sid\", \"image/x-mrsid-image\"],\n [\"sieve\", \"application/sieve\"],\n [\"sig\", \"application/pgp-signature\"],\n [\"sil\", \"audio/silk\"],\n [\"silo\", \"model/mesh\"],\n [\"sis\", \"application/vnd.symbian.install\"],\n [\"sisx\", \"application/vnd.symbian.install\"],\n [\"sit\", \"application/x-stuffit\"],\n [\"sitx\", \"application/x-stuffitx\"],\n [\"siv\", \"application/sieve\"],\n [\"skd\", \"application/vnd.koan\"],\n [\"skm\", \"application/vnd.koan\"],\n [\"skp\", \"application/vnd.koan\"],\n [\"skt\", \"application/vnd.koan\"],\n [\"sldm\", \"application/vnd.ms-powerpoint.slide.macroenabled.12\"],\n [\n \"sldx\",\n \"application/vnd.openxmlformats-officedocument.presentationml.slide\"\n ],\n [\"slim\", \"text/slim\"],\n [\"slm\", \"text/slim\"],\n [\"sls\", \"application/route-s-tsid+xml\"],\n [\"slt\", \"application/vnd.epson.salt\"],\n [\"sm\", \"application/vnd.stepmania.stepchart\"],\n [\"smf\", \"application/vnd.stardivision.math\"],\n [\"smi\", \"application/smil\"],\n [\"smil\", \"application/smil\"],\n [\"smv\", \"video/x-smv\"],\n [\"smzip\", \"application/vnd.stepmania.package\"],\n [\"snd\", \"audio/basic\"],\n [\"snf\", \"application/x-font-snf\"],\n [\"so\", \"application/octet-stream\"],\n [\"spc\", \"application/x-pkcs7-certificates\"],\n [\"spdx\", \"text/spdx\"],\n [\"spf\", \"application/vnd.yamaha.smaf-phrase\"],\n [\"spl\", \"application/x-futuresplash\"],\n [\"spot\", \"text/vnd.in3d.spot\"],\n [\"spp\", \"application/scvp-vp-response\"],\n [\"spq\", \"application/scvp-vp-request\"],\n [\"spx\", \"audio/ogg\"],\n [\"sql\", \"application/x-sql\"],\n [\"src\", \"application/x-wais-source\"],\n [\"srt\", \"application/x-subrip\"],\n [\"sru\", \"application/sru+xml\"],\n [\"srx\", \"application/sparql-results+xml\"],\n [\"ssdl\", \"application/ssdl+xml\"],\n [\"sse\", \"application/vnd.kodak-descriptor\"],\n [\"ssf\", \"application/vnd.epson.ssf\"],\n [\"ssml\", \"application/ssml+xml\"],\n [\"sst\", \"application/octet-stream\"],\n [\"st\", \"application/vnd.sailingtracker.track\"],\n [\"stc\", \"application/vnd.sun.xml.calc.template\"],\n [\"std\", \"application/vnd.sun.xml.draw.template\"],\n [\"stf\", \"application/vnd.wt.stf\"],\n [\"sti\", \"application/vnd.sun.xml.impress.template\"],\n [\"stk\", \"application/hyperstudio\"],\n [\"stl\", \"model/stl\"],\n [\"stpx\", \"model/step+xml\"],\n [\"stpxz\", \"model/step-xml+zip\"],\n [\"stpz\", \"model/step+zip\"],\n [\"str\", \"application/vnd.pg.format\"],\n [\"stw\", \"application/vnd.sun.xml.writer.template\"],\n [\"styl\", \"text/stylus\"],\n [\"stylus\", \"text/stylus\"],\n [\"sub\", \"text/vnd.dvb.subtitle\"],\n [\"sus\", \"application/vnd.sus-calendar\"],\n [\"susp\", \"application/vnd.sus-calendar\"],\n [\"sv4cpio\", \"application/x-sv4cpio\"],\n [\"sv4crc\", \"application/x-sv4crc\"],\n [\"svc\", \"application/vnd.dvb.service\"],\n [\"svd\", \"application/vnd.svd\"],\n [\"svg\", \"image/svg+xml\"],\n [\"svgz\", \"image/svg+xml\"],\n [\"swa\", \"application/x-director\"],\n [\"swf\", \"application/x-shockwave-flash\"],\n [\"swi\", \"application/vnd.aristanetworks.swi\"],\n [\"swidtag\", \"application/swid+xml\"],\n [\"sxc\", \"application/vnd.sun.xml.calc\"],\n [\"sxd\", \"application/vnd.sun.xml.draw\"],\n [\"sxg\", \"application/vnd.sun.xml.writer.global\"],\n [\"sxi\", \"application/vnd.sun.xml.impress\"],\n [\"sxm\", \"application/vnd.sun.xml.math\"],\n [\"sxw\", \"application/vnd.sun.xml.writer\"],\n [\"t\", \"text/troff\"],\n [\"t3\", \"application/x-t3vm-image\"],\n [\"t38\", \"image/t38\"],\n [\"taglet\", \"application/vnd.mynfc\"],\n [\"tao\", \"application/vnd.tao.intent-module-archive\"],\n [\"tap\", \"image/vnd.tencent.tap\"],\n [\"tar\", \"application/x-tar\"],\n [\"tcap\", \"application/vnd.3gpp2.tcap\"],\n [\"tcl\", \"application/x-tcl\"],\n [\"td\", \"application/urc-targetdesc+xml\"],\n [\"teacher\", \"application/vnd.smart.teacher\"],\n [\"tei\", \"application/tei+xml\"],\n [\"teicorpus\", \"application/tei+xml\"],\n [\"tex\", \"application/x-tex\"],\n [\"texi\", \"application/x-texinfo\"],\n [\"texinfo\", \"application/x-texinfo\"],\n [\"text\", \"text/plain\"],\n [\"tfi\", \"application/thraud+xml\"],\n [\"tfm\", \"application/x-tex-tfm\"],\n [\"tfx\", \"image/tiff-fx\"],\n [\"tga\", \"image/x-tga\"],\n [\"tgz\", \"application/x-tar\"],\n [\"thmx\", \"application/vnd.ms-officetheme\"],\n [\"tif\", \"image/tiff\"],\n [\"tiff\", \"image/tiff\"],\n [\"tk\", \"application/x-tcl\"],\n [\"tmo\", \"application/vnd.tmobile-livetv\"],\n [\"toml\", \"application/toml\"],\n [\"torrent\", \"application/x-bittorrent\"],\n [\"tpl\", \"application/vnd.groove-tool-template\"],\n [\"tpt\", \"application/vnd.trid.tpt\"],\n [\"tr\", \"text/troff\"],\n [\"tra\", \"application/vnd.trueapp\"],\n [\"trig\", \"application/trig\"],\n [\"trm\", \"application/x-msterminal\"],\n [\"ts\", \"video/mp2t\"],\n [\"tsd\", \"application/timestamped-data\"],\n [\"tsv\", \"text/tab-separated-values\"],\n [\"ttc\", \"font/collection\"],\n [\"ttf\", \"font/ttf\"],\n [\"ttl\", \"text/turtle\"],\n [\"ttml\", \"application/ttml+xml\"],\n [\"twd\", \"application/vnd.simtech-mindmapper\"],\n [\"twds\", \"application/vnd.simtech-mindmapper\"],\n [\"txd\", \"application/vnd.genomatix.tuxedo\"],\n [\"txf\", \"application/vnd.mobius.txf\"],\n [\"txt\", \"text/plain\"],\n [\"u8dsn\", \"message/global-delivery-status\"],\n [\"u8hdr\", \"message/global-headers\"],\n [\"u8mdn\", \"message/global-disposition-notification\"],\n [\"u8msg\", \"message/global\"],\n [\"u32\", \"application/x-authorware-bin\"],\n [\"ubj\", \"application/ubjson\"],\n [\"udeb\", \"application/x-debian-package\"],\n [\"ufd\", \"application/vnd.ufdl\"],\n [\"ufdl\", \"application/vnd.ufdl\"],\n [\"ulx\", \"application/x-glulx\"],\n [\"umj\", \"application/vnd.umajin\"],\n [\"unityweb\", \"application/vnd.unity\"],\n [\"uoml\", \"application/vnd.uoml+xml\"],\n [\"uri\", \"text/uri-list\"],\n [\"uris\", \"text/uri-list\"],\n [\"urls\", \"text/uri-list\"],\n [\"usdz\", \"model/vnd.usdz+zip\"],\n [\"ustar\", \"application/x-ustar\"],\n [\"utz\", \"application/vnd.uiq.theme\"],\n [\"uu\", \"text/x-uuencode\"],\n [\"uva\", \"audio/vnd.dece.audio\"],\n [\"uvd\", \"application/vnd.dece.data\"],\n [\"uvf\", \"application/vnd.dece.data\"],\n [\"uvg\", \"image/vnd.dece.graphic\"],\n [\"uvh\", \"video/vnd.dece.hd\"],\n [\"uvi\", \"image/vnd.dece.graphic\"],\n [\"uvm\", \"video/vnd.dece.mobile\"],\n [\"uvp\", \"video/vnd.dece.pd\"],\n [\"uvs\", \"video/vnd.dece.sd\"],\n [\"uvt\", \"application/vnd.dece.ttml+xml\"],\n [\"uvu\", \"video/vnd.uvvu.mp4\"],\n [\"uvv\", \"video/vnd.dece.video\"],\n [\"uvva\", \"audio/vnd.dece.audio\"],\n [\"uvvd\", \"application/vnd.dece.data\"],\n [\"uvvf\", \"application/vnd.dece.data\"],\n [\"uvvg\", \"image/vnd.dece.graphic\"],\n [\"uvvh\", \"video/vnd.dece.hd\"],\n [\"uvvi\", \"image/vnd.dece.graphic\"],\n [\"uvvm\", \"video/vnd.dece.mobile\"],\n [\"uvvp\", \"video/vnd.dece.pd\"],\n [\"uvvs\", \"video/vnd.dece.sd\"],\n [\"uvvt\", \"application/vnd.dece.ttml+xml\"],\n [\"uvvu\", \"video/vnd.uvvu.mp4\"],\n [\"uvvv\", \"video/vnd.dece.video\"],\n [\"uvvx\", \"application/vnd.dece.unspecified\"],\n [\"uvvz\", \"application/vnd.dece.zip\"],\n [\"uvx\", \"application/vnd.dece.unspecified\"],\n [\"uvz\", \"application/vnd.dece.zip\"],\n [\"vbox\", \"application/x-virtualbox-vbox\"],\n [\"vbox-extpack\", \"application/x-virtualbox-vbox-extpack\"],\n [\"vcard\", \"text/vcard\"],\n [\"vcd\", \"application/x-cdlink\"],\n [\"vcf\", \"text/x-vcard\"],\n [\"vcg\", \"application/vnd.groove-vcard\"],\n [\"vcs\", \"text/x-vcalendar\"],\n [\"vcx\", \"application/vnd.vcx\"],\n [\"vdi\", \"application/x-virtualbox-vdi\"],\n [\"vds\", \"model/vnd.sap.vds\"],\n [\"vhd\", \"application/x-virtualbox-vhd\"],\n [\"vis\", \"application/vnd.visionary\"],\n [\"viv\", \"video/vnd.vivo\"],\n [\"vlc\", \"application/videolan\"],\n [\"vmdk\", \"application/x-virtualbox-vmdk\"],\n [\"vob\", \"video/x-ms-vob\"],\n [\"vor\", \"application/vnd.stardivision.writer\"],\n [\"vox\", \"application/x-authorware-bin\"],\n [\"vrml\", \"model/vrml\"],\n [\"vsd\", \"application/vnd.visio\"],\n [\"vsf\", \"application/vnd.vsf\"],\n [\"vss\", \"application/vnd.visio\"],\n [\"vst\", \"application/vnd.visio\"],\n [\"vsw\", \"application/vnd.visio\"],\n [\"vtf\", \"image/vnd.valve.source.texture\"],\n [\"vtt\", \"text/vtt\"],\n [\"vtu\", \"model/vnd.vtu\"],\n [\"vxml\", \"application/voicexml+xml\"],\n [\"w3d\", \"application/x-director\"],\n [\"wad\", \"application/x-doom\"],\n [\"wadl\", \"application/vnd.sun.wadl+xml\"],\n [\"war\", \"application/java-archive\"],\n [\"wasm\", \"application/wasm\"],\n [\"wav\", \"audio/x-wav\"],\n [\"wax\", \"audio/x-ms-wax\"],\n [\"wbmp\", \"image/vnd.wap.wbmp\"],\n [\"wbs\", \"application/vnd.criticaltools.wbs+xml\"],\n [\"wbxml\", \"application/wbxml\"],\n [\"wcm\", \"application/vnd.ms-works\"],\n [\"wdb\", \"application/vnd.ms-works\"],\n [\"wdp\", \"image/vnd.ms-photo\"],\n [\"weba\", \"audio/webm\"],\n [\"webapp\", \"application/x-web-app-manifest+json\"],\n [\"webm\", \"video/webm\"],\n [\"webmanifest\", \"application/manifest+json\"],\n [\"webp\", \"image/webp\"],\n [\"wg\", \"application/vnd.pmi.widget\"],\n [\"wgt\", \"application/widget\"],\n [\"wks\", \"application/vnd.ms-works\"],\n [\"wm\", \"video/x-ms-wm\"],\n [\"wma\", \"audio/x-ms-wma\"],\n [\"wmd\", \"application/x-ms-wmd\"],\n [\"wmf\", \"image/wmf\"],\n [\"wml\", \"text/vnd.wap.wml\"],\n [\"wmlc\", \"application/wmlc\"],\n [\"wmls\", \"text/vnd.wap.wmlscript\"],\n [\"wmlsc\", \"application/vnd.wap.wmlscriptc\"],\n [\"wmv\", \"video/x-ms-wmv\"],\n [\"wmx\", \"video/x-ms-wmx\"],\n [\"wmz\", \"application/x-msmetafile\"],\n [\"woff\", \"font/woff\"],\n [\"woff2\", \"font/woff2\"],\n [\"word\", \"application/msword\"],\n [\"wpd\", \"application/vnd.wordperfect\"],\n [\"wpl\", \"application/vnd.ms-wpl\"],\n [\"wps\", \"application/vnd.ms-works\"],\n [\"wqd\", \"application/vnd.wqd\"],\n [\"wri\", \"application/x-mswrite\"],\n [\"wrl\", \"model/vrml\"],\n [\"wsc\", \"message/vnd.wfa.wsc\"],\n [\"wsdl\", \"application/wsdl+xml\"],\n [\"wspolicy\", \"application/wspolicy+xml\"],\n [\"wtb\", \"application/vnd.webturbo\"],\n [\"wvx\", \"video/x-ms-wvx\"],\n [\"x3d\", \"model/x3d+xml\"],\n [\"x3db\", \"model/x3d+fastinfoset\"],\n [\"x3dbz\", \"model/x3d+binary\"],\n [\"x3dv\", \"model/x3d-vrml\"],\n [\"x3dvz\", \"model/x3d+vrml\"],\n [\"x3dz\", \"model/x3d+xml\"],\n [\"x32\", \"application/x-authorware-bin\"],\n [\"x_b\", \"model/vnd.parasolid.transmit.binary\"],\n [\"x_t\", \"model/vnd.parasolid.transmit.text\"],\n [\"xaml\", \"application/xaml+xml\"],\n [\"xap\", \"application/x-silverlight-app\"],\n [\"xar\", \"application/vnd.xara\"],\n [\"xav\", \"application/xcap-att+xml\"],\n [\"xbap\", \"application/x-ms-xbap\"],\n [\"xbd\", \"application/vnd.fujixerox.docuworks.binder\"],\n [\"xbm\", \"image/x-xbitmap\"],\n [\"xca\", \"application/xcap-caps+xml\"],\n [\"xcs\", \"application/calendar+xml\"],\n [\"xdf\", \"application/xcap-diff+xml\"],\n [\"xdm\", \"application/vnd.syncml.dm+xml\"],\n [\"xdp\", \"application/vnd.adobe.xdp+xml\"],\n [\"xdssc\", \"application/dssc+xml\"],\n [\"xdw\", \"application/vnd.fujixerox.docuworks\"],\n [\"xel\", \"application/xcap-el+xml\"],\n [\"xenc\", \"application/xenc+xml\"],\n [\"xer\", \"application/patch-ops-error+xml\"],\n [\"xfdf\", \"application/vnd.adobe.xfdf\"],\n [\"xfdl\", \"application/vnd.xfdl\"],\n [\"xht\", \"application/xhtml+xml\"],\n [\"xhtml\", \"application/xhtml+xml\"],\n [\"xhvml\", \"application/xv+xml\"],\n [\"xif\", \"image/vnd.xiff\"],\n [\"xl\", \"application/excel\"],\n [\"xla\", \"application/vnd.ms-excel\"],\n [\"xlam\", \"application/vnd.ms-excel.addin.macroEnabled.12\"],\n [\"xlc\", \"application/vnd.ms-excel\"],\n [\"xlf\", \"application/xliff+xml\"],\n [\"xlm\", \"application/vnd.ms-excel\"],\n [\"xls\", \"application/vnd.ms-excel\"],\n [\"xlsb\", \"application/vnd.ms-excel.sheet.binary.macroEnabled.12\"],\n [\"xlsm\", \"application/vnd.ms-excel.sheet.macroEnabled.12\"],\n [\"xlsx\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"],\n [\"xlt\", \"application/vnd.ms-excel\"],\n [\"xltm\", \"application/vnd.ms-excel.template.macroEnabled.12\"],\n [\n \"xltx\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.template\"\n ],\n [\"xlw\", \"application/vnd.ms-excel\"],\n [\"xm\", \"audio/xm\"],\n [\"xml\", \"application/xml\"],\n [\"xns\", \"application/xcap-ns+xml\"],\n [\"xo\", \"application/vnd.olpc-sugar\"],\n [\"xop\", \"application/xop+xml\"],\n [\"xpi\", \"application/x-xpinstall\"],\n [\"xpl\", \"application/xproc+xml\"],\n [\"xpm\", \"image/x-xpixmap\"],\n [\"xpr\", \"application/vnd.is-xpr\"],\n [\"xps\", \"application/vnd.ms-xpsdocument\"],\n [\"xpw\", \"application/vnd.intercon.formnet\"],\n [\"xpx\", \"application/vnd.intercon.formnet\"],\n [\"xsd\", \"application/xml\"],\n [\"xsl\", \"application/xml\"],\n [\"xslt\", \"application/xslt+xml\"],\n [\"xsm\", \"application/vnd.syncml+xml\"],\n [\"xspf\", \"application/xspf+xml\"],\n [\"xul\", \"application/vnd.mozilla.xul+xml\"],\n [\"xvm\", \"application/xv+xml\"],\n [\"xvml\", \"application/xv+xml\"],\n [\"xwd\", \"image/x-xwindowdump\"],\n [\"xyz\", \"chemical/x-xyz\"],\n [\"xz\", \"application/x-xz\"],\n [\"yaml\", \"text/yaml\"],\n [\"yang\", \"application/yang\"],\n [\"yin\", \"application/yin+xml\"],\n [\"yml\", \"text/yaml\"],\n [\"ymp\", \"text/x-suse-ymp\"],\n [\"z\", \"application/x-compress\"],\n [\"z1\", \"application/x-zmachine\"],\n [\"z2\", \"application/x-zmachine\"],\n [\"z3\", \"application/x-zmachine\"],\n [\"z4\", \"application/x-zmachine\"],\n [\"z5\", \"application/x-zmachine\"],\n [\"z6\", \"application/x-zmachine\"],\n [\"z7\", \"application/x-zmachine\"],\n [\"z8\", \"application/x-zmachine\"],\n [\"zaz\", \"application/vnd.zzazz.deck+xml\"],\n [\"zip\", \"application/zip\"],\n [\"zir\", \"application/vnd.zul\"],\n [\"zirz\", \"application/vnd.zul\"],\n [\"zmm\", \"application/vnd.handheld-entertainment+xml\"],\n [\"zsh\", \"text/x-scriptzsh\"]\n]);\nfunction toFileWithPath(file, path, h) {\n const f = withMimeType(file);\n const { webkitRelativePath } = file;\n const p = typeof path === \"string\" ? path : (\n // If is set,\n // the File will have a {webkitRelativePath} property\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory\n typeof webkitRelativePath === \"string\" && webkitRelativePath.length > 0 ? webkitRelativePath : `./${file.name}`\n );\n if (typeof f.path !== \"string\") {\n setObjProp(f, \"path\", p);\n }\n if (h !== void 0) {\n Object.defineProperty(f, \"handle\", {\n value: h,\n writable: false,\n configurable: false,\n enumerable: true\n });\n }\n setObjProp(f, \"relativePath\", p);\n return f;\n}\nfunction withMimeType(file) {\n const { name } = file;\n const hasExtension = name && name.lastIndexOf(\".\") !== -1;\n if (hasExtension && !file.type) {\n const ext = name.split(\".\").pop().toLowerCase();\n const type = COMMON_MIME_TYPES.get(ext);\n if (type) {\n Object.defineProperty(file, \"type\", {\n value: type,\n writable: false,\n configurable: false,\n enumerable: true\n });\n }\n }\n return file;\n}\nfunction setObjProp(f, key, value) {\n Object.defineProperty(f, key, {\n value,\n writable: false,\n configurable: false,\n enumerable: true\n });\n}\n\nexport { COMMON_MIME_TYPES, toFileWithPath };\n","import { toFileWithPath } from './file.mjs';\n\nvar __async = (__this, __arguments, generator) => {\n return new Promise((resolve, reject) => {\n var fulfilled = (value) => {\n try {\n step(generator.next(value));\n } catch (e) {\n reject(e);\n }\n };\n var rejected = (value) => {\n try {\n step(generator.throw(value));\n } catch (e) {\n reject(e);\n }\n };\n var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);\n step((generator = generator.apply(__this, __arguments)).next());\n });\n};\nconst FILES_TO_IGNORE = [\n // Thumbnail cache files for macOS and Windows\n \".DS_Store\",\n // macOs\n \"Thumbs.db\"\n // Windows\n];\nfunction fromEvent(evt) {\n return __async(this, null, function* () {\n if (isObject(evt) && isDataTransfer(evt.dataTransfer)) {\n return getDataTransferFiles(evt.dataTransfer, evt.type);\n } else if (isChangeEvt(evt)) {\n return getInputFiles(evt);\n } else if (Array.isArray(evt) && evt.every((item) => \"getFile\" in item && typeof item.getFile === \"function\")) {\n return getFsHandleFiles(evt);\n }\n return [];\n });\n}\nfunction isDataTransfer(value) {\n return isObject(value);\n}\nfunction isChangeEvt(value) {\n return isObject(value) && isObject(value.target);\n}\nfunction isObject(v) {\n return typeof v === \"object\" && v !== null;\n}\nfunction getInputFiles(evt) {\n return fromList(evt.target.files).map((file) => toFileWithPath(file));\n}\nfunction getFsHandleFiles(handles) {\n return __async(this, null, function* () {\n const files = yield Promise.all(handles.map((h) => h.getFile()));\n return files.map((file) => toFileWithPath(file));\n });\n}\nfunction getDataTransferFiles(dt, type) {\n return __async(this, null, function* () {\n if (dt.items) {\n const items = fromList(dt.items).filter((item) => item.kind === \"file\");\n if (type !== \"drop\") {\n return items;\n }\n const files = yield Promise.all(items.map(toFilePromises));\n return noIgnoredFiles(flatten(files));\n }\n return noIgnoredFiles(fromList(dt.files).map((file) => toFileWithPath(file)));\n });\n}\nfunction noIgnoredFiles(files) {\n return files.filter((file) => FILES_TO_IGNORE.indexOf(file.name) === -1);\n}\nfunction fromList(items) {\n if (items === null) {\n return [];\n }\n const files = [];\n for (let i = 0; i < items.length; i++) {\n const file = items[i];\n files.push(file);\n }\n return files;\n}\nfunction toFilePromises(item) {\n if (typeof item.webkitGetAsEntry !== \"function\") {\n return fromDataTransferItem(item);\n }\n const entry = item.webkitGetAsEntry();\n if (entry && entry.isDirectory) {\n return fromDirEntry(entry);\n }\n return fromDataTransferItem(item, entry);\n}\nfunction flatten(items) {\n return items.reduce(\n (acc, files) => [\n ...acc,\n ...Array.isArray(files) ? flatten(files) : [files]\n ],\n []\n );\n}\nfunction fromDataTransferItem(item, entry) {\n var _a;\n if (typeof item.getAsFileSystemHandle === \"function\") {\n return item.getAsFileSystemHandle().then((h) => __async(this, null, function* () {\n const file2 = yield h.getFile();\n file2.handle = h;\n return toFileWithPath(file2);\n }));\n }\n const file = item.getAsFile();\n if (!file) {\n return Promise.reject(`${item} is not a File`);\n }\n const fwp = toFileWithPath(file, (_a = entry == null ? void 0 : entry.fullPath) != null ? _a : void 0);\n return Promise.resolve(fwp);\n}\nfunction fromEntry(entry) {\n return __async(this, null, function* () {\n return entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry);\n });\n}\nfunction fromDirEntry(entry) {\n const reader = entry.createReader();\n return new Promise((resolve, reject) => {\n const entries = [];\n function readEntries() {\n reader.readEntries(\n (batch) => __async(this, null, function* () {\n if (!batch.length) {\n try {\n const files = yield Promise.all(entries);\n resolve(files);\n } catch (err) {\n reject(err);\n }\n } else {\n const items = Promise.all(batch.map(fromEntry));\n entries.push(items);\n readEntries();\n }\n }),\n (err) => {\n reject(err);\n }\n );\n }\n readEntries();\n });\n}\nfunction fromFileEntry(entry) {\n return __async(this, null, function* () {\n return new Promise((resolve, reject) => {\n entry.file(\n (file) => {\n const fwp = toFileWithPath(file, entry.fullPath);\n resolve(fwp);\n },\n (err) => {\n reject(err);\n }\n );\n });\n });\n}\n\nexport { fromEvent };\n","function _accepts(file, acceptedFiles) {\n if (file && acceptedFiles) {\n const acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(\",\");\n if (acceptedFilesArray.length === 0) {\n return true;\n }\n const fileName = file.name || \"\";\n const mimeType = (file.type || \"\").toLowerCase();\n const baseMimeType = mimeType.replace(/\\/.*$/, \"\");\n return acceptedFilesArray.some((type) => {\n const validType = type.trim().toLowerCase();\n if (validType.charAt(0) === \".\") {\n return fileName.toLowerCase().endsWith(validType);\n } else if (validType.endsWith(\"/*\")) {\n return baseMimeType === validType.replace(/\\/.*$/, \"\");\n }\n return mimeType === validType;\n });\n }\n return true;\n}\n\nexport { _accepts as default };\n","import _accepts from './attr-accept.mjs';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst accepts = typeof _accepts === \"function\" ? _accepts : _accepts.default;\nconst FILE_INVALID_TYPE = \"file-invalid-type\";\nconst FILE_TOO_LARGE = \"file-too-large\";\nconst FILE_TOO_SMALL = \"file-too-small\";\nconst TOO_MANY_FILES = \"too-many-files\";\nconst ErrorCode = {\n FileInvalidType: FILE_INVALID_TYPE,\n FileTooLarge: FILE_TOO_LARGE,\n FileTooSmall: FILE_TOO_SMALL,\n TooManyFiles: TOO_MANY_FILES\n};\nconst getInvalidTypeRejectionErr = (accept = \"\") => {\n const acceptArr = accept.split(\",\");\n const msg = acceptArr.length > 1 ? `one of ${acceptArr.join(\", \")}` : acceptArr[0];\n return {\n code: FILE_INVALID_TYPE,\n message: `File type must be ${msg}`\n };\n};\nconst getTooLargeRejectionErr = (maxSize) => {\n return {\n code: FILE_TOO_LARGE,\n message: `File is larger than ${maxSize} ${maxSize === 1 ? \"byte\" : \"bytes\"}`\n };\n};\nconst getTooSmallRejectionErr = (minSize) => {\n return {\n code: FILE_TOO_SMALL,\n message: `File is smaller than ${minSize} ${minSize === 1 ? \"byte\" : \"bytes\"}`\n };\n};\nconst TOO_MANY_FILES_REJECTION = {\n code: TOO_MANY_FILES,\n message: \"Too many files\"\n};\nfunction fileAccepted(file, accept) {\n const isAcceptable = file.type === \"application/x-moz-file\" || accepts(file, accept);\n return [\n isAcceptable,\n isAcceptable ? null : getInvalidTypeRejectionErr(accept)\n ];\n}\nfunction fileMatchSize(file, minSize, maxSize) {\n if (isDefined(file.size)) {\n if (isDefined(minSize) && isDefined(maxSize)) {\n if (file.size > maxSize)\n return [false, getTooLargeRejectionErr(maxSize)];\n if (file.size < minSize)\n return [false, getTooSmallRejectionErr(minSize)];\n } else if (isDefined(minSize) && file.size < minSize)\n return [false, getTooSmallRejectionErr(minSize)];\n else if (isDefined(maxSize) && file.size > maxSize)\n return [false, getTooLargeRejectionErr(maxSize)];\n }\n return [true, null];\n}\nfunction isDefined(value) {\n return value !== void 0 && value !== null;\n}\nfunction allFilesAccepted({\n files,\n accept,\n minSize,\n maxSize,\n multiple,\n maxFiles,\n validator\n}) {\n if (!multiple && files.length > 1 || multiple && maxFiles >= 1 && files.length > maxFiles) {\n return false;\n }\n return files.every((file) => {\n const [accepted] = fileAccepted(file, accept);\n const [sizeMatch] = fileMatchSize(file, minSize, maxSize);\n const customErrors = validator ? validator(file) : null;\n return accepted && sizeMatch && !customErrors;\n });\n}\nfunction isPropagationStopped(event) {\n if (typeof event.isPropagationStopped === \"function\") {\n return event.isPropagationStopped();\n } else if (typeof event.cancelBubble !== \"undefined\") {\n return event.cancelBubble;\n }\n return false;\n}\nfunction isEvtWithFiles(event) {\n if (!event.dataTransfer) {\n return !!event.target && !!event.target.files;\n }\n return Array.prototype.some.call(\n event.dataTransfer.types,\n (type) => type === \"Files\" || type === \"application/x-moz-file\"\n );\n}\nfunction onDocumentDragOver(event) {\n event.preventDefault();\n}\nfunction isIe(userAgent) {\n return userAgent.indexOf(\"MSIE\") !== -1 || userAgent.indexOf(\"Trident/\") !== -1;\n}\nfunction isEdge(userAgent) {\n return userAgent.indexOf(\"Edge/\") !== -1;\n}\nfunction isIeOrEdge(userAgent = window.navigator.userAgent) {\n return isIe(userAgent) || isEdge(userAgent);\n}\nfunction composeEventHandlers(...fns) {\n return (event, ...args) => fns.some((fn) => {\n if (!isPropagationStopped(event) && fn) {\n fn(event, ...args);\n }\n return isPropagationStopped(event);\n });\n}\nfunction canUseFileSystemAccessAPI() {\n return \"showOpenFilePicker\" in window;\n}\nfunction pickerOptionsFromAccept(accept) {\n if (isDefined(accept)) {\n const acceptForPicker = Object.entries(accept).filter(([mimeType, ext]) => {\n let ok = true;\n if (!isMIMEType(mimeType)) {\n console.warn(\n `Skipped \"${mimeType}\" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.`\n );\n ok = false;\n }\n if (!Array.isArray(ext) || !ext.every(isExt)) {\n console.warn(\n `Skipped \"${mimeType}\" because an invalid file extension was provided.`\n );\n ok = false;\n }\n return ok;\n }).reduce(\n (agg, [mimeType, ext]) => __spreadProps(__spreadValues({}, agg), {\n [mimeType]: ext\n }),\n {}\n );\n return [\n {\n // description is required due to https://crbug.com/1264708\n description: \"Files\",\n accept: acceptForPicker\n }\n ];\n }\n return accept;\n}\nfunction acceptPropAsAcceptAttr(accept) {\n if (isDefined(accept)) {\n return Object.entries(accept).reduce((a, [mimeType, ext]) => [...a, mimeType, ...ext], []).filter((v) => isMIMEType(v) || isExt(v)).join(\",\");\n }\n return void 0;\n}\nfunction isAbort(v) {\n return v instanceof DOMException && (v.name === \"AbortError\" || v.code === v.ABORT_ERR);\n}\nfunction isSecurityError(v) {\n return v instanceof DOMException && (v.name === \"SecurityError\" || v.code === v.SECURITY_ERR);\n}\nfunction isMIMEType(v) {\n return v === \"audio/*\" || v === \"video/*\" || v === \"image/*\" || v === \"text/*\" || v === \"application/*\" || /\\w+\\/[-+.\\w]+/g.test(v);\n}\nfunction isExt(v) {\n return /^.*\\.[\\w]+$/.test(v);\n}\n\nexport { ErrorCode, FILE_INVALID_TYPE, FILE_TOO_LARGE, FILE_TOO_SMALL, TOO_MANY_FILES, TOO_MANY_FILES_REJECTION, acceptPropAsAcceptAttr, allFilesAccepted, canUseFileSystemAccessAPI, composeEventHandlers, fileAccepted, fileMatchSize, getInvalidTypeRejectionErr, getTooLargeRejectionErr, getTooSmallRejectionErr, isAbort, isEvtWithFiles, isExt, isIeOrEdge, isMIMEType, isPropagationStopped, isSecurityError, onDocumentDragOver, pickerOptionsFromAccept };\n","'use client';\nimport React, { forwardRef, useImperativeHandle, Fragment, useMemo, useRef, useReducer, useEffect, useCallback } from 'react';\nimport PropTypes from 'prop-types';\nimport { fromEvent } from './file-selector.mjs';\nimport { acceptPropAsAcceptAttr, pickerOptionsFromAccept, canUseFileSystemAccessAPI, onDocumentDragOver, isEvtWithFiles, isPropagationStopped, allFilesAccepted, fileAccepted, fileMatchSize, TOO_MANY_FILES_REJECTION, isAbort, isSecurityError, isIeOrEdge, composeEventHandlers } from './utils.mjs';\nexport { ErrorCode } from './utils.mjs';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nvar __objRest = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nconst Dropzone = forwardRef((_a, ref) => {\n var _b = _a, { children } = _b, params = __objRest(_b, [\"children\"]);\n const _a2 = useDropzone(params), { open } = _a2, props = __objRest(_a2, [\"open\"]);\n useImperativeHandle(ref, () => ({ open }), [open]);\n return /* @__PURE__ */ React.createElement(Fragment, null, children(__spreadProps(__spreadValues({}, props), { open })));\n});\nDropzone.displayName = \"Dropzone\";\nconst defaultProps = {\n disabled: false,\n getFilesFromEvent: fromEvent,\n maxSize: Infinity,\n minSize: 0,\n multiple: true,\n maxFiles: 0,\n preventDropOnDocument: true,\n noClick: false,\n noKeyboard: false,\n noDrag: false,\n noDragEventsBubbling: false,\n validator: null,\n useFsAccessApi: false,\n autoFocus: false\n};\nDropzone.defaultProps = defaultProps;\nDropzone.propTypes = {\n /**\n * Render function that exposes the dropzone state and prop getter fns\n *\n * @param {object} params\n * @param {Function} params.getRootProps Returns the props you should apply to the root drop container you render\n * @param {Function} params.getInputProps Returns the props you should apply to hidden file input you render\n * @param {Function} params.open Open the native file selection dialog\n * @param {boolean} params.isFocused Dropzone area is in focus\n * @param {boolean} params.isFileDialogActive File dialog is opened\n * @param {boolean} params.isDragActive Active drag is in progress\n * @param {boolean} params.isDragAccept Dragged files are accepted\n * @param {boolean} params.isDragReject Some dragged files are rejected\n * @param {File[]} params.acceptedFiles Accepted files\n * @param {FileRejection[]} params.fileRejections Rejected files and why they were rejected\n */\n children: PropTypes.func,\n /**\n * Set accepted file types.\n * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.\n * Keep in mind that mime type determination is not reliable across platforms. CSV files,\n * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under\n * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276).\n */\n accept: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),\n /**\n * Allow drag 'n' drop (or selection from the file dialog) of multiple files\n */\n multiple: PropTypes.bool,\n /**\n * If false, allow dropped items to take over the current browser window\n */\n preventDropOnDocument: PropTypes.bool,\n /**\n * If true, disables click to open the native file selection dialog\n */\n noClick: PropTypes.bool,\n /**\n * If true, disables SPACE/ENTER to open the native file selection dialog.\n * Note that it also stops tracking the focus state.\n */\n noKeyboard: PropTypes.bool,\n /**\n * If true, disables drag 'n' drop\n */\n noDrag: PropTypes.bool,\n /**\n * If true, stops drag event propagation to parents\n */\n noDragEventsBubbling: PropTypes.bool,\n /**\n * Minimum file size (in bytes)\n */\n minSize: PropTypes.number,\n /**\n * Maximum file size (in bytes)\n */\n maxSize: PropTypes.number,\n /**\n * Maximum accepted number of files\n * The default value is 0 which means there is no limitation to how many files are accepted.\n */\n maxFiles: PropTypes.number,\n /**\n * Enable/disable the dropzone\n */\n disabled: PropTypes.bool,\n /**\n * Use this to provide a custom file aggregator\n *\n * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)\n */\n getFilesFromEvent: PropTypes.func,\n /**\n * Cb for when closing the file dialog with no selection\n */\n onFileDialogCancel: PropTypes.func,\n /**\n * Cb for when opening the file dialog\n */\n onFileDialogOpen: PropTypes.func,\n /**\n * Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API\n * to open the file picker instead of using an `` click event.\n */\n useFsAccessApi: PropTypes.bool,\n /**\n * Set to true to focus the root element on render\n */\n autoFocus: PropTypes.bool,\n /**\n * Cb for when the `dragenter` event occurs.\n *\n * @param {DragEvent} event\n */\n onDragEnter: PropTypes.func,\n /**\n * Cb for when the `dragleave` event occurs\n *\n * @param {DragEvent} event\n */\n onDragLeave: PropTypes.func,\n /**\n * Cb for when the `dragover` event occurs\n *\n * @param {DragEvent} event\n */\n onDragOver: PropTypes.func,\n /**\n * Cb for when the `drop` event occurs.\n * Note that this callback is invoked after the `getFilesFromEvent` callback is done.\n *\n * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.\n * `accept` must be a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) or a valid file extension.\n * If `multiple` is set to false and additional files are dropped,\n * all files besides the first will be rejected.\n * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.\n *\n * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.\n * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.\n *\n * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server.\n * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:\n *\n * ```js\n * function onDrop(acceptedFiles) {\n * const req = request.post('/upload')\n * acceptedFiles.forEach(file => {\n * req.attach(file.name, file)\n * })\n * req.end(callback)\n * }\n * ```\n *\n * @param {File[]} acceptedFiles\n * @param {FileRejection[]} fileRejections\n * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)\n */\n onDrop: PropTypes.func,\n /**\n * Cb for when the `drop` event occurs.\n * Note that if no files are accepted, this callback is not invoked.\n *\n * @param {File[]} files\n * @param {(DragEvent|Event)} event\n */\n onDropAccepted: PropTypes.func,\n /**\n * Cb for when the `drop` event occurs.\n * Note that if no files are rejected, this callback is not invoked.\n *\n * @param {FileRejection[]} fileRejections\n * @param {(DragEvent|Event)} event\n */\n onDropRejected: PropTypes.func,\n /**\n * Cb for when there's some error from any of the promises.\n *\n * @param {Error} error\n */\n onError: PropTypes.func,\n /**\n * Custom validation function. It must return null if there's no errors.\n * @param {File} file\n * @returns {FileError|FileError[]|null}\n */\n validator: PropTypes.func\n};\nconst initialState = {\n isFocused: false,\n isFileDialogActive: false,\n isDragActive: false,\n isDragAccept: false,\n isDragReject: false,\n acceptedFiles: [],\n fileRejections: []\n};\nfunction useDropzone(props = {}) {\n const {\n accept,\n disabled,\n getFilesFromEvent,\n maxSize,\n minSize,\n multiple,\n maxFiles,\n onDragEnter,\n onDragLeave,\n onDragOver,\n onDrop,\n onDropAccepted,\n onDropRejected,\n onFileDialogCancel,\n onFileDialogOpen,\n useFsAccessApi,\n autoFocus,\n preventDropOnDocument,\n noClick,\n noKeyboard,\n noDrag,\n noDragEventsBubbling,\n onError,\n validator\n } = __spreadValues(__spreadValues({}, defaultProps), props);\n const acceptAttr = useMemo(() => acceptPropAsAcceptAttr(accept), [accept]);\n const pickerTypes = useMemo(() => pickerOptionsFromAccept(accept), [accept]);\n const onFileDialogOpenCb = useMemo(\n () => typeof onFileDialogOpen === \"function\" ? onFileDialogOpen : noop,\n [onFileDialogOpen]\n );\n const onFileDialogCancelCb = useMemo(\n () => typeof onFileDialogCancel === \"function\" ? onFileDialogCancel : noop,\n [onFileDialogCancel]\n );\n const rootRef = useRef(null);\n const inputRef = useRef(null);\n const [state, dispatch] = useReducer(reducer, initialState);\n const { isFocused, isFileDialogActive } = state;\n const fsAccessApiWorksRef = useRef(\n typeof window !== \"undefined\" && window.isSecureContext && useFsAccessApi && canUseFileSystemAccessAPI()\n );\n const onWindowFocus = () => {\n if (!fsAccessApiWorksRef.current && isFileDialogActive) {\n setTimeout(() => {\n if (inputRef.current) {\n const { files } = inputRef.current;\n if (!files.length) {\n dispatch({ type: \"closeDialog\" });\n onFileDialogCancelCb();\n }\n }\n }, 300);\n }\n };\n useEffect(() => {\n window.addEventListener(\"focus\", onWindowFocus, false);\n return () => {\n window.removeEventListener(\"focus\", onWindowFocus, false);\n };\n }, [inputRef, isFileDialogActive, onFileDialogCancelCb, fsAccessApiWorksRef]);\n const dragTargetsRef = useRef([]);\n const onDocumentDrop = (event) => {\n if (rootRef.current && rootRef.current.contains(event.target)) {\n return;\n }\n event.preventDefault();\n dragTargetsRef.current = [];\n };\n useEffect(() => {\n if (preventDropOnDocument) {\n document.addEventListener(\"dragover\", onDocumentDragOver, false);\n document.addEventListener(\"drop\", onDocumentDrop, false);\n }\n return () => {\n if (preventDropOnDocument) {\n document.removeEventListener(\"dragover\", onDocumentDragOver);\n document.removeEventListener(\"drop\", onDocumentDrop);\n }\n };\n }, [rootRef, preventDropOnDocument]);\n useEffect(() => {\n if (!disabled && autoFocus && rootRef.current) {\n rootRef.current.focus();\n }\n return () => {\n };\n }, [rootRef, autoFocus, disabled]);\n const onErrCb = useCallback(\n (e) => {\n if (onError) {\n onError(e);\n } else {\n console.error(e);\n }\n },\n [onError]\n );\n const onDragEnterCb = useCallback(\n (event) => {\n event.preventDefault();\n event.persist();\n stopPropagation(event);\n dragTargetsRef.current = [...dragTargetsRef.current, event.target];\n if (isEvtWithFiles(event)) {\n Promise.resolve(getFilesFromEvent(event)).then((files) => {\n if (isPropagationStopped(event) && !noDragEventsBubbling) {\n return;\n }\n const fileCount = files.length;\n const isDragAccept = fileCount > 0 && allFilesAccepted({\n files,\n accept: acceptAttr,\n minSize,\n maxSize,\n multiple,\n maxFiles,\n validator\n });\n const isDragReject = fileCount > 0 && !isDragAccept;\n dispatch({\n isDragAccept,\n isDragReject,\n isDragActive: true,\n type: \"setDraggedFiles\"\n });\n if (onDragEnter) {\n onDragEnter(event);\n }\n }).catch((e) => onErrCb(e));\n }\n },\n [\n getFilesFromEvent,\n onDragEnter,\n onErrCb,\n noDragEventsBubbling,\n acceptAttr,\n minSize,\n maxSize,\n multiple,\n maxFiles,\n validator\n ]\n );\n const onDragOverCb = useCallback(\n (event) => {\n event.preventDefault();\n event.persist();\n stopPropagation(event);\n const hasFiles = isEvtWithFiles(event);\n if (hasFiles && event.dataTransfer) {\n try {\n event.dataTransfer.dropEffect = \"copy\";\n } catch (e) {\n }\n }\n if (hasFiles && onDragOver) {\n onDragOver(event);\n }\n return false;\n },\n [onDragOver, noDragEventsBubbling]\n );\n const onDragLeaveCb = useCallback(\n (event) => {\n event.preventDefault();\n event.persist();\n stopPropagation(event);\n const targets = dragTargetsRef.current.filter(\n (target) => rootRef.current && rootRef.current.contains(target)\n );\n const targetIdx = targets.indexOf(event.target);\n if (targetIdx !== -1) {\n targets.splice(targetIdx, 1);\n }\n dragTargetsRef.current = targets;\n if (targets.length > 0) {\n return;\n }\n dispatch({\n type: \"setDraggedFiles\",\n isDragActive: false,\n isDragAccept: false,\n isDragReject: false\n });\n if (isEvtWithFiles(event) && onDragLeave) {\n onDragLeave(event);\n }\n },\n [rootRef, onDragLeave, noDragEventsBubbling]\n );\n const setFiles = useCallback(\n (files, event) => {\n const acceptedFiles = [];\n const fileRejections = [];\n files.forEach((file) => {\n const [accepted, acceptError] = fileAccepted(file, acceptAttr);\n const [sizeMatch, sizeError] = fileMatchSize(file, minSize, maxSize);\n const customErrors = validator ? validator(file) : null;\n if (accepted && sizeMatch && !customErrors) {\n acceptedFiles.push(file);\n } else {\n let errors = [acceptError, sizeError];\n if (customErrors) {\n errors = errors.concat(customErrors);\n }\n fileRejections.push({ file, errors: errors.filter((e) => e) });\n }\n });\n if (!multiple && acceptedFiles.length > 1 || multiple && maxFiles >= 1 && acceptedFiles.length > maxFiles) {\n acceptedFiles.forEach((file) => {\n fileRejections.push({ file, errors: [TOO_MANY_FILES_REJECTION] });\n });\n acceptedFiles.splice(0);\n }\n dispatch({\n acceptedFiles,\n fileRejections,\n isDragReject: fileRejections.length > 0,\n type: \"setFiles\"\n });\n if (onDrop) {\n onDrop(acceptedFiles, fileRejections, event);\n }\n if (fileRejections.length > 0 && onDropRejected) {\n onDropRejected(fileRejections, event);\n }\n if (acceptedFiles.length > 0 && onDropAccepted) {\n onDropAccepted(acceptedFiles, event);\n }\n },\n [\n dispatch,\n multiple,\n acceptAttr,\n minSize,\n maxSize,\n maxFiles,\n onDrop,\n onDropAccepted,\n onDropRejected,\n validator\n ]\n );\n const onDropCb = useCallback(\n (event) => {\n event.preventDefault();\n event.persist();\n stopPropagation(event);\n dragTargetsRef.current = [];\n if (isEvtWithFiles(event)) {\n Promise.resolve(getFilesFromEvent(event)).then((files) => {\n if (isPropagationStopped(event) && !noDragEventsBubbling) {\n return;\n }\n setFiles(files, event);\n }).catch((e) => onErrCb(e));\n }\n dispatch({ type: \"reset\" });\n },\n [getFilesFromEvent, setFiles, onErrCb, noDragEventsBubbling]\n );\n const openFileDialog = useCallback(() => {\n if (fsAccessApiWorksRef.current) {\n dispatch({ type: \"openDialog\" });\n onFileDialogOpenCb();\n const opts = {\n multiple,\n types: pickerTypes\n };\n window.showOpenFilePicker(opts).then((handles) => getFilesFromEvent(handles)).then((files) => {\n setFiles(files, null);\n dispatch({ type: \"closeDialog\" });\n }).catch((e) => {\n if (isAbort(e)) {\n onFileDialogCancelCb(e);\n dispatch({ type: \"closeDialog\" });\n } else if (isSecurityError(e)) {\n fsAccessApiWorksRef.current = false;\n if (inputRef.current) {\n inputRef.current.value = null;\n inputRef.current.click();\n } else {\n onErrCb(\n new Error(\n \"Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no was provided.\"\n )\n );\n }\n } else {\n onErrCb(e);\n }\n });\n return;\n }\n if (inputRef.current) {\n dispatch({ type: \"openDialog\" });\n onFileDialogOpenCb();\n inputRef.current.value = null;\n inputRef.current.click();\n }\n }, [\n dispatch,\n onFileDialogOpenCb,\n onFileDialogCancelCb,\n useFsAccessApi,\n setFiles,\n onErrCb,\n pickerTypes,\n multiple\n ]);\n const onKeyDownCb = useCallback(\n (event) => {\n if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) {\n return;\n }\n if (event.key === \" \" || event.key === \"Enter\" || event.keyCode === 32 || event.keyCode === 13) {\n event.preventDefault();\n openFileDialog();\n }\n },\n [rootRef, openFileDialog]\n );\n const onFocusCb = useCallback(() => {\n dispatch({ type: \"focus\" });\n }, []);\n const onBlurCb = useCallback(() => {\n dispatch({ type: \"blur\" });\n }, []);\n const onClickCb = useCallback(() => {\n if (noClick) {\n return;\n }\n if (isIeOrEdge()) {\n setTimeout(openFileDialog, 0);\n } else {\n openFileDialog();\n }\n }, [noClick, openFileDialog]);\n const composeHandler = (fn) => {\n return disabled ? null : fn;\n };\n const composeKeyboardHandler = (fn) => {\n return noKeyboard ? null : composeHandler(fn);\n };\n const composeDragHandler = (fn) => {\n return noDrag ? null : composeHandler(fn);\n };\n const stopPropagation = (event) => {\n if (noDragEventsBubbling) {\n event.stopPropagation();\n }\n };\n const getRootProps = useMemo(\n () => (_a = {}) => {\n var _b = _a, {\n refKey = \"ref\",\n role,\n onKeyDown,\n onFocus,\n onBlur,\n onClick,\n onDragEnter: onDragEnter2,\n onDragOver: onDragOver2,\n onDragLeave: onDragLeave2,\n onDrop: onDrop2\n } = _b, rest = __objRest(_b, [\n \"refKey\",\n \"role\",\n \"onKeyDown\",\n \"onFocus\",\n \"onBlur\",\n \"onClick\",\n \"onDragEnter\",\n \"onDragOver\",\n \"onDragLeave\",\n \"onDrop\"\n ]);\n return __spreadValues(__spreadValues({\n onKeyDown: composeKeyboardHandler(\n composeEventHandlers(onKeyDown, onKeyDownCb)\n ),\n onFocus: composeKeyboardHandler(\n composeEventHandlers(onFocus, onFocusCb)\n ),\n onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)),\n onClick: composeHandler(composeEventHandlers(onClick, onClickCb)),\n onDragEnter: composeDragHandler(\n composeEventHandlers(onDragEnter2, onDragEnterCb)\n ),\n onDragOver: composeDragHandler(\n composeEventHandlers(onDragOver2, onDragOverCb)\n ),\n onDragLeave: composeDragHandler(\n composeEventHandlers(onDragLeave2, onDragLeaveCb)\n ),\n onDrop: composeDragHandler(composeEventHandlers(onDrop2, onDropCb)),\n role: typeof role === \"string\" && role !== \"\" ? role : \"presentation\",\n [refKey]: rootRef\n }, !disabled && !noKeyboard ? { tabIndex: 0 } : {}), rest);\n },\n [\n rootRef,\n onKeyDownCb,\n onFocusCb,\n onBlurCb,\n onClickCb,\n onDragEnterCb,\n onDragOverCb,\n onDragLeaveCb,\n onDropCb,\n noKeyboard,\n noDrag,\n disabled\n ]\n );\n const onInputElementClick = useCallback((event) => {\n event.stopPropagation();\n }, []);\n const getInputProps = useMemo(\n () => (_a = {}) => {\n var _b = _a, { refKey = \"ref\", onChange, onClick } = _b, rest = __objRest(_b, [\"refKey\", \"onChange\", \"onClick\"]);\n const inputProps = {\n accept: acceptAttr,\n multiple,\n type: \"file\",\n style: {\n border: 0,\n clip: \"rect(0, 0, 0, 0)\",\n clipPath: \"inset(50%)\",\n height: \"1px\",\n margin: \"0 -1px -1px 0\",\n overflow: \"hidden\",\n padding: 0,\n position: \"absolute\",\n width: \"1px\",\n whiteSpace: \"nowrap\"\n },\n onChange: composeHandler(composeEventHandlers(onChange, onDropCb)),\n onClick: composeHandler(\n composeEventHandlers(onClick, onInputElementClick)\n ),\n tabIndex: -1,\n [refKey]: inputRef\n };\n return __spreadValues(__spreadValues({}, inputProps), rest);\n },\n [inputRef, accept, multiple, onDropCb, disabled]\n );\n return __spreadProps(__spreadValues({}, state), {\n isFocused: isFocused && !disabled,\n getRootProps,\n getInputProps,\n rootRef,\n inputRef,\n open: composeHandler(openFileDialog)\n });\n}\nfunction reducer(state, action) {\n switch (action.type) {\n case \"focus\":\n return __spreadProps(__spreadValues({}, state), {\n isFocused: true\n });\n case \"blur\":\n return __spreadProps(__spreadValues({}, state), {\n isFocused: false\n });\n case \"openDialog\":\n return __spreadProps(__spreadValues({}, initialState), {\n isFileDialogActive: true\n });\n case \"closeDialog\":\n return __spreadProps(__spreadValues({}, state), {\n isFileDialogActive: false\n });\n case \"setDraggedFiles\":\n return __spreadProps(__spreadValues({}, state), {\n isDragActive: action.isDragActive,\n isDragAccept: action.isDragAccept,\n isDragReject: action.isDragReject\n });\n case \"setFiles\":\n return __spreadProps(__spreadValues({}, state), {\n acceptedFiles: action.acceptedFiles,\n fileRejections: action.fileRejections,\n isDragReject: action.isDragReject\n });\n case \"reset\":\n return __spreadValues({}, initialState);\n default:\n return state;\n }\n}\nfunction noop() {\n}\n\nexport { Dropzone as default, useDropzone };\n","'use client';\nimport { createSafeContext } from '@mantine/core';\n\nconst [DropzoneProvider, useDropzoneContext] = createSafeContext(\n \"Dropzone component was not found in tree\"\n);\n\nexport { DropzoneProvider, useDropzoneContext };\n//# sourceMappingURL=Dropzone.context.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { cloneElement } from 'react';\nimport { useProps, isElement } from '@mantine/core';\nimport { upperFirst } from '@mantine/hooks';\nimport { useDropzoneContext } from './Dropzone.context.mjs';\n\nfunction createDropzoneStatus(status) {\n const Component = (props) => {\n const { children, ...others } = useProps(`Dropzone${upperFirst(status)}`, {}, props);\n const ctx = useDropzoneContext();\n const _children = isElement(children) ? children : /* @__PURE__ */ jsx(\"span\", { children });\n if (ctx[status]) {\n return cloneElement(_children, others);\n }\n return null;\n };\n Component.displayName = `@mantine/dropzone/${upperFirst(status)}`;\n return Component;\n}\nconst DropzoneAccept = createDropzoneStatus(\"accept\");\nconst DropzoneReject = createDropzoneStatus(\"reject\");\nconst DropzoneIdle = createDropzoneStatus(\"idle\");\n\nexport { DropzoneAccept, DropzoneIdle, DropzoneReject };\n//# sourceMappingURL=DropzoneStatus.mjs.map\n","'use client';\nvar classes = {\"root\":\"m_d46a4834\",\"inner\":\"m_b85f7144\",\"fullScreen\":\"m_96f6e9ad\",\"dropzone\":\"m_7946116d\"};\n\nexport { classes as default };\n//# sourceMappingURL=Dropzone.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { useDropzone } from 'react-dropzone-esm';\nimport { createVarsResolver, getRadius, factory, useProps, useStyles, Box, LoadingOverlay } from '@mantine/core';\nimport { assignRef } from '@mantine/hooks';\nimport { DropzoneProvider } from './Dropzone.context.mjs';\nimport { DropzoneAccept, DropzoneIdle, DropzoneReject } from './DropzoneStatus.mjs';\nimport classes from './Dropzone.module.css.mjs';\n\nconst defaultProps = {\n loading: false,\n multiple: true,\n maxSize: Infinity,\n autoFocus: false,\n activateOnClick: true,\n activateOnDrag: true,\n dragEventsBubbling: true,\n activateOnKeyboard: true,\n useFsAccessApi: true,\n variant: \"light\",\n rejectColor: \"red\"\n};\nconst varsResolver = createVarsResolver(\n (theme, { radius, variant, acceptColor, rejectColor }) => {\n const acceptColors = theme.variantColorResolver({\n color: acceptColor || theme.primaryColor,\n theme,\n variant\n });\n const rejectColors = theme.variantColorResolver({\n color: rejectColor || \"red\",\n theme,\n variant\n });\n return {\n root: {\n \"--dropzone-radius\": getRadius(radius),\n \"--dropzone-accept-color\": acceptColors.color,\n \"--dropzone-accept-bg\": acceptColors.background,\n \"--dropzone-reject-color\": rejectColors.color,\n \"--dropzone-reject-bg\": rejectColors.background\n }\n };\n }\n);\nconst Dropzone = factory((_props, ref) => {\n const props = useProps(\"Dropzone\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n radius,\n disabled,\n loading,\n multiple,\n maxSize,\n accept,\n children,\n onDropAny,\n onDrop,\n onReject,\n openRef,\n name,\n maxFiles,\n autoFocus,\n activateOnClick,\n activateOnDrag,\n dragEventsBubbling,\n activateOnKeyboard,\n onDragEnter,\n onDragLeave,\n onDragOver,\n onFileDialogCancel,\n onFileDialogOpen,\n preventDropOnDocument,\n useFsAccessApi,\n getFilesFromEvent,\n validator,\n rejectColor,\n acceptColor,\n enablePointerEvents,\n loaderProps,\n inputProps,\n mod,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"Dropzone\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver\n });\n const { getRootProps, getInputProps, isDragAccept, isDragReject, open } = useDropzone({\n onDrop: onDropAny,\n onDropAccepted: onDrop,\n onDropRejected: onReject,\n disabled: disabled || loading,\n accept: Array.isArray(accept) ? accept.reduce((r, key) => ({ ...r, [key]: [] }), {}) : accept,\n multiple,\n maxSize,\n maxFiles,\n autoFocus,\n noClick: !activateOnClick,\n noDrag: !activateOnDrag,\n noDragEventsBubbling: !dragEventsBubbling,\n noKeyboard: !activateOnKeyboard,\n onDragEnter,\n onDragLeave,\n onDragOver,\n onFileDialogCancel,\n onFileDialogOpen,\n preventDropOnDocument,\n useFsAccessApi,\n validator,\n ...getFilesFromEvent ? { getFilesFromEvent } : null\n });\n assignRef(openRef, open);\n const isIdle = !isDragAccept && !isDragReject;\n return /* @__PURE__ */ jsx(DropzoneProvider, { value: { accept: isDragAccept, reject: isDragReject, idle: isIdle }, children: /* @__PURE__ */ jsxs(\n Box,\n {\n ...getRootProps(),\n ...getStyles(\"root\", { focusable: true }),\n ...others,\n mod: [\n {\n accept: isDragAccept,\n reject: isDragReject,\n idle: isIdle,\n disabled,\n loading,\n \"activate-on-click\": activateOnClick\n },\n mod\n ],\n children: [\n /* @__PURE__ */ jsx(\n LoadingOverlay,\n {\n visible: loading,\n overlayProps: { radius },\n unstyled,\n loaderProps\n }\n ),\n /* @__PURE__ */ jsx(\"input\", { ...getInputProps(inputProps), name }),\n /* @__PURE__ */ jsx(\n \"div\",\n {\n ...getStyles(\"inner\"),\n ref,\n \"data-enable-pointer-events\": enablePointerEvents || void 0,\n children\n }\n )\n ]\n }\n ) });\n});\nDropzone.classes = classes;\nDropzone.displayName = \"@mantine/dropzone/Dropzone\";\nDropzone.Accept = DropzoneAccept;\nDropzone.Idle = DropzoneIdle;\nDropzone.Reject = DropzoneReject;\n\nexport { Dropzone };\n//# sourceMappingURL=Dropzone.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { useState, useEffect } from 'react';\nimport { getDefaultZIndex, factory, useProps, useStyles, useResolvedStylesApi, OptionalPortal, Box } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { Dropzone } from './Dropzone.mjs';\nimport classes from './Dropzone.module.css.mjs';\n\nconst defaultProps = {\n loading: false,\n maxSize: Infinity,\n activateOnClick: false,\n activateOnDrag: true,\n dragEventsBubbling: true,\n activateOnKeyboard: true,\n active: true,\n zIndex: getDefaultZIndex(\"max\"),\n withinPortal: true\n};\nconst DropzoneFullScreen = factory((_props, ref) => {\n const props = useProps(\"DropzoneFullScreen\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n active,\n onDrop,\n onReject,\n zIndex,\n withinPortal,\n portalProps,\n ...others\n } = props;\n const getStyles = useStyles({\n name: \"DropzoneFullScreen\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n rootSelector: \"fullScreen\"\n });\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n const [counter, setCounter] = useState(0);\n const [visible, { open, close }] = useDisclosure(false);\n const handleDragEnter = (event) => {\n if (event.dataTransfer?.types.includes(\"Files\")) {\n setCounter((prev) => prev + 1);\n open();\n }\n };\n const handleDragLeave = () => {\n setCounter((prev) => prev - 1);\n };\n useEffect(() => {\n counter === 0 && close();\n }, [counter]);\n useEffect(() => {\n if (!active) {\n return void 0;\n }\n document.addEventListener(\"dragenter\", handleDragEnter, false);\n document.addEventListener(\"dragleave\", handleDragLeave, false);\n return () => {\n document.removeEventListener(\"dragenter\", handleDragEnter, false);\n document.removeEventListener(\"dragleave\", handleDragLeave, false);\n };\n }, [active]);\n return /* @__PURE__ */ jsx(OptionalPortal, { ...portalProps, withinPortal, children: /* @__PURE__ */ jsx(\n Box,\n {\n ...getStyles(\"fullScreen\", {\n style: { opacity: visible ? 1 : 0, pointerEvents: visible ? \"all\" : \"none\", zIndex }\n }),\n ref,\n children: /* @__PURE__ */ jsx(\n Dropzone,\n {\n ...others,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n className: classes.dropzone,\n onDrop: (files) => {\n onDrop?.(files);\n close();\n setCounter(0);\n },\n onReject: (files) => {\n onReject?.(files);\n close();\n setCounter(0);\n }\n }\n )\n }\n ) });\n});\nDropzoneFullScreen.classes = classes;\nDropzoneFullScreen.displayName = \"@mantine/dropzone/DropzoneFullScreen\";\n\nexport { DropzoneFullScreen };\n//# sourceMappingURL=DropzoneFullScreen.mjs.map\n","'use client';\nconst MIME_TYPES = {\n // Images\n png: \"image/png\",\n gif: \"image/gif\",\n jpeg: \"image/jpeg\",\n svg: \"image/svg+xml\",\n webp: \"image/webp\",\n avif: \"image/avif\",\n heic: \"image/heic\",\n heif: \"image/heif\",\n // Documents\n mp4: \"video/mp4\",\n zip: \"application/zip\",\n rar: \"application/x-rar\",\n \"7z\": \"application/x-7z-compressed\",\n csv: \"text/csv\",\n pdf: \"application/pdf\",\n doc: \"application/msword\",\n docx: \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n xls: \"application/vnd.ms-excel\",\n xlsx: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n ppt: \"application/vnd.ms-powerpoint\",\n pptx: \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n exe: \"application/vnd.microsoft.portable-executable\"\n};\nconst IMAGE_MIME_TYPE = [\n MIME_TYPES.png,\n MIME_TYPES.gif,\n MIME_TYPES.jpeg,\n MIME_TYPES.svg,\n MIME_TYPES.webp,\n MIME_TYPES.avif,\n MIME_TYPES.heic,\n MIME_TYPES.heif\n];\nconst PDF_MIME_TYPE = [MIME_TYPES.pdf];\nconst MS_WORD_MIME_TYPE = [MIME_TYPES.doc, MIME_TYPES.docx];\nconst MS_EXCEL_MIME_TYPE = [MIME_TYPES.xls, MIME_TYPES.xlsx];\nconst MS_POWERPOINT_MIME_TYPE = [MIME_TYPES.ppt, MIME_TYPES.pptx];\nconst EXE_MIME_TYPE = [MIME_TYPES.exe];\n\nexport { EXE_MIME_TYPE, IMAGE_MIME_TYPE, MIME_TYPES, MS_EXCEL_MIME_TYPE, MS_POWERPOINT_MIME_TYPE, MS_WORD_MIME_TYPE, PDF_MIME_TYPE };\n//# sourceMappingURL=mime-types.mjs.map\n","import { Dropzone as Dropzone$1 } from './Dropzone.mjs';\nimport { DropzoneFullScreen } from './DropzoneFullScreen.mjs';\nexport { DropzoneAccept, DropzoneIdle, DropzoneReject } from './DropzoneStatus.mjs';\nexport { EXE_MIME_TYPE, IMAGE_MIME_TYPE, MIME_TYPES, MS_EXCEL_MIME_TYPE, MS_POWERPOINT_MIME_TYPE, MS_WORD_MIME_TYPE, PDF_MIME_TYPE } from './mime-types.mjs';\n\nDropzone$1.FullScreen = DropzoneFullScreen;\nconst Dropzone = Dropzone$1;\n\nexport { Dropzone, DropzoneFullScreen };\n//# sourceMappingURL=index.mjs.map\n","/*!\n * Cropper.js v1.6.2\n * https://fengyuanchen.github.io/cropperjs\n *\n * Copyright 2015-present Chen Fengyuan\n * Released under the MIT license\n *\n * Date: 2024-04-21T07:43:05.335Z\n */\n\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nfunction _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n _defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}\nfunction _toPrimitive(t, r) {\n if (\"object\" != typeof t || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != typeof i) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n var i = _toPrimitive(t, \"string\");\n return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);\n }\n}\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\nfunction _defineProperty(obj, key, value) {\n key = _toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined';\nvar WINDOW = IS_BROWSER ? window : {};\nvar IS_TOUCH_DEVICE = IS_BROWSER && WINDOW.document.documentElement ? 'ontouchstart' in WINDOW.document.documentElement : false;\nvar HAS_POINTER_EVENT = IS_BROWSER ? 'PointerEvent' in WINDOW : false;\nvar NAMESPACE = 'cropper';\n\n// Actions\nvar ACTION_ALL = 'all';\nvar ACTION_CROP = 'crop';\nvar ACTION_MOVE = 'move';\nvar ACTION_ZOOM = 'zoom';\nvar ACTION_EAST = 'e';\nvar ACTION_WEST = 'w';\nvar ACTION_SOUTH = 's';\nvar ACTION_NORTH = 'n';\nvar ACTION_NORTH_EAST = 'ne';\nvar ACTION_NORTH_WEST = 'nw';\nvar ACTION_SOUTH_EAST = 'se';\nvar ACTION_SOUTH_WEST = 'sw';\n\n// Classes\nvar CLASS_CROP = \"\".concat(NAMESPACE, \"-crop\");\nvar CLASS_DISABLED = \"\".concat(NAMESPACE, \"-disabled\");\nvar CLASS_HIDDEN = \"\".concat(NAMESPACE, \"-hidden\");\nvar CLASS_HIDE = \"\".concat(NAMESPACE, \"-hide\");\nvar CLASS_INVISIBLE = \"\".concat(NAMESPACE, \"-invisible\");\nvar CLASS_MODAL = \"\".concat(NAMESPACE, \"-modal\");\nvar CLASS_MOVE = \"\".concat(NAMESPACE, \"-move\");\n\n// Data keys\nvar DATA_ACTION = \"\".concat(NAMESPACE, \"Action\");\nvar DATA_PREVIEW = \"\".concat(NAMESPACE, \"Preview\");\n\n// Drag modes\nvar DRAG_MODE_CROP = 'crop';\nvar DRAG_MODE_MOVE = 'move';\nvar DRAG_MODE_NONE = 'none';\n\n// Events\nvar EVENT_CROP = 'crop';\nvar EVENT_CROP_END = 'cropend';\nvar EVENT_CROP_MOVE = 'cropmove';\nvar EVENT_CROP_START = 'cropstart';\nvar EVENT_DBLCLICK = 'dblclick';\nvar EVENT_TOUCH_START = IS_TOUCH_DEVICE ? 'touchstart' : 'mousedown';\nvar EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? 'touchmove' : 'mousemove';\nvar EVENT_TOUCH_END = IS_TOUCH_DEVICE ? 'touchend touchcancel' : 'mouseup';\nvar EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? 'pointerdown' : EVENT_TOUCH_START;\nvar EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? 'pointermove' : EVENT_TOUCH_MOVE;\nvar EVENT_POINTER_UP = HAS_POINTER_EVENT ? 'pointerup pointercancel' : EVENT_TOUCH_END;\nvar EVENT_READY = 'ready';\nvar EVENT_RESIZE = 'resize';\nvar EVENT_WHEEL = 'wheel';\nvar EVENT_ZOOM = 'zoom';\n\n// Mime types\nvar MIME_TYPE_JPEG = 'image/jpeg';\n\n// RegExps\nvar REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/;\nvar REGEXP_DATA_URL = /^data:/;\nvar REGEXP_DATA_URL_JPEG = /^data:image\\/jpeg;base64,/;\nvar REGEXP_TAG_NAME = /^img|canvas$/i;\n\n// Misc\n// Inspired by the default width and height of a canvas element.\nvar MIN_CONTAINER_WIDTH = 200;\nvar MIN_CONTAINER_HEIGHT = 100;\n\nvar DEFAULTS = {\n // Define the view mode of the cropper\n viewMode: 0,\n // 0, 1, 2, 3\n\n // Define the dragging mode of the cropper\n dragMode: DRAG_MODE_CROP,\n // 'crop', 'move' or 'none'\n\n // Define the initial aspect ratio of the crop box\n initialAspectRatio: NaN,\n // Define the aspect ratio of the crop box\n aspectRatio: NaN,\n // An object with the previous cropping result data\n data: null,\n // A selector for adding extra containers to preview\n preview: '',\n // Re-render the cropper when resize the window\n responsive: true,\n // Restore the cropped area after resize the window\n restore: true,\n // Check if the current image is a cross-origin image\n checkCrossOrigin: true,\n // Check the current image's Exif Orientation information\n checkOrientation: true,\n // Show the black modal\n modal: true,\n // Show the dashed lines for guiding\n guides: true,\n // Show the center indicator for guiding\n center: true,\n // Show the white modal to highlight the crop box\n highlight: true,\n // Show the grid background\n background: true,\n // Enable to crop the image automatically when initialize\n autoCrop: true,\n // Define the percentage of automatic cropping area when initializes\n autoCropArea: 0.8,\n // Enable to move the image\n movable: true,\n // Enable to rotate the image\n rotatable: true,\n // Enable to scale the image\n scalable: true,\n // Enable to zoom the image\n zoomable: true,\n // Enable to zoom the image by dragging touch\n zoomOnTouch: true,\n // Enable to zoom the image by wheeling mouse\n zoomOnWheel: true,\n // Define zoom ratio when zoom the image by wheeling mouse\n wheelZoomRatio: 0.1,\n // Enable to move the crop box\n cropBoxMovable: true,\n // Enable to resize the crop box\n cropBoxResizable: true,\n // Toggle drag mode between \"crop\" and \"move\" when click twice on the cropper\n toggleDragModeOnDblclick: true,\n // Size limitation\n minCanvasWidth: 0,\n minCanvasHeight: 0,\n minCropBoxWidth: 0,\n minCropBoxHeight: 0,\n minContainerWidth: MIN_CONTAINER_WIDTH,\n minContainerHeight: MIN_CONTAINER_HEIGHT,\n // Shortcuts of events\n ready: null,\n cropstart: null,\n cropmove: null,\n cropend: null,\n crop: null,\n zoom: null\n};\n\nvar TEMPLATE = '
      ' + '
      ' + '
      ' + '
      ' + '
      ' + '
      ' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '
      ' + '
      ';\n\n/**\n * Check if the given value is not a number.\n */\nvar isNaN = Number.isNaN || WINDOW.isNaN;\n\n/**\n * Check if the given value is a number.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a number, else `false`.\n */\nfunction isNumber(value) {\n return typeof value === 'number' && !isNaN(value);\n}\n\n/**\n * Check if the given value is a positive number.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a positive number, else `false`.\n */\nvar isPositiveNumber = function isPositiveNumber(value) {\n return value > 0 && value < Infinity;\n};\n\n/**\n * Check if the given value is undefined.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is undefined, else `false`.\n */\nfunction isUndefined(value) {\n return typeof value === 'undefined';\n}\n\n/**\n * Check if the given value is an object.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is an object, else `false`.\n */\nfunction isObject(value) {\n return _typeof(value) === 'object' && value !== null;\n}\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * Check if the given value is a plain object.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a plain object, else `false`.\n */\nfunction isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n try {\n var _constructor = value.constructor;\n var prototype = _constructor.prototype;\n return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf');\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Check if the given value is a function.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a function, else `false`.\n */\nfunction isFunction(value) {\n return typeof value === 'function';\n}\nvar slice = Array.prototype.slice;\n\n/**\n * Convert array-like or iterable object to an array.\n * @param {*} value - The value to convert.\n * @returns {Array} Returns a new array.\n */\nfunction toArray(value) {\n return Array.from ? Array.from(value) : slice.call(value);\n}\n\n/**\n * Iterate the given data.\n * @param {*} data - The data to iterate.\n * @param {Function} callback - The process function for each element.\n * @returns {*} The original data.\n */\nfunction forEach(data, callback) {\n if (data && isFunction(callback)) {\n if (Array.isArray(data) || isNumber(data.length) /* array-like */) {\n toArray(data).forEach(function (value, key) {\n callback.call(data, value, key, data);\n });\n } else if (isObject(data)) {\n Object.keys(data).forEach(function (key) {\n callback.call(data, data[key], key, data);\n });\n }\n }\n return data;\n}\n\n/**\n * Extend the given object.\n * @param {*} target - The target object to extend.\n * @param {*} args - The rest objects for merging to the target object.\n * @returns {Object} The extended object.\n */\nvar assign = Object.assign || function assign(target) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n if (isObject(target) && args.length > 0) {\n args.forEach(function (arg) {\n if (isObject(arg)) {\n Object.keys(arg).forEach(function (key) {\n target[key] = arg[key];\n });\n }\n });\n }\n return target;\n};\nvar REGEXP_DECIMALS = /\\.\\d*(?:0|9){12}\\d*$/;\n\n/**\n * Normalize decimal number.\n * Check out {@link https://0.30000000000000004.com/}\n * @param {number} value - The value to normalize.\n * @param {number} [times=100000000000] - The times for normalizing.\n * @returns {number} Returns the normalized number.\n */\nfunction normalizeDecimalNumber(value) {\n var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;\n return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;\n}\nvar REGEXP_SUFFIX = /^width|height|left|top|marginLeft|marginTop$/;\n\n/**\n * Apply styles to the given element.\n * @param {Element} element - The target element.\n * @param {Object} styles - The styles for applying.\n */\nfunction setStyle(element, styles) {\n var style = element.style;\n forEach(styles, function (value, property) {\n if (REGEXP_SUFFIX.test(property) && isNumber(value)) {\n value = \"\".concat(value, \"px\");\n }\n style[property] = value;\n });\n}\n\n/**\n * Check if the given element has a special class.\n * @param {Element} element - The element to check.\n * @param {string} value - The class to search.\n * @returns {boolean} Returns `true` if the special class was found.\n */\nfunction hasClass(element, value) {\n return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1;\n}\n\n/**\n * Add classes to the given element.\n * @param {Element} element - The target element.\n * @param {string} value - The classes to be added.\n */\nfunction addClass(element, value) {\n if (!value) {\n return;\n }\n if (isNumber(element.length)) {\n forEach(element, function (elem) {\n addClass(elem, value);\n });\n return;\n }\n if (element.classList) {\n element.classList.add(value);\n return;\n }\n var className = element.className.trim();\n if (!className) {\n element.className = value;\n } else if (className.indexOf(value) < 0) {\n element.className = \"\".concat(className, \" \").concat(value);\n }\n}\n\n/**\n * Remove classes from the given element.\n * @param {Element} element - The target element.\n * @param {string} value - The classes to be removed.\n */\nfunction removeClass(element, value) {\n if (!value) {\n return;\n }\n if (isNumber(element.length)) {\n forEach(element, function (elem) {\n removeClass(elem, value);\n });\n return;\n }\n if (element.classList) {\n element.classList.remove(value);\n return;\n }\n if (element.className.indexOf(value) >= 0) {\n element.className = element.className.replace(value, '');\n }\n}\n\n/**\n * Add or remove classes from the given element.\n * @param {Element} element - The target element.\n * @param {string} value - The classes to be toggled.\n * @param {boolean} added - Add only.\n */\nfunction toggleClass(element, value, added) {\n if (!value) {\n return;\n }\n if (isNumber(element.length)) {\n forEach(element, function (elem) {\n toggleClass(elem, value, added);\n });\n return;\n }\n\n // IE10-11 doesn't support the second parameter of `classList.toggle`\n if (added) {\n addClass(element, value);\n } else {\n removeClass(element, value);\n }\n}\nvar REGEXP_CAMEL_CASE = /([a-z\\d])([A-Z])/g;\n\n/**\n * Transform the given string from camelCase to kebab-case\n * @param {string} value - The value to transform.\n * @returns {string} The transformed value.\n */\nfunction toParamCase(value) {\n return value.replace(REGEXP_CAMEL_CASE, '$1-$2').toLowerCase();\n}\n\n/**\n * Get data from the given element.\n * @param {Element} element - The target element.\n * @param {string} name - The data key to get.\n * @returns {string} The data value.\n */\nfunction getData(element, name) {\n if (isObject(element[name])) {\n return element[name];\n }\n if (element.dataset) {\n return element.dataset[name];\n }\n return element.getAttribute(\"data-\".concat(toParamCase(name)));\n}\n\n/**\n * Set data to the given element.\n * @param {Element} element - The target element.\n * @param {string} name - The data key to set.\n * @param {string} data - The data value.\n */\nfunction setData(element, name, data) {\n if (isObject(data)) {\n element[name] = data;\n } else if (element.dataset) {\n element.dataset[name] = data;\n } else {\n element.setAttribute(\"data-\".concat(toParamCase(name)), data);\n }\n}\n\n/**\n * Remove data from the given element.\n * @param {Element} element - The target element.\n * @param {string} name - The data key to remove.\n */\nfunction removeData(element, name) {\n if (isObject(element[name])) {\n try {\n delete element[name];\n } catch (error) {\n element[name] = undefined;\n }\n } else if (element.dataset) {\n // #128 Safari not allows to delete dataset property\n try {\n delete element.dataset[name];\n } catch (error) {\n element.dataset[name] = undefined;\n }\n } else {\n element.removeAttribute(\"data-\".concat(toParamCase(name)));\n }\n}\nvar REGEXP_SPACES = /\\s\\s*/;\nvar onceSupported = function () {\n var supported = false;\n if (IS_BROWSER) {\n var once = false;\n var listener = function listener() {};\n var options = Object.defineProperty({}, 'once', {\n get: function get() {\n supported = true;\n return once;\n },\n /**\n * This setter can fix a `TypeError` in strict mode\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only}\n * @param {boolean} value - The value to set\n */\n set: function set(value) {\n once = value;\n }\n });\n WINDOW.addEventListener('test', listener, options);\n WINDOW.removeEventListener('test', listener, options);\n }\n return supported;\n}();\n\n/**\n * Remove event listener from the target element.\n * @param {Element} element - The event target.\n * @param {string} type - The event type(s).\n * @param {Function} listener - The event listener.\n * @param {Object} options - The event options.\n */\nfunction removeListener(element, type, listener) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var handler = listener;\n type.trim().split(REGEXP_SPACES).forEach(function (event) {\n if (!onceSupported) {\n var listeners = element.listeners;\n if (listeners && listeners[event] && listeners[event][listener]) {\n handler = listeners[event][listener];\n delete listeners[event][listener];\n if (Object.keys(listeners[event]).length === 0) {\n delete listeners[event];\n }\n if (Object.keys(listeners).length === 0) {\n delete element.listeners;\n }\n }\n }\n element.removeEventListener(event, handler, options);\n });\n}\n\n/**\n * Add event listener to the target element.\n * @param {Element} element - The event target.\n * @param {string} type - The event type(s).\n * @param {Function} listener - The event listener.\n * @param {Object} options - The event options.\n */\nfunction addListener(element, type, listener) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var _handler = listener;\n type.trim().split(REGEXP_SPACES).forEach(function (event) {\n if (options.once && !onceSupported) {\n var _element$listeners = element.listeners,\n listeners = _element$listeners === void 0 ? {} : _element$listeners;\n _handler = function handler() {\n delete listeners[event][listener];\n element.removeEventListener(event, _handler, options);\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n listener.apply(element, args);\n };\n if (!listeners[event]) {\n listeners[event] = {};\n }\n if (listeners[event][listener]) {\n element.removeEventListener(event, listeners[event][listener], options);\n }\n listeners[event][listener] = _handler;\n element.listeners = listeners;\n }\n element.addEventListener(event, _handler, options);\n });\n}\n\n/**\n * Dispatch event on the target element.\n * @param {Element} element - The event target.\n * @param {string} type - The event type(s).\n * @param {Object} data - The additional event data.\n * @returns {boolean} Indicate if the event is default prevented or not.\n */\nfunction dispatchEvent(element, type, data) {\n var event;\n\n // Event and CustomEvent on IE9-11 are global objects, not constructors\n if (isFunction(Event) && isFunction(CustomEvent)) {\n event = new CustomEvent(type, {\n detail: data,\n bubbles: true,\n cancelable: true\n });\n } else {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(type, true, true, data);\n }\n return element.dispatchEvent(event);\n}\n\n/**\n * Get the offset base on the document.\n * @param {Element} element - The target element.\n * @returns {Object} The offset data.\n */\nfunction getOffset(element) {\n var box = element.getBoundingClientRect();\n return {\n left: box.left + (window.pageXOffset - document.documentElement.clientLeft),\n top: box.top + (window.pageYOffset - document.documentElement.clientTop)\n };\n}\nvar location = WINDOW.location;\nvar REGEXP_ORIGINS = /^(\\w+:)\\/\\/([^:/?#]*):?(\\d*)/i;\n\n/**\n * Check if the given URL is a cross origin URL.\n * @param {string} url - The target URL.\n * @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`.\n */\nfunction isCrossOriginURL(url) {\n var parts = url.match(REGEXP_ORIGINS);\n return parts !== null && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port);\n}\n\n/**\n * Add timestamp to the given URL.\n * @param {string} url - The target URL.\n * @returns {string} The result URL.\n */\nfunction addTimestamp(url) {\n var timestamp = \"timestamp=\".concat(new Date().getTime());\n return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp;\n}\n\n/**\n * Get transforms base on the given object.\n * @param {Object} obj - The target object.\n * @returns {string} A string contains transform values.\n */\nfunction getTransforms(_ref) {\n var rotate = _ref.rotate,\n scaleX = _ref.scaleX,\n scaleY = _ref.scaleY,\n translateX = _ref.translateX,\n translateY = _ref.translateY;\n var values = [];\n if (isNumber(translateX) && translateX !== 0) {\n values.push(\"translateX(\".concat(translateX, \"px)\"));\n }\n if (isNumber(translateY) && translateY !== 0) {\n values.push(\"translateY(\".concat(translateY, \"px)\"));\n }\n\n // Rotate should come first before scale to match orientation transform\n if (isNumber(rotate) && rotate !== 0) {\n values.push(\"rotate(\".concat(rotate, \"deg)\"));\n }\n if (isNumber(scaleX) && scaleX !== 1) {\n values.push(\"scaleX(\".concat(scaleX, \")\"));\n }\n if (isNumber(scaleY) && scaleY !== 1) {\n values.push(\"scaleY(\".concat(scaleY, \")\"));\n }\n var transform = values.length ? values.join(' ') : 'none';\n return {\n WebkitTransform: transform,\n msTransform: transform,\n transform: transform\n };\n}\n\n/**\n * Get the max ratio of a group of pointers.\n * @param {string} pointers - The target pointers.\n * @returns {number} The result ratio.\n */\nfunction getMaxZoomRatio(pointers) {\n var pointers2 = _objectSpread2({}, pointers);\n var maxRatio = 0;\n forEach(pointers, function (pointer, pointerId) {\n delete pointers2[pointerId];\n forEach(pointers2, function (pointer2) {\n var x1 = Math.abs(pointer.startX - pointer2.startX);\n var y1 = Math.abs(pointer.startY - pointer2.startY);\n var x2 = Math.abs(pointer.endX - pointer2.endX);\n var y2 = Math.abs(pointer.endY - pointer2.endY);\n var z1 = Math.sqrt(x1 * x1 + y1 * y1);\n var z2 = Math.sqrt(x2 * x2 + y2 * y2);\n var ratio = (z2 - z1) / z1;\n if (Math.abs(ratio) > Math.abs(maxRatio)) {\n maxRatio = ratio;\n }\n });\n });\n return maxRatio;\n}\n\n/**\n * Get a pointer from an event object.\n * @param {Object} event - The target event object.\n * @param {boolean} endOnly - Indicates if only returns the end point coordinate or not.\n * @returns {Object} The result pointer contains start and/or end point coordinates.\n */\nfunction getPointer(_ref2, endOnly) {\n var pageX = _ref2.pageX,\n pageY = _ref2.pageY;\n var end = {\n endX: pageX,\n endY: pageY\n };\n return endOnly ? end : _objectSpread2({\n startX: pageX,\n startY: pageY\n }, end);\n}\n\n/**\n * Get the center point coordinate of a group of pointers.\n * @param {Object} pointers - The target pointers.\n * @returns {Object} The center point coordinate.\n */\nfunction getPointersCenter(pointers) {\n var pageX = 0;\n var pageY = 0;\n var count = 0;\n forEach(pointers, function (_ref3) {\n var startX = _ref3.startX,\n startY = _ref3.startY;\n pageX += startX;\n pageY += startY;\n count += 1;\n });\n pageX /= count;\n pageY /= count;\n return {\n pageX: pageX,\n pageY: pageY\n };\n}\n\n/**\n * Get the max sizes in a rectangle under the given aspect ratio.\n * @param {Object} data - The original sizes.\n * @param {string} [type='contain'] - The adjust type.\n * @returns {Object} The result sizes.\n */\nfunction getAdjustedSizes(_ref4) {\n var aspectRatio = _ref4.aspectRatio,\n height = _ref4.height,\n width = _ref4.width;\n var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain';\n var isValidWidth = isPositiveNumber(width);\n var isValidHeight = isPositiveNumber(height);\n if (isValidWidth && isValidHeight) {\n var adjustedWidth = height * aspectRatio;\n if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {\n height = width / aspectRatio;\n } else {\n width = height * aspectRatio;\n }\n } else if (isValidWidth) {\n height = width / aspectRatio;\n } else if (isValidHeight) {\n width = height * aspectRatio;\n }\n return {\n width: width,\n height: height\n };\n}\n\n/**\n * Get the new sizes of a rectangle after rotated.\n * @param {Object} data - The original sizes.\n * @returns {Object} The result sizes.\n */\nfunction getRotatedSizes(_ref5) {\n var width = _ref5.width,\n height = _ref5.height,\n degree = _ref5.degree;\n degree = Math.abs(degree) % 180;\n if (degree === 90) {\n return {\n width: height,\n height: width\n };\n }\n var arc = degree % 90 * Math.PI / 180;\n var sinArc = Math.sin(arc);\n var cosArc = Math.cos(arc);\n var newWidth = width * cosArc + height * sinArc;\n var newHeight = width * sinArc + height * cosArc;\n return degree > 90 ? {\n width: newHeight,\n height: newWidth\n } : {\n width: newWidth,\n height: newHeight\n };\n}\n\n/**\n * Get a canvas which drew the given image.\n * @param {HTMLImageElement} image - The image for drawing.\n * @param {Object} imageData - The image data.\n * @param {Object} canvasData - The canvas data.\n * @param {Object} options - The options.\n * @returns {HTMLCanvasElement} The result canvas.\n */\nfunction getSourceCanvas(image, _ref6, _ref7, _ref8) {\n var imageAspectRatio = _ref6.aspectRatio,\n imageNaturalWidth = _ref6.naturalWidth,\n imageNaturalHeight = _ref6.naturalHeight,\n _ref6$rotate = _ref6.rotate,\n rotate = _ref6$rotate === void 0 ? 0 : _ref6$rotate,\n _ref6$scaleX = _ref6.scaleX,\n scaleX = _ref6$scaleX === void 0 ? 1 : _ref6$scaleX,\n _ref6$scaleY = _ref6.scaleY,\n scaleY = _ref6$scaleY === void 0 ? 1 : _ref6$scaleY;\n var aspectRatio = _ref7.aspectRatio,\n naturalWidth = _ref7.naturalWidth,\n naturalHeight = _ref7.naturalHeight;\n var _ref8$fillColor = _ref8.fillColor,\n fillColor = _ref8$fillColor === void 0 ? 'transparent' : _ref8$fillColor,\n _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled,\n imageSmoothingEnabled = _ref8$imageSmoothingE === void 0 ? true : _ref8$imageSmoothingE,\n _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality,\n imageSmoothingQuality = _ref8$imageSmoothingQ === void 0 ? 'low' : _ref8$imageSmoothingQ,\n _ref8$maxWidth = _ref8.maxWidth,\n maxWidth = _ref8$maxWidth === void 0 ? Infinity : _ref8$maxWidth,\n _ref8$maxHeight = _ref8.maxHeight,\n maxHeight = _ref8$maxHeight === void 0 ? Infinity : _ref8$maxHeight,\n _ref8$minWidth = _ref8.minWidth,\n minWidth = _ref8$minWidth === void 0 ? 0 : _ref8$minWidth,\n _ref8$minHeight = _ref8.minHeight,\n minHeight = _ref8$minHeight === void 0 ? 0 : _ref8$minHeight;\n var canvas = document.createElement('canvas');\n var context = canvas.getContext('2d');\n var maxSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: maxWidth,\n height: maxHeight\n });\n var minSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: minWidth,\n height: minHeight\n }, 'cover');\n var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth));\n var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight));\n\n // Note: should always use image's natural sizes for drawing as\n // imageData.naturalWidth === canvasData.naturalHeight when rotate % 180 === 90\n var destMaxSizes = getAdjustedSizes({\n aspectRatio: imageAspectRatio,\n width: maxWidth,\n height: maxHeight\n });\n var destMinSizes = getAdjustedSizes({\n aspectRatio: imageAspectRatio,\n width: minWidth,\n height: minHeight\n }, 'cover');\n var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth));\n var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight));\n var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight];\n canvas.width = normalizeDecimalNumber(width);\n canvas.height = normalizeDecimalNumber(height);\n context.fillStyle = fillColor;\n context.fillRect(0, 0, width, height);\n context.save();\n context.translate(width / 2, height / 2);\n context.rotate(rotate * Math.PI / 180);\n context.scale(scaleX, scaleY);\n context.imageSmoothingEnabled = imageSmoothingEnabled;\n context.imageSmoothingQuality = imageSmoothingQuality;\n context.drawImage.apply(context, [image].concat(_toConsumableArray(params.map(function (param) {\n return Math.floor(normalizeDecimalNumber(param));\n }))));\n context.restore();\n return canvas;\n}\nvar fromCharCode = String.fromCharCode;\n\n/**\n * Get string from char code in data view.\n * @param {DataView} dataView - The data view for read.\n * @param {number} start - The start index.\n * @param {number} length - The read length.\n * @returns {string} The read result.\n */\nfunction getStringFromCharCode(dataView, start, length) {\n var str = '';\n length += start;\n for (var i = start; i < length; i += 1) {\n str += fromCharCode(dataView.getUint8(i));\n }\n return str;\n}\nvar REGEXP_DATA_URL_HEAD = /^data:.*,/;\n\n/**\n * Transform Data URL to array buffer.\n * @param {string} dataURL - The Data URL to transform.\n * @returns {ArrayBuffer} The result array buffer.\n */\nfunction dataURLToArrayBuffer(dataURL) {\n var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, '');\n var binary = atob(base64);\n var arrayBuffer = new ArrayBuffer(binary.length);\n var uint8 = new Uint8Array(arrayBuffer);\n forEach(uint8, function (value, i) {\n uint8[i] = binary.charCodeAt(i);\n });\n return arrayBuffer;\n}\n\n/**\n * Transform array buffer to Data URL.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.\n * @param {string} mimeType - The mime type of the Data URL.\n * @returns {string} The result Data URL.\n */\nfunction arrayBufferToDataURL(arrayBuffer, mimeType) {\n var chunks = [];\n\n // Chunk Typed Array for better performance (#435)\n var chunkSize = 8192;\n var uint8 = new Uint8Array(arrayBuffer);\n while (uint8.length > 0) {\n // XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9\n // eslint-disable-next-line prefer-spread\n chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize))));\n uint8 = uint8.subarray(chunkSize);\n }\n return \"data:\".concat(mimeType, \";base64,\").concat(btoa(chunks.join('')));\n}\n\n/**\n * Get orientation value from given array buffer.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to read.\n * @returns {number} The read orientation value.\n */\nfunction resetAndGetOrientation(arrayBuffer) {\n var dataView = new DataView(arrayBuffer);\n var orientation;\n\n // Ignores range error when the image does not have correct Exif information\n try {\n var littleEndian;\n var app1Start;\n var ifdStart;\n\n // Only handle JPEG image (start by 0xFFD8)\n if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {\n var length = dataView.byteLength;\n var offset = 2;\n while (offset + 1 < length) {\n if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {\n app1Start = offset;\n break;\n }\n offset += 1;\n }\n }\n if (app1Start) {\n var exifIDCode = app1Start + 4;\n var tiffOffset = app1Start + 10;\n if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {\n var endianness = dataView.getUint16(tiffOffset);\n littleEndian = endianness === 0x4949;\n if (littleEndian || endianness === 0x4D4D /* bigEndian */) {\n if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {\n var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);\n if (firstIFDOffset >= 0x00000008) {\n ifdStart = tiffOffset + firstIFDOffset;\n }\n }\n }\n }\n }\n if (ifdStart) {\n var _length = dataView.getUint16(ifdStart, littleEndian);\n var _offset;\n var i;\n for (i = 0; i < _length; i += 1) {\n _offset = ifdStart + i * 12 + 2;\n if (dataView.getUint16(_offset, littleEndian) === 0x0112 /* Orientation */) {\n // 8 is the offset of the current tag's value\n _offset += 8;\n\n // Get the original orientation value\n orientation = dataView.getUint16(_offset, littleEndian);\n\n // Override the orientation with its default value\n dataView.setUint16(_offset, 1, littleEndian);\n break;\n }\n }\n }\n } catch (error) {\n orientation = 1;\n }\n return orientation;\n}\n\n/**\n * Parse Exif Orientation value.\n * @param {number} orientation - The orientation to parse.\n * @returns {Object} The parsed result.\n */\nfunction parseOrientation(orientation) {\n var rotate = 0;\n var scaleX = 1;\n var scaleY = 1;\n switch (orientation) {\n // Flip horizontal\n case 2:\n scaleX = -1;\n break;\n\n // Rotate left 180°\n case 3:\n rotate = -180;\n break;\n\n // Flip vertical\n case 4:\n scaleY = -1;\n break;\n\n // Flip vertical and rotate right 90°\n case 5:\n rotate = 90;\n scaleY = -1;\n break;\n\n // Rotate right 90°\n case 6:\n rotate = 90;\n break;\n\n // Flip horizontal and rotate right 90°\n case 7:\n rotate = 90;\n scaleX = -1;\n break;\n\n // Rotate left 90°\n case 8:\n rotate = -90;\n break;\n }\n return {\n rotate: rotate,\n scaleX: scaleX,\n scaleY: scaleY\n };\n}\n\nvar render = {\n render: function render() {\n this.initContainer();\n this.initCanvas();\n this.initCropBox();\n this.renderCanvas();\n if (this.cropped) {\n this.renderCropBox();\n }\n },\n initContainer: function initContainer() {\n var element = this.element,\n options = this.options,\n container = this.container,\n cropper = this.cropper;\n var minWidth = Number(options.minContainerWidth);\n var minHeight = Number(options.minContainerHeight);\n addClass(cropper, CLASS_HIDDEN);\n removeClass(element, CLASS_HIDDEN);\n var containerData = {\n width: Math.max(container.offsetWidth, minWidth >= 0 ? minWidth : MIN_CONTAINER_WIDTH),\n height: Math.max(container.offsetHeight, minHeight >= 0 ? minHeight : MIN_CONTAINER_HEIGHT)\n };\n this.containerData = containerData;\n setStyle(cropper, {\n width: containerData.width,\n height: containerData.height\n });\n addClass(element, CLASS_HIDDEN);\n removeClass(cropper, CLASS_HIDDEN);\n },\n // Canvas (image wrapper)\n initCanvas: function initCanvas() {\n var containerData = this.containerData,\n imageData = this.imageData;\n var viewMode = this.options.viewMode;\n var rotated = Math.abs(imageData.rotate) % 180 === 90;\n var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth;\n var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight;\n var aspectRatio = naturalWidth / naturalHeight;\n var canvasWidth = containerData.width;\n var canvasHeight = containerData.height;\n if (containerData.height * aspectRatio > containerData.width) {\n if (viewMode === 3) {\n canvasWidth = containerData.height * aspectRatio;\n } else {\n canvasHeight = containerData.width / aspectRatio;\n }\n } else if (viewMode === 3) {\n canvasHeight = containerData.width / aspectRatio;\n } else {\n canvasWidth = containerData.height * aspectRatio;\n }\n var canvasData = {\n aspectRatio: aspectRatio,\n naturalWidth: naturalWidth,\n naturalHeight: naturalHeight,\n width: canvasWidth,\n height: canvasHeight\n };\n this.canvasData = canvasData;\n this.limited = viewMode === 1 || viewMode === 2;\n this.limitCanvas(true, true);\n canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth);\n canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight);\n canvasData.left = (containerData.width - canvasData.width) / 2;\n canvasData.top = (containerData.height - canvasData.height) / 2;\n canvasData.oldLeft = canvasData.left;\n canvasData.oldTop = canvasData.top;\n this.initialCanvasData = assign({}, canvasData);\n },\n limitCanvas: function limitCanvas(sizeLimited, positionLimited) {\n var options = this.options,\n containerData = this.containerData,\n canvasData = this.canvasData,\n cropBoxData = this.cropBoxData;\n var viewMode = options.viewMode;\n var aspectRatio = canvasData.aspectRatio;\n var cropped = this.cropped && cropBoxData;\n if (sizeLimited) {\n var minCanvasWidth = Number(options.minCanvasWidth) || 0;\n var minCanvasHeight = Number(options.minCanvasHeight) || 0;\n if (viewMode > 1) {\n minCanvasWidth = Math.max(minCanvasWidth, containerData.width);\n minCanvasHeight = Math.max(minCanvasHeight, containerData.height);\n if (viewMode === 3) {\n if (minCanvasHeight * aspectRatio > minCanvasWidth) {\n minCanvasWidth = minCanvasHeight * aspectRatio;\n } else {\n minCanvasHeight = minCanvasWidth / aspectRatio;\n }\n }\n } else if (viewMode > 0) {\n if (minCanvasWidth) {\n minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0);\n } else if (minCanvasHeight) {\n minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0);\n } else if (cropped) {\n minCanvasWidth = cropBoxData.width;\n minCanvasHeight = cropBoxData.height;\n if (minCanvasHeight * aspectRatio > minCanvasWidth) {\n minCanvasWidth = minCanvasHeight * aspectRatio;\n } else {\n minCanvasHeight = minCanvasWidth / aspectRatio;\n }\n }\n }\n var _getAdjustedSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: minCanvasWidth,\n height: minCanvasHeight\n });\n minCanvasWidth = _getAdjustedSizes.width;\n minCanvasHeight = _getAdjustedSizes.height;\n canvasData.minWidth = minCanvasWidth;\n canvasData.minHeight = minCanvasHeight;\n canvasData.maxWidth = Infinity;\n canvasData.maxHeight = Infinity;\n }\n if (positionLimited) {\n if (viewMode > (cropped ? 0 : 1)) {\n var newCanvasLeft = containerData.width - canvasData.width;\n var newCanvasTop = containerData.height - canvasData.height;\n canvasData.minLeft = Math.min(0, newCanvasLeft);\n canvasData.minTop = Math.min(0, newCanvasTop);\n canvasData.maxLeft = Math.max(0, newCanvasLeft);\n canvasData.maxTop = Math.max(0, newCanvasTop);\n if (cropped && this.limited) {\n canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width));\n canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height));\n canvasData.maxLeft = cropBoxData.left;\n canvasData.maxTop = cropBoxData.top;\n if (viewMode === 2) {\n if (canvasData.width >= containerData.width) {\n canvasData.minLeft = Math.min(0, newCanvasLeft);\n canvasData.maxLeft = Math.max(0, newCanvasLeft);\n }\n if (canvasData.height >= containerData.height) {\n canvasData.minTop = Math.min(0, newCanvasTop);\n canvasData.maxTop = Math.max(0, newCanvasTop);\n }\n }\n }\n } else {\n canvasData.minLeft = -canvasData.width;\n canvasData.minTop = -canvasData.height;\n canvasData.maxLeft = containerData.width;\n canvasData.maxTop = containerData.height;\n }\n }\n },\n renderCanvas: function renderCanvas(changed, transformed) {\n var canvasData = this.canvasData,\n imageData = this.imageData;\n if (transformed) {\n var _getRotatedSizes = getRotatedSizes({\n width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1),\n height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1),\n degree: imageData.rotate || 0\n }),\n naturalWidth = _getRotatedSizes.width,\n naturalHeight = _getRotatedSizes.height;\n var width = canvasData.width * (naturalWidth / canvasData.naturalWidth);\n var height = canvasData.height * (naturalHeight / canvasData.naturalHeight);\n canvasData.left -= (width - canvasData.width) / 2;\n canvasData.top -= (height - canvasData.height) / 2;\n canvasData.width = width;\n canvasData.height = height;\n canvasData.aspectRatio = naturalWidth / naturalHeight;\n canvasData.naturalWidth = naturalWidth;\n canvasData.naturalHeight = naturalHeight;\n this.limitCanvas(true, false);\n }\n if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) {\n canvasData.left = canvasData.oldLeft;\n }\n if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) {\n canvasData.top = canvasData.oldTop;\n }\n canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth);\n canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight);\n this.limitCanvas(false, true);\n canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft);\n canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop);\n canvasData.oldLeft = canvasData.left;\n canvasData.oldTop = canvasData.top;\n setStyle(this.canvas, assign({\n width: canvasData.width,\n height: canvasData.height\n }, getTransforms({\n translateX: canvasData.left,\n translateY: canvasData.top\n })));\n this.renderImage(changed);\n if (this.cropped && this.limited) {\n this.limitCropBox(true, true);\n }\n },\n renderImage: function renderImage(changed) {\n var canvasData = this.canvasData,\n imageData = this.imageData;\n var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth);\n var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight);\n assign(imageData, {\n width: width,\n height: height,\n left: (canvasData.width - width) / 2,\n top: (canvasData.height - height) / 2\n });\n setStyle(this.image, assign({\n width: imageData.width,\n height: imageData.height\n }, getTransforms(assign({\n translateX: imageData.left,\n translateY: imageData.top\n }, imageData))));\n if (changed) {\n this.output();\n }\n },\n initCropBox: function initCropBox() {\n var options = this.options,\n canvasData = this.canvasData;\n var aspectRatio = options.aspectRatio || options.initialAspectRatio;\n var autoCropArea = Number(options.autoCropArea) || 0.8;\n var cropBoxData = {\n width: canvasData.width,\n height: canvasData.height\n };\n if (aspectRatio) {\n if (canvasData.height * aspectRatio > canvasData.width) {\n cropBoxData.height = cropBoxData.width / aspectRatio;\n } else {\n cropBoxData.width = cropBoxData.height * aspectRatio;\n }\n }\n this.cropBoxData = cropBoxData;\n this.limitCropBox(true, true);\n\n // Initialize auto crop area\n cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);\n cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);\n\n // The width/height of auto crop area must large than \"minWidth/Height\"\n cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea);\n cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea);\n cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2;\n cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2;\n cropBoxData.oldLeft = cropBoxData.left;\n cropBoxData.oldTop = cropBoxData.top;\n this.initialCropBoxData = assign({}, cropBoxData);\n },\n limitCropBox: function limitCropBox(sizeLimited, positionLimited) {\n var options = this.options,\n containerData = this.containerData,\n canvasData = this.canvasData,\n cropBoxData = this.cropBoxData,\n limited = this.limited;\n var aspectRatio = options.aspectRatio;\n if (sizeLimited) {\n var minCropBoxWidth = Number(options.minCropBoxWidth) || 0;\n var minCropBoxHeight = Number(options.minCropBoxHeight) || 0;\n var maxCropBoxWidth = limited ? Math.min(containerData.width, canvasData.width, canvasData.width + canvasData.left, containerData.width - canvasData.left) : containerData.width;\n var maxCropBoxHeight = limited ? Math.min(containerData.height, canvasData.height, canvasData.height + canvasData.top, containerData.height - canvasData.top) : containerData.height;\n\n // The min/maxCropBoxWidth/Height must be less than container's width/height\n minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width);\n minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height);\n if (aspectRatio) {\n if (minCropBoxWidth && minCropBoxHeight) {\n if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {\n minCropBoxHeight = minCropBoxWidth / aspectRatio;\n } else {\n minCropBoxWidth = minCropBoxHeight * aspectRatio;\n }\n } else if (minCropBoxWidth) {\n minCropBoxHeight = minCropBoxWidth / aspectRatio;\n } else if (minCropBoxHeight) {\n minCropBoxWidth = minCropBoxHeight * aspectRatio;\n }\n if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {\n maxCropBoxHeight = maxCropBoxWidth / aspectRatio;\n } else {\n maxCropBoxWidth = maxCropBoxHeight * aspectRatio;\n }\n }\n\n // The minWidth/Height must be less than maxWidth/Height\n cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth);\n cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight);\n cropBoxData.maxWidth = maxCropBoxWidth;\n cropBoxData.maxHeight = maxCropBoxHeight;\n }\n if (positionLimited) {\n if (limited) {\n cropBoxData.minLeft = Math.max(0, canvasData.left);\n cropBoxData.minTop = Math.max(0, canvasData.top);\n cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width;\n cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height;\n } else {\n cropBoxData.minLeft = 0;\n cropBoxData.minTop = 0;\n cropBoxData.maxLeft = containerData.width - cropBoxData.width;\n cropBoxData.maxTop = containerData.height - cropBoxData.height;\n }\n }\n },\n renderCropBox: function renderCropBox() {\n var options = this.options,\n containerData = this.containerData,\n cropBoxData = this.cropBoxData;\n if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) {\n cropBoxData.left = cropBoxData.oldLeft;\n }\n if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) {\n cropBoxData.top = cropBoxData.oldTop;\n }\n cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);\n cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);\n this.limitCropBox(false, true);\n cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft);\n cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop);\n cropBoxData.oldLeft = cropBoxData.left;\n cropBoxData.oldTop = cropBoxData.top;\n if (options.movable && options.cropBoxMovable) {\n // Turn to move the canvas when the crop box is equal to the container\n setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL);\n }\n setStyle(this.cropBox, assign({\n width: cropBoxData.width,\n height: cropBoxData.height\n }, getTransforms({\n translateX: cropBoxData.left,\n translateY: cropBoxData.top\n })));\n if (this.cropped && this.limited) {\n this.limitCanvas(true, true);\n }\n if (!this.disabled) {\n this.output();\n }\n },\n output: function output() {\n this.preview();\n dispatchEvent(this.element, EVENT_CROP, this.getData());\n }\n};\n\nvar preview = {\n initPreview: function initPreview() {\n var element = this.element,\n crossOrigin = this.crossOrigin;\n var preview = this.options.preview;\n var url = crossOrigin ? this.crossOriginUrl : this.url;\n var alt = element.alt || 'The image to preview';\n var image = document.createElement('img');\n if (crossOrigin) {\n image.crossOrigin = crossOrigin;\n }\n image.src = url;\n image.alt = alt;\n this.viewBox.appendChild(image);\n this.viewBoxImage = image;\n if (!preview) {\n return;\n }\n var previews = preview;\n if (typeof preview === 'string') {\n previews = element.ownerDocument.querySelectorAll(preview);\n } else if (preview.querySelector) {\n previews = [preview];\n }\n this.previews = previews;\n forEach(previews, function (el) {\n var img = document.createElement('img');\n\n // Save the original size for recover\n setData(el, DATA_PREVIEW, {\n width: el.offsetWidth,\n height: el.offsetHeight,\n html: el.innerHTML\n });\n if (crossOrigin) {\n img.crossOrigin = crossOrigin;\n }\n img.src = url;\n img.alt = alt;\n\n /**\n * Override img element styles\n * Add `display:block` to avoid margin top issue\n * Add `height:auto` to override `height` attribute on IE8\n * (Occur only when margin-top <= -height)\n */\n img.style.cssText = 'display:block;' + 'width:100%;' + 'height:auto;' + 'min-width:0!important;' + 'min-height:0!important;' + 'max-width:none!important;' + 'max-height:none!important;' + 'image-orientation:0deg!important;\"';\n el.innerHTML = '';\n el.appendChild(img);\n });\n },\n resetPreview: function resetPreview() {\n forEach(this.previews, function (element) {\n var data = getData(element, DATA_PREVIEW);\n setStyle(element, {\n width: data.width,\n height: data.height\n });\n element.innerHTML = data.html;\n removeData(element, DATA_PREVIEW);\n });\n },\n preview: function preview() {\n var imageData = this.imageData,\n canvasData = this.canvasData,\n cropBoxData = this.cropBoxData;\n var cropBoxWidth = cropBoxData.width,\n cropBoxHeight = cropBoxData.height;\n var width = imageData.width,\n height = imageData.height;\n var left = cropBoxData.left - canvasData.left - imageData.left;\n var top = cropBoxData.top - canvasData.top - imageData.top;\n if (!this.cropped || this.disabled) {\n return;\n }\n setStyle(this.viewBoxImage, assign({\n width: width,\n height: height\n }, getTransforms(assign({\n translateX: -left,\n translateY: -top\n }, imageData))));\n forEach(this.previews, function (element) {\n var data = getData(element, DATA_PREVIEW);\n var originalWidth = data.width;\n var originalHeight = data.height;\n var newWidth = originalWidth;\n var newHeight = originalHeight;\n var ratio = 1;\n if (cropBoxWidth) {\n ratio = originalWidth / cropBoxWidth;\n newHeight = cropBoxHeight * ratio;\n }\n if (cropBoxHeight && newHeight > originalHeight) {\n ratio = originalHeight / cropBoxHeight;\n newWidth = cropBoxWidth * ratio;\n newHeight = originalHeight;\n }\n setStyle(element, {\n width: newWidth,\n height: newHeight\n });\n setStyle(element.getElementsByTagName('img')[0], assign({\n width: width * ratio,\n height: height * ratio\n }, getTransforms(assign({\n translateX: -left * ratio,\n translateY: -top * ratio\n }, imageData))));\n });\n }\n};\n\nvar events = {\n bind: function bind() {\n var element = this.element,\n options = this.options,\n cropper = this.cropper;\n if (isFunction(options.cropstart)) {\n addListener(element, EVENT_CROP_START, options.cropstart);\n }\n if (isFunction(options.cropmove)) {\n addListener(element, EVENT_CROP_MOVE, options.cropmove);\n }\n if (isFunction(options.cropend)) {\n addListener(element, EVENT_CROP_END, options.cropend);\n }\n if (isFunction(options.crop)) {\n addListener(element, EVENT_CROP, options.crop);\n }\n if (isFunction(options.zoom)) {\n addListener(element, EVENT_ZOOM, options.zoom);\n }\n addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this));\n if (options.zoomable && options.zoomOnWheel) {\n addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), {\n passive: false,\n capture: true\n });\n }\n if (options.toggleDragModeOnDblclick) {\n addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this));\n }\n addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this));\n addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this));\n if (options.responsive) {\n addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this));\n }\n },\n unbind: function unbind() {\n var element = this.element,\n options = this.options,\n cropper = this.cropper;\n if (isFunction(options.cropstart)) {\n removeListener(element, EVENT_CROP_START, options.cropstart);\n }\n if (isFunction(options.cropmove)) {\n removeListener(element, EVENT_CROP_MOVE, options.cropmove);\n }\n if (isFunction(options.cropend)) {\n removeListener(element, EVENT_CROP_END, options.cropend);\n }\n if (isFunction(options.crop)) {\n removeListener(element, EVENT_CROP, options.crop);\n }\n if (isFunction(options.zoom)) {\n removeListener(element, EVENT_ZOOM, options.zoom);\n }\n removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart);\n if (options.zoomable && options.zoomOnWheel) {\n removeListener(cropper, EVENT_WHEEL, this.onWheel, {\n passive: false,\n capture: true\n });\n }\n if (options.toggleDragModeOnDblclick) {\n removeListener(cropper, EVENT_DBLCLICK, this.onDblclick);\n }\n removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove);\n removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd);\n if (options.responsive) {\n removeListener(window, EVENT_RESIZE, this.onResize);\n }\n }\n};\n\nvar handlers = {\n resize: function resize() {\n if (this.disabled) {\n return;\n }\n var options = this.options,\n container = this.container,\n containerData = this.containerData;\n var ratioX = container.offsetWidth / containerData.width;\n var ratioY = container.offsetHeight / containerData.height;\n var ratio = Math.abs(ratioX - 1) > Math.abs(ratioY - 1) ? ratioX : ratioY;\n\n // Resize when width changed or height changed\n if (ratio !== 1) {\n var canvasData;\n var cropBoxData;\n if (options.restore) {\n canvasData = this.getCanvasData();\n cropBoxData = this.getCropBoxData();\n }\n this.render();\n if (options.restore) {\n this.setCanvasData(forEach(canvasData, function (n, i) {\n canvasData[i] = n * ratio;\n }));\n this.setCropBoxData(forEach(cropBoxData, function (n, i) {\n cropBoxData[i] = n * ratio;\n }));\n }\n }\n },\n dblclick: function dblclick() {\n if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) {\n return;\n }\n this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP);\n },\n wheel: function wheel(event) {\n var _this = this;\n var ratio = Number(this.options.wheelZoomRatio) || 0.1;\n var delta = 1;\n if (this.disabled) {\n return;\n }\n event.preventDefault();\n\n // Limit wheel speed to prevent zoom too fast (#21)\n if (this.wheeling) {\n return;\n }\n this.wheeling = true;\n setTimeout(function () {\n _this.wheeling = false;\n }, 50);\n if (event.deltaY) {\n delta = event.deltaY > 0 ? 1 : -1;\n } else if (event.wheelDelta) {\n delta = -event.wheelDelta / 120;\n } else if (event.detail) {\n delta = event.detail > 0 ? 1 : -1;\n }\n this.zoom(-delta * ratio, event);\n },\n cropStart: function cropStart(event) {\n var buttons = event.buttons,\n button = event.button;\n if (this.disabled\n\n // Handle mouse event and pointer event and ignore touch event\n || (event.type === 'mousedown' || event.type === 'pointerdown' && event.pointerType === 'mouse') && (\n // No primary button (Usually the left button)\n isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0\n\n // Open context menu\n || event.ctrlKey)) {\n return;\n }\n var options = this.options,\n pointers = this.pointers;\n var action;\n if (event.changedTouches) {\n // Handle touch event\n forEach(event.changedTouches, function (touch) {\n pointers[touch.identifier] = getPointer(touch);\n });\n } else {\n // Handle mouse event and pointer event\n pointers[event.pointerId || 0] = getPointer(event);\n }\n if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) {\n action = ACTION_ZOOM;\n } else {\n action = getData(event.target, DATA_ACTION);\n }\n if (!REGEXP_ACTIONS.test(action)) {\n return;\n }\n if (dispatchEvent(this.element, EVENT_CROP_START, {\n originalEvent: event,\n action: action\n }) === false) {\n return;\n }\n\n // This line is required for preventing page zooming in iOS browsers\n event.preventDefault();\n this.action = action;\n this.cropping = false;\n if (action === ACTION_CROP) {\n this.cropping = true;\n addClass(this.dragBox, CLASS_MODAL);\n }\n },\n cropMove: function cropMove(event) {\n var action = this.action;\n if (this.disabled || !action) {\n return;\n }\n var pointers = this.pointers;\n event.preventDefault();\n if (dispatchEvent(this.element, EVENT_CROP_MOVE, {\n originalEvent: event,\n action: action\n }) === false) {\n return;\n }\n if (event.changedTouches) {\n forEach(event.changedTouches, function (touch) {\n // The first parameter should not be undefined (#432)\n assign(pointers[touch.identifier] || {}, getPointer(touch, true));\n });\n } else {\n assign(pointers[event.pointerId || 0] || {}, getPointer(event, true));\n }\n this.change(event);\n },\n cropEnd: function cropEnd(event) {\n if (this.disabled) {\n return;\n }\n var action = this.action,\n pointers = this.pointers;\n if (event.changedTouches) {\n forEach(event.changedTouches, function (touch) {\n delete pointers[touch.identifier];\n });\n } else {\n delete pointers[event.pointerId || 0];\n }\n if (!action) {\n return;\n }\n event.preventDefault();\n if (!Object.keys(pointers).length) {\n this.action = '';\n }\n if (this.cropping) {\n this.cropping = false;\n toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal);\n }\n dispatchEvent(this.element, EVENT_CROP_END, {\n originalEvent: event,\n action: action\n });\n }\n};\n\nvar change = {\n change: function change(event) {\n var options = this.options,\n canvasData = this.canvasData,\n containerData = this.containerData,\n cropBoxData = this.cropBoxData,\n pointers = this.pointers;\n var action = this.action;\n var aspectRatio = options.aspectRatio;\n var left = cropBoxData.left,\n top = cropBoxData.top,\n width = cropBoxData.width,\n height = cropBoxData.height;\n var right = left + width;\n var bottom = top + height;\n var minLeft = 0;\n var minTop = 0;\n var maxWidth = containerData.width;\n var maxHeight = containerData.height;\n var renderable = true;\n var offset;\n\n // Locking aspect ratio in \"free mode\" by holding shift key\n if (!aspectRatio && event.shiftKey) {\n aspectRatio = width && height ? width / height : 1;\n }\n if (this.limited) {\n minLeft = cropBoxData.minLeft;\n minTop = cropBoxData.minTop;\n maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width);\n maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height);\n }\n var pointer = pointers[Object.keys(pointers)[0]];\n var range = {\n x: pointer.endX - pointer.startX,\n y: pointer.endY - pointer.startY\n };\n var check = function check(side) {\n switch (side) {\n case ACTION_EAST:\n if (right + range.x > maxWidth) {\n range.x = maxWidth - right;\n }\n break;\n case ACTION_WEST:\n if (left + range.x < minLeft) {\n range.x = minLeft - left;\n }\n break;\n case ACTION_NORTH:\n if (top + range.y < minTop) {\n range.y = minTop - top;\n }\n break;\n case ACTION_SOUTH:\n if (bottom + range.y > maxHeight) {\n range.y = maxHeight - bottom;\n }\n break;\n }\n };\n switch (action) {\n // Move crop box\n case ACTION_ALL:\n left += range.x;\n top += range.y;\n break;\n\n // Resize crop box\n case ACTION_EAST:\n if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) {\n renderable = false;\n break;\n }\n check(ACTION_EAST);\n width += range.x;\n if (width < 0) {\n action = ACTION_WEST;\n width = -width;\n left -= width;\n }\n if (aspectRatio) {\n height = width / aspectRatio;\n top += (cropBoxData.height - height) / 2;\n }\n break;\n case ACTION_NORTH:\n if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) {\n renderable = false;\n break;\n }\n check(ACTION_NORTH);\n height -= range.y;\n top += range.y;\n if (height < 0) {\n action = ACTION_SOUTH;\n height = -height;\n top -= height;\n }\n if (aspectRatio) {\n width = height * aspectRatio;\n left += (cropBoxData.width - width) / 2;\n }\n break;\n case ACTION_WEST:\n if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) {\n renderable = false;\n break;\n }\n check(ACTION_WEST);\n width -= range.x;\n left += range.x;\n if (width < 0) {\n action = ACTION_EAST;\n width = -width;\n left -= width;\n }\n if (aspectRatio) {\n height = width / aspectRatio;\n top += (cropBoxData.height - height) / 2;\n }\n break;\n case ACTION_SOUTH:\n if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) {\n renderable = false;\n break;\n }\n check(ACTION_SOUTH);\n height += range.y;\n if (height < 0) {\n action = ACTION_NORTH;\n height = -height;\n top -= height;\n }\n if (aspectRatio) {\n width = height * aspectRatio;\n left += (cropBoxData.width - width) / 2;\n }\n break;\n case ACTION_NORTH_EAST:\n if (aspectRatio) {\n if (range.y <= 0 && (top <= minTop || right >= maxWidth)) {\n renderable = false;\n break;\n }\n check(ACTION_NORTH);\n height -= range.y;\n top += range.y;\n width = height * aspectRatio;\n } else {\n check(ACTION_NORTH);\n check(ACTION_EAST);\n if (range.x >= 0) {\n if (right < maxWidth) {\n width += range.x;\n } else if (range.y <= 0 && top <= minTop) {\n renderable = false;\n }\n } else {\n width += range.x;\n }\n if (range.y <= 0) {\n if (top > minTop) {\n height -= range.y;\n top += range.y;\n }\n } else {\n height -= range.y;\n top += range.y;\n }\n }\n if (width < 0 && height < 0) {\n action = ACTION_SOUTH_WEST;\n height = -height;\n width = -width;\n top -= height;\n left -= width;\n } else if (width < 0) {\n action = ACTION_NORTH_WEST;\n width = -width;\n left -= width;\n } else if (height < 0) {\n action = ACTION_SOUTH_EAST;\n height = -height;\n top -= height;\n }\n break;\n case ACTION_NORTH_WEST:\n if (aspectRatio) {\n if (range.y <= 0 && (top <= minTop || left <= minLeft)) {\n renderable = false;\n break;\n }\n check(ACTION_NORTH);\n height -= range.y;\n top += range.y;\n width = height * aspectRatio;\n left += cropBoxData.width - width;\n } else {\n check(ACTION_NORTH);\n check(ACTION_WEST);\n if (range.x <= 0) {\n if (left > minLeft) {\n width -= range.x;\n left += range.x;\n } else if (range.y <= 0 && top <= minTop) {\n renderable = false;\n }\n } else {\n width -= range.x;\n left += range.x;\n }\n if (range.y <= 0) {\n if (top > minTop) {\n height -= range.y;\n top += range.y;\n }\n } else {\n height -= range.y;\n top += range.y;\n }\n }\n if (width < 0 && height < 0) {\n action = ACTION_SOUTH_EAST;\n height = -height;\n width = -width;\n top -= height;\n left -= width;\n } else if (width < 0) {\n action = ACTION_NORTH_EAST;\n width = -width;\n left -= width;\n } else if (height < 0) {\n action = ACTION_SOUTH_WEST;\n height = -height;\n top -= height;\n }\n break;\n case ACTION_SOUTH_WEST:\n if (aspectRatio) {\n if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) {\n renderable = false;\n break;\n }\n check(ACTION_WEST);\n width -= range.x;\n left += range.x;\n height = width / aspectRatio;\n } else {\n check(ACTION_SOUTH);\n check(ACTION_WEST);\n if (range.x <= 0) {\n if (left > minLeft) {\n width -= range.x;\n left += range.x;\n } else if (range.y >= 0 && bottom >= maxHeight) {\n renderable = false;\n }\n } else {\n width -= range.x;\n left += range.x;\n }\n if (range.y >= 0) {\n if (bottom < maxHeight) {\n height += range.y;\n }\n } else {\n height += range.y;\n }\n }\n if (width < 0 && height < 0) {\n action = ACTION_NORTH_EAST;\n height = -height;\n width = -width;\n top -= height;\n left -= width;\n } else if (width < 0) {\n action = ACTION_SOUTH_EAST;\n width = -width;\n left -= width;\n } else if (height < 0) {\n action = ACTION_NORTH_WEST;\n height = -height;\n top -= height;\n }\n break;\n case ACTION_SOUTH_EAST:\n if (aspectRatio) {\n if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) {\n renderable = false;\n break;\n }\n check(ACTION_EAST);\n width += range.x;\n height = width / aspectRatio;\n } else {\n check(ACTION_SOUTH);\n check(ACTION_EAST);\n if (range.x >= 0) {\n if (right < maxWidth) {\n width += range.x;\n } else if (range.y >= 0 && bottom >= maxHeight) {\n renderable = false;\n }\n } else {\n width += range.x;\n }\n if (range.y >= 0) {\n if (bottom < maxHeight) {\n height += range.y;\n }\n } else {\n height += range.y;\n }\n }\n if (width < 0 && height < 0) {\n action = ACTION_NORTH_WEST;\n height = -height;\n width = -width;\n top -= height;\n left -= width;\n } else if (width < 0) {\n action = ACTION_SOUTH_WEST;\n width = -width;\n left -= width;\n } else if (height < 0) {\n action = ACTION_NORTH_EAST;\n height = -height;\n top -= height;\n }\n break;\n\n // Move canvas\n case ACTION_MOVE:\n this.move(range.x, range.y);\n renderable = false;\n break;\n\n // Zoom canvas\n case ACTION_ZOOM:\n this.zoom(getMaxZoomRatio(pointers), event);\n renderable = false;\n break;\n\n // Create crop box\n case ACTION_CROP:\n if (!range.x || !range.y) {\n renderable = false;\n break;\n }\n offset = getOffset(this.cropper);\n left = pointer.startX - offset.left;\n top = pointer.startY - offset.top;\n width = cropBoxData.minWidth;\n height = cropBoxData.minHeight;\n if (range.x > 0) {\n action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST;\n } else if (range.x < 0) {\n left -= width;\n action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST;\n }\n if (range.y < 0) {\n top -= height;\n }\n\n // Show the crop box if is hidden\n if (!this.cropped) {\n removeClass(this.cropBox, CLASS_HIDDEN);\n this.cropped = true;\n if (this.limited) {\n this.limitCropBox(true, true);\n }\n }\n break;\n }\n if (renderable) {\n cropBoxData.width = width;\n cropBoxData.height = height;\n cropBoxData.left = left;\n cropBoxData.top = top;\n this.action = action;\n this.renderCropBox();\n }\n\n // Override\n forEach(pointers, function (p) {\n p.startX = p.endX;\n p.startY = p.endY;\n });\n }\n};\n\nvar methods = {\n // Show the crop box manually\n crop: function crop() {\n if (this.ready && !this.cropped && !this.disabled) {\n this.cropped = true;\n this.limitCropBox(true, true);\n if (this.options.modal) {\n addClass(this.dragBox, CLASS_MODAL);\n }\n removeClass(this.cropBox, CLASS_HIDDEN);\n this.setCropBoxData(this.initialCropBoxData);\n }\n return this;\n },\n // Reset the image and crop box to their initial states\n reset: function reset() {\n if (this.ready && !this.disabled) {\n this.imageData = assign({}, this.initialImageData);\n this.canvasData = assign({}, this.initialCanvasData);\n this.cropBoxData = assign({}, this.initialCropBoxData);\n this.renderCanvas();\n if (this.cropped) {\n this.renderCropBox();\n }\n }\n return this;\n },\n // Clear the crop box\n clear: function clear() {\n if (this.cropped && !this.disabled) {\n assign(this.cropBoxData, {\n left: 0,\n top: 0,\n width: 0,\n height: 0\n });\n this.cropped = false;\n this.renderCropBox();\n this.limitCanvas(true, true);\n\n // Render canvas after crop box rendered\n this.renderCanvas();\n removeClass(this.dragBox, CLASS_MODAL);\n addClass(this.cropBox, CLASS_HIDDEN);\n }\n return this;\n },\n /**\n * Replace the image's src and rebuild the cropper\n * @param {string} url - The new URL.\n * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one.\n * @returns {Cropper} this\n */\n replace: function replace(url) {\n var hasSameSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (!this.disabled && url) {\n if (this.isImg) {\n this.element.src = url;\n }\n if (hasSameSize) {\n this.url = url;\n this.image.src = url;\n if (this.ready) {\n this.viewBoxImage.src = url;\n forEach(this.previews, function (element) {\n element.getElementsByTagName('img')[0].src = url;\n });\n }\n } else {\n if (this.isImg) {\n this.replaced = true;\n }\n this.options.data = null;\n this.uncreate();\n this.load(url);\n }\n }\n return this;\n },\n // Enable (unfreeze) the cropper\n enable: function enable() {\n if (this.ready && this.disabled) {\n this.disabled = false;\n removeClass(this.cropper, CLASS_DISABLED);\n }\n return this;\n },\n // Disable (freeze) the cropper\n disable: function disable() {\n if (this.ready && !this.disabled) {\n this.disabled = true;\n addClass(this.cropper, CLASS_DISABLED);\n }\n return this;\n },\n /**\n * Destroy the cropper and remove the instance from the image\n * @returns {Cropper} this\n */\n destroy: function destroy() {\n var element = this.element;\n if (!element[NAMESPACE]) {\n return this;\n }\n element[NAMESPACE] = undefined;\n if (this.isImg && this.replaced) {\n element.src = this.originalUrl;\n }\n this.uncreate();\n return this;\n },\n /**\n * Move the canvas with relative offsets\n * @param {number} offsetX - The relative offset distance on the x-axis.\n * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis.\n * @returns {Cropper} this\n */\n move: function move(offsetX) {\n var offsetY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : offsetX;\n var _this$canvasData = this.canvasData,\n left = _this$canvasData.left,\n top = _this$canvasData.top;\n return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY));\n },\n /**\n * Move the canvas to an absolute point\n * @param {number} x - The x-axis coordinate.\n * @param {number} [y=x] - The y-axis coordinate.\n * @returns {Cropper} this\n */\n moveTo: function moveTo(x) {\n var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;\n var canvasData = this.canvasData;\n var changed = false;\n x = Number(x);\n y = Number(y);\n if (this.ready && !this.disabled && this.options.movable) {\n if (isNumber(x)) {\n canvasData.left = x;\n changed = true;\n }\n if (isNumber(y)) {\n canvasData.top = y;\n changed = true;\n }\n if (changed) {\n this.renderCanvas(true);\n }\n }\n return this;\n },\n /**\n * Zoom the canvas with a relative ratio\n * @param {number} ratio - The target ratio.\n * @param {Event} _originalEvent - The original event if any.\n * @returns {Cropper} this\n */\n zoom: function zoom(ratio, _originalEvent) {\n var canvasData = this.canvasData;\n ratio = Number(ratio);\n if (ratio < 0) {\n ratio = 1 / (1 - ratio);\n } else {\n ratio = 1 + ratio;\n }\n return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent);\n },\n /**\n * Zoom the canvas to an absolute ratio\n * @param {number} ratio - The target ratio.\n * @param {Object} pivot - The zoom pivot point coordinate.\n * @param {Event} _originalEvent - The original event if any.\n * @returns {Cropper} this\n */\n zoomTo: function zoomTo(ratio, pivot, _originalEvent) {\n var options = this.options,\n canvasData = this.canvasData;\n var width = canvasData.width,\n height = canvasData.height,\n naturalWidth = canvasData.naturalWidth,\n naturalHeight = canvasData.naturalHeight;\n ratio = Number(ratio);\n if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) {\n var newWidth = naturalWidth * ratio;\n var newHeight = naturalHeight * ratio;\n if (dispatchEvent(this.element, EVENT_ZOOM, {\n ratio: ratio,\n oldRatio: width / naturalWidth,\n originalEvent: _originalEvent\n }) === false) {\n return this;\n }\n if (_originalEvent) {\n var pointers = this.pointers;\n var offset = getOffset(this.cropper);\n var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : {\n pageX: _originalEvent.pageX,\n pageY: _originalEvent.pageY\n };\n\n // Zoom from the triggering point of the event\n canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width);\n canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height);\n } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) {\n canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width);\n canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height);\n } else {\n // Zoom from the center of the canvas\n canvasData.left -= (newWidth - width) / 2;\n canvasData.top -= (newHeight - height) / 2;\n }\n canvasData.width = newWidth;\n canvasData.height = newHeight;\n this.renderCanvas(true);\n }\n return this;\n },\n /**\n * Rotate the canvas with a relative degree\n * @param {number} degree - The rotate degree.\n * @returns {Cropper} this\n */\n rotate: function rotate(degree) {\n return this.rotateTo((this.imageData.rotate || 0) + Number(degree));\n },\n /**\n * Rotate the canvas to an absolute degree\n * @param {number} degree - The rotate degree.\n * @returns {Cropper} this\n */\n rotateTo: function rotateTo(degree) {\n degree = Number(degree);\n if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) {\n this.imageData.rotate = degree % 360;\n this.renderCanvas(true, true);\n }\n return this;\n },\n /**\n * Scale the image on the x-axis.\n * @param {number} scaleX - The scale ratio on the x-axis.\n * @returns {Cropper} this\n */\n scaleX: function scaleX(_scaleX) {\n var scaleY = this.imageData.scaleY;\n return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1);\n },\n /**\n * Scale the image on the y-axis.\n * @param {number} scaleY - The scale ratio on the y-axis.\n * @returns {Cropper} this\n */\n scaleY: function scaleY(_scaleY) {\n var scaleX = this.imageData.scaleX;\n return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY);\n },\n /**\n * Scale the image\n * @param {number} scaleX - The scale ratio on the x-axis.\n * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis.\n * @returns {Cropper} this\n */\n scale: function scale(scaleX) {\n var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX;\n var imageData = this.imageData;\n var transformed = false;\n scaleX = Number(scaleX);\n scaleY = Number(scaleY);\n if (this.ready && !this.disabled && this.options.scalable) {\n if (isNumber(scaleX)) {\n imageData.scaleX = scaleX;\n transformed = true;\n }\n if (isNumber(scaleY)) {\n imageData.scaleY = scaleY;\n transformed = true;\n }\n if (transformed) {\n this.renderCanvas(true, true);\n }\n }\n return this;\n },\n /**\n * Get the cropped area position and size data (base on the original image)\n * @param {boolean} [rounded=false] - Indicate if round the data values or not.\n * @returns {Object} The result cropped data.\n */\n getData: function getData() {\n var rounded = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var options = this.options,\n imageData = this.imageData,\n canvasData = this.canvasData,\n cropBoxData = this.cropBoxData;\n var data;\n if (this.ready && this.cropped) {\n data = {\n x: cropBoxData.left - canvasData.left,\n y: cropBoxData.top - canvasData.top,\n width: cropBoxData.width,\n height: cropBoxData.height\n };\n var ratio = imageData.width / imageData.naturalWidth;\n forEach(data, function (n, i) {\n data[i] = n / ratio;\n });\n if (rounded) {\n // In case rounding off leads to extra 1px in right or bottom border\n // we should round the top-left corner and the dimension (#343).\n var bottom = Math.round(data.y + data.height);\n var right = Math.round(data.x + data.width);\n data.x = Math.round(data.x);\n data.y = Math.round(data.y);\n data.width = right - data.x;\n data.height = bottom - data.y;\n }\n } else {\n data = {\n x: 0,\n y: 0,\n width: 0,\n height: 0\n };\n }\n if (options.rotatable) {\n data.rotate = imageData.rotate || 0;\n }\n if (options.scalable) {\n data.scaleX = imageData.scaleX || 1;\n data.scaleY = imageData.scaleY || 1;\n }\n return data;\n },\n /**\n * Set the cropped area position and size with new data\n * @param {Object} data - The new data.\n * @returns {Cropper} this\n */\n setData: function setData(data) {\n var options = this.options,\n imageData = this.imageData,\n canvasData = this.canvasData;\n var cropBoxData = {};\n if (this.ready && !this.disabled && isPlainObject(data)) {\n var transformed = false;\n if (options.rotatable) {\n if (isNumber(data.rotate) && data.rotate !== imageData.rotate) {\n imageData.rotate = data.rotate;\n transformed = true;\n }\n }\n if (options.scalable) {\n if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) {\n imageData.scaleX = data.scaleX;\n transformed = true;\n }\n if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) {\n imageData.scaleY = data.scaleY;\n transformed = true;\n }\n }\n if (transformed) {\n this.renderCanvas(true, true);\n }\n var ratio = imageData.width / imageData.naturalWidth;\n if (isNumber(data.x)) {\n cropBoxData.left = data.x * ratio + canvasData.left;\n }\n if (isNumber(data.y)) {\n cropBoxData.top = data.y * ratio + canvasData.top;\n }\n if (isNumber(data.width)) {\n cropBoxData.width = data.width * ratio;\n }\n if (isNumber(data.height)) {\n cropBoxData.height = data.height * ratio;\n }\n this.setCropBoxData(cropBoxData);\n }\n return this;\n },\n /**\n * Get the container size data.\n * @returns {Object} The result container data.\n */\n getContainerData: function getContainerData() {\n return this.ready ? assign({}, this.containerData) : {};\n },\n /**\n * Get the image position and size data.\n * @returns {Object} The result image data.\n */\n getImageData: function getImageData() {\n return this.sized ? assign({}, this.imageData) : {};\n },\n /**\n * Get the canvas position and size data.\n * @returns {Object} The result canvas data.\n */\n getCanvasData: function getCanvasData() {\n var canvasData = this.canvasData;\n var data = {};\n if (this.ready) {\n forEach(['left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight'], function (n) {\n data[n] = canvasData[n];\n });\n }\n return data;\n },\n /**\n * Set the canvas position and size with new data.\n * @param {Object} data - The new canvas data.\n * @returns {Cropper} this\n */\n setCanvasData: function setCanvasData(data) {\n var canvasData = this.canvasData;\n var aspectRatio = canvasData.aspectRatio;\n if (this.ready && !this.disabled && isPlainObject(data)) {\n if (isNumber(data.left)) {\n canvasData.left = data.left;\n }\n if (isNumber(data.top)) {\n canvasData.top = data.top;\n }\n if (isNumber(data.width)) {\n canvasData.width = data.width;\n canvasData.height = data.width / aspectRatio;\n } else if (isNumber(data.height)) {\n canvasData.height = data.height;\n canvasData.width = data.height * aspectRatio;\n }\n this.renderCanvas(true);\n }\n return this;\n },\n /**\n * Get the crop box position and size data.\n * @returns {Object} The result crop box data.\n */\n getCropBoxData: function getCropBoxData() {\n var cropBoxData = this.cropBoxData;\n var data;\n if (this.ready && this.cropped) {\n data = {\n left: cropBoxData.left,\n top: cropBoxData.top,\n width: cropBoxData.width,\n height: cropBoxData.height\n };\n }\n return data || {};\n },\n /**\n * Set the crop box position and size with new data.\n * @param {Object} data - The new crop box data.\n * @returns {Cropper} this\n */\n setCropBoxData: function setCropBoxData(data) {\n var cropBoxData = this.cropBoxData;\n var aspectRatio = this.options.aspectRatio;\n var widthChanged;\n var heightChanged;\n if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) {\n if (isNumber(data.left)) {\n cropBoxData.left = data.left;\n }\n if (isNumber(data.top)) {\n cropBoxData.top = data.top;\n }\n if (isNumber(data.width) && data.width !== cropBoxData.width) {\n widthChanged = true;\n cropBoxData.width = data.width;\n }\n if (isNumber(data.height) && data.height !== cropBoxData.height) {\n heightChanged = true;\n cropBoxData.height = data.height;\n }\n if (aspectRatio) {\n if (widthChanged) {\n cropBoxData.height = cropBoxData.width / aspectRatio;\n } else if (heightChanged) {\n cropBoxData.width = cropBoxData.height * aspectRatio;\n }\n }\n this.renderCropBox();\n }\n return this;\n },\n /**\n * Get a canvas drawn the cropped image.\n * @param {Object} [options={}] - The config options.\n * @returns {HTMLCanvasElement} - The result canvas.\n */\n getCroppedCanvas: function getCroppedCanvas() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (!this.ready || !window.HTMLCanvasElement) {\n return null;\n }\n var canvasData = this.canvasData;\n var source = getSourceCanvas(this.image, this.imageData, canvasData, options);\n\n // Returns the source canvas if it is not cropped.\n if (!this.cropped) {\n return source;\n }\n var _this$getData = this.getData(options.rounded),\n initialX = _this$getData.x,\n initialY = _this$getData.y,\n initialWidth = _this$getData.width,\n initialHeight = _this$getData.height;\n var ratio = source.width / Math.floor(canvasData.naturalWidth);\n if (ratio !== 1) {\n initialX *= ratio;\n initialY *= ratio;\n initialWidth *= ratio;\n initialHeight *= ratio;\n }\n var aspectRatio = initialWidth / initialHeight;\n var maxSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: options.maxWidth || Infinity,\n height: options.maxHeight || Infinity\n });\n var minSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: options.minWidth || 0,\n height: options.minHeight || 0\n }, 'cover');\n var _getAdjustedSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: options.width || (ratio !== 1 ? source.width : initialWidth),\n height: options.height || (ratio !== 1 ? source.height : initialHeight)\n }),\n width = _getAdjustedSizes.width,\n height = _getAdjustedSizes.height;\n width = Math.min(maxSizes.width, Math.max(minSizes.width, width));\n height = Math.min(maxSizes.height, Math.max(minSizes.height, height));\n var canvas = document.createElement('canvas');\n var context = canvas.getContext('2d');\n canvas.width = normalizeDecimalNumber(width);\n canvas.height = normalizeDecimalNumber(height);\n context.fillStyle = options.fillColor || 'transparent';\n context.fillRect(0, 0, width, height);\n var _options$imageSmoothi = options.imageSmoothingEnabled,\n imageSmoothingEnabled = _options$imageSmoothi === void 0 ? true : _options$imageSmoothi,\n imageSmoothingQuality = options.imageSmoothingQuality;\n context.imageSmoothingEnabled = imageSmoothingEnabled;\n if (imageSmoothingQuality) {\n context.imageSmoothingQuality = imageSmoothingQuality;\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage\n var sourceWidth = source.width;\n var sourceHeight = source.height;\n\n // Source canvas parameters\n var srcX = initialX;\n var srcY = initialY;\n var srcWidth;\n var srcHeight;\n\n // Destination canvas parameters\n var dstX;\n var dstY;\n var dstWidth;\n var dstHeight;\n if (srcX <= -initialWidth || srcX > sourceWidth) {\n srcX = 0;\n srcWidth = 0;\n dstX = 0;\n dstWidth = 0;\n } else if (srcX <= 0) {\n dstX = -srcX;\n srcX = 0;\n srcWidth = Math.min(sourceWidth, initialWidth + srcX);\n dstWidth = srcWidth;\n } else if (srcX <= sourceWidth) {\n dstX = 0;\n srcWidth = Math.min(initialWidth, sourceWidth - srcX);\n dstWidth = srcWidth;\n }\n if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) {\n srcY = 0;\n srcHeight = 0;\n dstY = 0;\n dstHeight = 0;\n } else if (srcY <= 0) {\n dstY = -srcY;\n srcY = 0;\n srcHeight = Math.min(sourceHeight, initialHeight + srcY);\n dstHeight = srcHeight;\n } else if (srcY <= sourceHeight) {\n dstY = 0;\n srcHeight = Math.min(initialHeight, sourceHeight - srcY);\n dstHeight = srcHeight;\n }\n var params = [srcX, srcY, srcWidth, srcHeight];\n\n // Avoid \"IndexSizeError\"\n if (dstWidth > 0 && dstHeight > 0) {\n var scale = width / initialWidth;\n params.push(dstX * scale, dstY * scale, dstWidth * scale, dstHeight * scale);\n }\n\n // All the numerical parameters should be integer for `drawImage`\n // https://github.com/fengyuanchen/cropper/issues/476\n context.drawImage.apply(context, [source].concat(_toConsumableArray(params.map(function (param) {\n return Math.floor(normalizeDecimalNumber(param));\n }))));\n return canvas;\n },\n /**\n * Change the aspect ratio of the crop box.\n * @param {number} aspectRatio - The new aspect ratio.\n * @returns {Cropper} this\n */\n setAspectRatio: function setAspectRatio(aspectRatio) {\n var options = this.options;\n if (!this.disabled && !isUndefined(aspectRatio)) {\n // 0 -> NaN\n options.aspectRatio = Math.max(0, aspectRatio) || NaN;\n if (this.ready) {\n this.initCropBox();\n if (this.cropped) {\n this.renderCropBox();\n }\n }\n }\n return this;\n },\n /**\n * Change the drag mode.\n * @param {string} mode - The new drag mode.\n * @returns {Cropper} this\n */\n setDragMode: function setDragMode(mode) {\n var options = this.options,\n dragBox = this.dragBox,\n face = this.face;\n if (this.ready && !this.disabled) {\n var croppable = mode === DRAG_MODE_CROP;\n var movable = options.movable && mode === DRAG_MODE_MOVE;\n mode = croppable || movable ? mode : DRAG_MODE_NONE;\n options.dragMode = mode;\n setData(dragBox, DATA_ACTION, mode);\n toggleClass(dragBox, CLASS_CROP, croppable);\n toggleClass(dragBox, CLASS_MOVE, movable);\n if (!options.cropBoxMovable) {\n // Sync drag mode to crop box when it is not movable\n setData(face, DATA_ACTION, mode);\n toggleClass(face, CLASS_CROP, croppable);\n toggleClass(face, CLASS_MOVE, movable);\n }\n }\n return this;\n }\n};\n\nvar AnotherCropper = WINDOW.Cropper;\nvar Cropper = /*#__PURE__*/function () {\n /**\n * Create a new Cropper.\n * @param {Element} element - The target element for cropping.\n * @param {Object} [options={}] - The configuration options.\n */\n function Cropper(element) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n _classCallCheck(this, Cropper);\n if (!element || !REGEXP_TAG_NAME.test(element.tagName)) {\n throw new Error('The first argument is required and must be an or element.');\n }\n this.element = element;\n this.options = assign({}, DEFAULTS, isPlainObject(options) && options);\n this.cropped = false;\n this.disabled = false;\n this.pointers = {};\n this.ready = false;\n this.reloading = false;\n this.replaced = false;\n this.sized = false;\n this.sizing = false;\n this.init();\n }\n return _createClass(Cropper, [{\n key: \"init\",\n value: function init() {\n var element = this.element;\n var tagName = element.tagName.toLowerCase();\n var url;\n if (element[NAMESPACE]) {\n return;\n }\n element[NAMESPACE] = this;\n if (tagName === 'img') {\n this.isImg = true;\n\n // e.g.: \"img/picture.jpg\"\n url = element.getAttribute('src') || '';\n this.originalUrl = url;\n\n // Stop when it's a blank image\n if (!url) {\n return;\n }\n\n // e.g.: \"https://example.com/img/picture.jpg\"\n url = element.src;\n } else if (tagName === 'canvas' && window.HTMLCanvasElement) {\n url = element.toDataURL();\n }\n this.load(url);\n }\n }, {\n key: \"load\",\n value: function load(url) {\n var _this = this;\n if (!url) {\n return;\n }\n this.url = url;\n this.imageData = {};\n var element = this.element,\n options = this.options;\n if (!options.rotatable && !options.scalable) {\n options.checkOrientation = false;\n }\n\n // Only IE10+ supports Typed Arrays\n if (!options.checkOrientation || !window.ArrayBuffer) {\n this.clone();\n return;\n }\n\n // Detect the mime type of the image directly if it is a Data URL\n if (REGEXP_DATA_URL.test(url)) {\n // Read ArrayBuffer from Data URL of JPEG images directly for better performance\n if (REGEXP_DATA_URL_JPEG.test(url)) {\n this.read(dataURLToArrayBuffer(url));\n } else {\n // Only a JPEG image may contains Exif Orientation information,\n // the rest types of Data URLs are not necessary to check orientation at all.\n this.clone();\n }\n return;\n }\n\n // 1. Detect the mime type of the image by a XMLHttpRequest.\n // 2. Load the image as ArrayBuffer for reading orientation if its a JPEG image.\n var xhr = new XMLHttpRequest();\n var clone = this.clone.bind(this);\n this.reloading = true;\n this.xhr = xhr;\n\n // 1. Cross origin requests are only supported for protocol schemes:\n // http, https, data, chrome, chrome-extension.\n // 2. Access to XMLHttpRequest from a Data URL will be blocked by CORS policy\n // in some browsers as IE11 and Safari.\n xhr.onabort = clone;\n xhr.onerror = clone;\n xhr.ontimeout = clone;\n xhr.onprogress = function () {\n // Abort the request directly if it not a JPEG image for better performance\n if (xhr.getResponseHeader('content-type') !== MIME_TYPE_JPEG) {\n xhr.abort();\n }\n };\n xhr.onload = function () {\n _this.read(xhr.response);\n };\n xhr.onloadend = function () {\n _this.reloading = false;\n _this.xhr = null;\n };\n\n // Bust cache when there is a \"crossOrigin\" property to avoid browser cache error\n if (options.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) {\n url = addTimestamp(url);\n }\n\n // The third parameter is required for avoiding side-effect (#682)\n xhr.open('GET', url, true);\n xhr.responseType = 'arraybuffer';\n xhr.withCredentials = element.crossOrigin === 'use-credentials';\n xhr.send();\n }\n }, {\n key: \"read\",\n value: function read(arrayBuffer) {\n var options = this.options,\n imageData = this.imageData;\n\n // Reset the orientation value to its default value 1\n // as some iOS browsers will render image with its orientation\n var orientation = resetAndGetOrientation(arrayBuffer);\n var rotate = 0;\n var scaleX = 1;\n var scaleY = 1;\n if (orientation > 1) {\n // Generate a new URL which has the default orientation value\n this.url = arrayBufferToDataURL(arrayBuffer, MIME_TYPE_JPEG);\n var _parseOrientation = parseOrientation(orientation);\n rotate = _parseOrientation.rotate;\n scaleX = _parseOrientation.scaleX;\n scaleY = _parseOrientation.scaleY;\n }\n if (options.rotatable) {\n imageData.rotate = rotate;\n }\n if (options.scalable) {\n imageData.scaleX = scaleX;\n imageData.scaleY = scaleY;\n }\n this.clone();\n }\n }, {\n key: \"clone\",\n value: function clone() {\n var element = this.element,\n url = this.url;\n var crossOrigin = element.crossOrigin;\n var crossOriginUrl = url;\n if (this.options.checkCrossOrigin && isCrossOriginURL(url)) {\n if (!crossOrigin) {\n crossOrigin = 'anonymous';\n }\n\n // Bust cache when there is not a \"crossOrigin\" property (#519)\n crossOriginUrl = addTimestamp(url);\n }\n this.crossOrigin = crossOrigin;\n this.crossOriginUrl = crossOriginUrl;\n var image = document.createElement('img');\n if (crossOrigin) {\n image.crossOrigin = crossOrigin;\n }\n image.src = crossOriginUrl || url;\n image.alt = element.alt || 'The image to crop';\n this.image = image;\n image.onload = this.start.bind(this);\n image.onerror = this.stop.bind(this);\n addClass(image, CLASS_HIDE);\n element.parentNode.insertBefore(image, element.nextSibling);\n }\n }, {\n key: \"start\",\n value: function start() {\n var _this2 = this;\n var image = this.image;\n image.onload = null;\n image.onerror = null;\n this.sizing = true;\n\n // Match all browsers that use WebKit as the layout engine in iOS devices,\n // such as Safari for iOS, Chrome for iOS, and in-app browsers.\n var isIOSWebKit = WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent);\n var done = function done(naturalWidth, naturalHeight) {\n assign(_this2.imageData, {\n naturalWidth: naturalWidth,\n naturalHeight: naturalHeight,\n aspectRatio: naturalWidth / naturalHeight\n });\n _this2.initialImageData = assign({}, _this2.imageData);\n _this2.sizing = false;\n _this2.sized = true;\n _this2.build();\n };\n\n // Most modern browsers (excepts iOS WebKit)\n if (image.naturalWidth && !isIOSWebKit) {\n done(image.naturalWidth, image.naturalHeight);\n return;\n }\n var sizingImage = document.createElement('img');\n var body = document.body || document.documentElement;\n this.sizingImage = sizingImage;\n sizingImage.onload = function () {\n done(sizingImage.width, sizingImage.height);\n if (!isIOSWebKit) {\n body.removeChild(sizingImage);\n }\n };\n sizingImage.src = image.src;\n\n // iOS WebKit will convert the image automatically\n // with its orientation once append it into DOM (#279)\n if (!isIOSWebKit) {\n sizingImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;';\n body.appendChild(sizingImage);\n }\n }\n }, {\n key: \"stop\",\n value: function stop() {\n var image = this.image;\n image.onload = null;\n image.onerror = null;\n image.parentNode.removeChild(image);\n this.image = null;\n }\n }, {\n key: \"build\",\n value: function build() {\n if (!this.sized || this.ready) {\n return;\n }\n var element = this.element,\n options = this.options,\n image = this.image;\n\n // Create cropper elements\n var container = element.parentNode;\n var template = document.createElement('div');\n template.innerHTML = TEMPLATE;\n var cropper = template.querySelector(\".\".concat(NAMESPACE, \"-container\"));\n var canvas = cropper.querySelector(\".\".concat(NAMESPACE, \"-canvas\"));\n var dragBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-drag-box\"));\n var cropBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-crop-box\"));\n var face = cropBox.querySelector(\".\".concat(NAMESPACE, \"-face\"));\n this.container = container;\n this.cropper = cropper;\n this.canvas = canvas;\n this.dragBox = dragBox;\n this.cropBox = cropBox;\n this.viewBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-view-box\"));\n this.face = face;\n canvas.appendChild(image);\n\n // Hide the original image\n addClass(element, CLASS_HIDDEN);\n\n // Inserts the cropper after to the current image\n container.insertBefore(cropper, element.nextSibling);\n\n // Show the hidden image\n removeClass(image, CLASS_HIDE);\n this.initPreview();\n this.bind();\n options.initialAspectRatio = Math.max(0, options.initialAspectRatio) || NaN;\n options.aspectRatio = Math.max(0, options.aspectRatio) || NaN;\n options.viewMode = Math.max(0, Math.min(3, Math.round(options.viewMode))) || 0;\n addClass(cropBox, CLASS_HIDDEN);\n if (!options.guides) {\n addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-dashed\")), CLASS_HIDDEN);\n }\n if (!options.center) {\n addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-center\")), CLASS_HIDDEN);\n }\n if (options.background) {\n addClass(cropper, \"\".concat(NAMESPACE, \"-bg\"));\n }\n if (!options.highlight) {\n addClass(face, CLASS_INVISIBLE);\n }\n if (options.cropBoxMovable) {\n addClass(face, CLASS_MOVE);\n setData(face, DATA_ACTION, ACTION_ALL);\n }\n if (!options.cropBoxResizable) {\n addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-line\")), CLASS_HIDDEN);\n addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-point\")), CLASS_HIDDEN);\n }\n this.render();\n this.ready = true;\n this.setDragMode(options.dragMode);\n if (options.autoCrop) {\n this.crop();\n }\n this.setData(options.data);\n if (isFunction(options.ready)) {\n addListener(element, EVENT_READY, options.ready, {\n once: true\n });\n }\n dispatchEvent(element, EVENT_READY);\n }\n }, {\n key: \"unbuild\",\n value: function unbuild() {\n if (!this.ready) {\n return;\n }\n this.ready = false;\n this.unbind();\n this.resetPreview();\n var parentNode = this.cropper.parentNode;\n if (parentNode) {\n parentNode.removeChild(this.cropper);\n }\n removeClass(this.element, CLASS_HIDDEN);\n }\n }, {\n key: \"uncreate\",\n value: function uncreate() {\n if (this.ready) {\n this.unbuild();\n this.ready = false;\n this.cropped = false;\n } else if (this.sizing) {\n this.sizingImage.onload = null;\n this.sizing = false;\n this.sized = false;\n } else if (this.reloading) {\n this.xhr.onabort = null;\n this.xhr.abort();\n } else if (this.image) {\n this.stop();\n }\n }\n\n /**\n * Get the no conflict cropper class.\n * @returns {Cropper} The cropper class.\n */\n }], [{\n key: \"noConflict\",\n value: function noConflict() {\n window.Cropper = AnotherCropper;\n return Cropper;\n }\n\n /**\n * Change the default options.\n * @param {Object} options - The new default options.\n */\n }, {\n key: \"setDefaults\",\n value: function setDefaults(options) {\n assign(DEFAULTS, isPlainObject(options) && options);\n }\n }]);\n}();\nassign(Cropper.prototype, render, preview, events, handlers, change, methods);\n\nexport { Cropper as default };\n","import e,{useRef as r,useEffect as o}from\"react\";import t from\"cropperjs\";var n=function(){return n=Object.assign||function(e){for(var r,o=1,t=arguments.length;o0&&e.zoomTo(s)}(e.currentTarget.cropper,M),w&&w(e)}}));x&&x(e)}return function(){var e,r;null===(r=null===(e=E.current)||void 0===e?void 0:e.cropper)||void 0===r||r.destroy()}}),[E]);var R=function(e){return c.reduce((function(e,r){var o=e,t=r;return o[t],a(o,[\"symbol\"==typeof t?t:t+\"\"])}),e)}(n(n({},j),{crossOrigin:g,src:v,alt:C}));return e.createElement(\"div\",{style:f,className:m},e.createElement(\"img\",n({},R,{style:i,ref:E})))}));export{l as Cropper,l as default};\n","import React, { useRef, useState } from 'react';\nimport { Cropper } from 'react-cropper';\nimport { Button, Group, Image, Box } from '@mantine/core';\nimport 'cropperjs/dist/cropper.css';\n\ninterface ImageCropperProps {\n src: string; // The base64 or URL of the original image\n aspectRatio?: number;\n setCroppedBlob: (blob: Blob) => void;\n}\n\nexport default function ImageCropper({ src, aspectRatio, setCroppedBlob }: ImageCropperProps) {\n const cropperRef = useRef(null);\n const [croppedPreviewUrl, setCroppedPreviewUrl] = useState(null);\n const [showCropper, setShowCropper] = useState(true);\n\n // Called when user clicks \"Crop\" button\n const handleCrop = () => {\n const cropper = (cropperRef.current as any)?.cropper;\n if (!cropper) return;\n\n const canvas = cropper.getCroppedCanvas();\n if (!canvas) return;\n\n // 1. Create a data URL for a preview \n const dataUrl = canvas.toDataURL('image/png');\n setCroppedPreviewUrl(dataUrl);\n\n // 2. Create a Blob for uploading\n canvas.toBlob((blob: Blob | null) => {\n if (blob) {\n setCroppedBlob(blob);\n }\n }, 'image/png');\n\n // 3. Hide the cropper, show the preview instead\n setShowCropper(false);\n };\n\n // Optional reset: clear the crop box and preview\n const handleReset = () => {\n const cropper = (cropperRef.current as any)?.cropper;\n cropper?.reset();\n setCroppedPreviewUrl(null);\n };\n\n return (\n \n {showCropper && (\n \n \n\n \n \n Crop\n \n \n \n )}\n\n {croppedPreviewUrl && (\n \n \"Cropped\n \n )}\n \n );\n}\n","// components/ImageUploadModal.tsx\nimport React, { useState, useEffect } from 'react';\nimport { Modal, Group, Button, Text, Image } from '@mantine/core';\nimport { Dropzone, IMAGE_MIME_TYPE } from '@mantine/dropzone';\nimport { IconUpload, IconPhoto, IconX } from '@tabler/icons-react';\nimport ImageCropper from './ImageCropper';\n\ninterface ImageUploadModalProps {\n previewUrl?: string | null;\n onImageChange: (file: File) => void;\n}\n\nconst ImageUploadModal: React.FC = ({ previewUrl, onImageChange }) => {\n const [modalOpen, setModalOpen] = useState(false);\n const [imageSrc, setImageSrc] = useState(null);\n const [croppedBlob, setCroppedBlob] = useState(null);\n const [isHovering, setIsHovering] = useState(false);\n\n // Common handler for any image drop/selection\n const handleDrop = (files: File[]) => {\n if (files.length > 0) {\n const file = files[0];\n console.log('📸 Image selected:', file);\n\n // Set image source for cropping and open the modal\n setImageSrc(URL.createObjectURL(file));\n setModalOpen(true);\n }\n };\n\n // Called by the cropper when an image has been cropped\n const handleCropped = (blob: Blob) => {\n setCroppedBlob(blob);\n };\n\n const handleModalSubmit = () => {\n if (croppedBlob) {\n const newFile = new File([croppedBlob], 'cropped_image.jpg', { type: croppedBlob.type });\n onImageChange(newFile);\n setModalOpen(false);\n setImageSrc(null);\n setCroppedBlob(null);\n }\n };\n\n const handleModalCancel = () => {\n setModalOpen(false);\n setImageSrc(null);\n setCroppedBlob(null);\n };\n\n return (\n
      \n {previewUrl ? (\n
      \n \"Image\n setModalOpen(true)}\n onMouseEnter={() => setIsHovering(true)}\n onMouseLeave={() => setIsHovering(false)}\n style={{\n position: 'absolute',\n bottom: 10,\n right: 10,\n background: isHovering ? 'rgba(245, 208, 117, 0.7)' : 'rgba(128, 59, 10, 0.5)',\n width: 75,\n height: 75,\n borderRadius: '50%',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n cursor: 'pointer',\n transition: 'background 0.3s ease',\n }}\n >\n {isHovering && (\n \n )}\n \n
      \n
      \n ) : (\n // If no preview exists, display an inline dropzone.\n
      \n console.log('Rejected files:', files)}\n maxSize={5 * 1024 ** 2}\n accept={IMAGE_MIME_TYPE}\n styles={() => ({\n root: {\n backgroundColor: '#fcefe1',\n border: '3px dashed #f6b73c',\n },\n })}\n >\n \n \n \n \n \n \n \n \n \n \n
      \n \n Drag image here or click to select file\n \n \n Image must be under 5 MB\n \n
      \n
      \n \n
      \n )}\n\n \n {/* Show dropzone if no image has been dropped yet */}\n {!imageSrc ? (\n console.log('Rejected files:', files)}\n maxSize={5 * 1024 ** 2}\n accept={IMAGE_MIME_TYPE}\n mb=\"md\"\n styles={() => ({\n root: {\n backgroundColor: '#fcefe1',\n border: '3px dashed #f6b73c',\n },\n })}\n >\n \n \n \n \n \n \n \n \n \n \n
      \n \n Drag image here or click to select file\n \n \n Image must be under 5 MB\n \n
      \n
      \n \n ) : (\n // Show cropper once an image is selected\n \n )}\n\n \n \n \n \n
      \n \n );\n};\n\nexport default ImageUploadModal;\n","import React, { useState, useEffect } from 'react';\nimport { Head, usePage } from '@inertiajs/react';\nimport { useForm } from '@mantine/form';\nimport {\n Container,\n TextInput,\n Radio,\n RadioGroup,\n Textarea,\n Button,\n MantineProvider,\n createTheme,\n Box,\n Paper,\n Title,\n Accordion,\n Text,\n Group,\n} from '@mantine/core';\nimport { Notifications, showNotification } from '@mantine/notifications';\nimport { router } from '@inertiajs/react';\n\nimport { IconAlertCircle, IconCheck, IconLink } from '@tabler/icons-react';\nimport { RichTextEditor } from '@mantine/tiptap';\nimport { useEditor, EditorContent } from '@tiptap/react';\nimport Highlight from '@tiptap/extension-highlight';\nimport StarterKit from '@tiptap/starter-kit';\nimport Underline from '@tiptap/extension-underline';\nimport TextAlign from '@tiptap/extension-text-align';\nimport Heading from '@tiptap/extension-heading';\nimport Link from '@tiptap/extension-link';\nimport ImageUploadModal from '../../components/ImageUploadModal';\nimport { useUser, User } from '../../src/context/UserContext';\n\nimport '@mantine/core/styles.css';\nimport '@mantine/notifications/styles.css';\nimport '../../styles/Login-form.css';\nimport '@mantine/tiptap/styles.css';\n\ninterface EditArtistPageProps extends InertiaPageProps {\n artist: {\n id: number;\n name: string;\n slug: string;\n description?: string;\n website_url?: string;\n tiktok_url: string;\n instagram_url: string;\n youtube_url: string;\n spotify_url: string;\n facebook_url: string;\n soundcloud_url: string;\n mixcloud_url: string;\n dance_with_me: string;\n portal_password: string;\n short_bio: string;\n long_bio: string;\n promo_photos: string;\n promo_videos: string;\n traveler_info: string;\n preferred_airports: string;\n disliked_foods: string;\n favorite_foods: string;\n payment_methods: string;\n rates: string;\n accomodation_info: string;\n stripe_account_id: string;\n is_portal_enabled?: boolean;\n private_lessons_enabled?: boolean;\n instructor?: boolean;\n dj?: boolean;\n avatar?: File | null;\n avatar_url?: string | null;\n };\n errors?: Record;\n}\n\nconst theme = createTheme({\n primaryColor: 'orange',\n colors: {\n orange: [\n '#FEF5ED',\n '#FDE3D1',\n '#FCB693',\n '#FA9D73',\n '#F87F4D',\n '#F66A33',\n '#EA580C',\n '#C44B0A',\n '#9E3D08',\n '#783006',\n ],\n },\n fontFamily: 'Poppins, sans-serif',\n headings: { fontFamily: 'Poppins, sans-serif' },\n});\n\nexport default function EditArtist() {\n const { artist, errors } = usePage().props;\n console.log('Artist Data:', artist);\n const [seoImagePreview, setSeoImagePreview] = useState(artist.avatar_url);\n const { user, refreshUser } = useUser() as { user: User | null; refreshUser: () => Promise };\n\n const form = useForm({\n initialValues: {\n name: artist.name || '',\n slug: artist.slug || '',\n instructor: artist.instructor ? 'true' : 'false',\n is_portal_enabled: artist.is_portal_enabled ? 'true' : 'false',\n private_lessons_enabled: artist.private_lessons_enabled ? 'true' : 'false',\n dj: artist.dj ? 'true' : 'false',\n description: artist.description || '',\n website_url: artist.website_url,\n facebook_url: artist.facebook_url,\n instagram_url: artist.instagram_url,\n youtube_url: artist.youtube_url,\n tiktok_url: artist.tiktok_url,\n spotify_url: artist.spotify_url,\n soundcloud_url: artist.soundcloud_url,\n mixcloud_url: artist.mixcloud_url,\n dance_with_me: artist.dance_with_me,\n portal_password: artist.portal_password,\n short_bio: artist.short_bio,\n long_bio: artist.long_bio,\n promo_photos: artist.promo_photos,\n promo_videos: artist.promo_videos,\n traveler_info: artist.traveler_info,\n preferred_airports: artist.preferred_airports,\n disliked_foods: artist.disliked_foods,\n favorite_foods: artist.favorite_foods,\n payment_methods: artist.payment_methods,\n rates: artist.rates,\n accomodation_info: artist.accomodation_info,\n stripe_account_id: artist.stripe_account_id,\n avatar_url: artist.avatar_url,\n avatar: null as File | null,\n },\n });\n\n const handleImageChange = (file: File) => {\n // Update the form state with the new file\n form.setFieldValue('avatar', file);\n setSeoImagePreview(URL.createObjectURL(file));\n // Update the preview with a new URL\n console.log('Image changed - file stored in form:', file.name);\n };\n\n const [userRole, setUserRole] = useState(null);\n const is_superadmin = user?.roles?.includes('SuperAdmin') || false;\n\n const editor = useEditor({\n extensions: [\n StarterKit,\n Highlight,\n Underline,\n TextAlign.configure({ types: ['heading', 'paragraph'] }),\n Heading.configure({ levels: [1, 2, 3] }),\n Link.configure({ openOnClick: true }),\n ],\n content: artist.description,\n onUpdate: ({ editor }) => {\n form.setFieldValue('description', editor.getHTML());\n },\n });\n const [isLoading, setIsLoading] = useState(false);\n\n const handleSubmit = async (values: typeof form.values) => {\n console.log('📍 Submitting form with values:', values);\n setIsLoading(true);\n const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content;\n\n console.log('🔐 CSRF Token:', csrfToken);\n\n try {\n const formData = new FormData();\n\n // Add all basic artist fields\n formData.append('artist[name]', values.name);\n formData.append('artist[slug]', values.slug);\n formData.append('artist[description]', values.description);\n formData.append('artist[instructor]', values.instructor);\n formData.append('artist[dj]', values.dj);\n formData.append('artist[is_portal_enabled]', values.is_portal_enabled);\n formData.append('artist[private_lessons_enabled]', values.private_lessons_enabled);\n\n // Add all URL fields\n formData.append('artist[website_url]', values.website_url || '');\n formData.append('artist[facebook_url]', values.facebook_url || '');\n formData.append('artist[instagram_url]', values.instagram_url || '');\n formData.append('artist[youtube_url]', values.youtube_url || '');\n formData.append('artist[tiktok_url]', values.tiktok_url || '');\n formData.append('artist[spotify_url]', values.spotify_url || '');\n formData.append('artist[soundcloud_url]', values.soundcloud_url || '');\n formData.append('artist[mixcloud_url]', values.mixcloud_url || '');\n formData.append('artist[dance_with_me]', values.dance_with_me || '');\n\n // Add portal fields\n if (is_superadmin) {\n formData.append('artist[portal_password]', values.portal_password || '');\n formData.append('artist[short_bio]', values.short_bio || '');\n formData.append('artist[long_bio]', values.long_bio || '');\n formData.append('artist[promo_photos]', values.promo_photos || '');\n formData.append('artist[promo_videos]', values.promo_videos || '');\n formData.append('artist[traveler_info]', values.traveler_info || '');\n formData.append('artist[preferred_airports]', values.preferred_airports || '');\n formData.append('artist[disliked_foods]', values.disliked_foods || '');\n formData.append('artist[favorite_foods]', values.favorite_foods || '');\n formData.append('artist[payment_methods]', values.payment_methods || '');\n formData.append('artist[rates]', values.rates || '');\n formData.append('artist[accomodation_info]', values.accomodation_info || '');\n formData.append('artist[stripe_account_id]', values.stripe_account_id || '');\n }\n\n console.log('Form state for debugging:', form.values); // Check what's in the form\n\n // You should store the actual File object in your state\n // when handleImageChange is called\n const avatarFile: any = form.values.avatar; // This should be the File object\n\n if (avatarFile instanceof File) {\n console.log('✅ Found avatar File object:', avatarFile.name, avatarFile.size);\n formData.append('artist[avatar]', avatarFile);\n } else {\n console.log('❌ No valid avatar File object found in form state');\n }\n // Send PUT request with CSRF token\n const response = await fetch(`/artists/${artist.slug}`, {\n method: 'PUT',\n headers: {\n Accept: 'application/json',\n 'X-CSRF-Token': csrfToken || '',\n },\n credentials: 'include',\n body: formData,\n });\n\n if (response.ok) {\n showNotification({\n color: 'green',\n title: 'Update Successful',\n position: 'top-right',\n message: 'Artist was successfully updated!',\n icon: ,\n autoClose: 6000,\n });\n\n // Redirect to the updated artist page after success\n setTimeout(() => {\n window.location.href = `/artists/${values.slug}`;\n }, 1500);\n } else {\n const data = await response.json().catch(() => ({}));\n showNotification({\n color: 'red',\n title: 'Update Failed',\n position: 'top-right',\n message: data.error || 'Something went wrong!',\n icon: ,\n autoClose: 5000,\n });\n\n // Show validation errors if available\n if (data.errors) {\n form.setErrors(data.errors);\n }\n }\n } catch (error) {\n showNotification({\n color: 'red',\n title: 'Error',\n position: 'top-right',\n message: 'An unexpected error occurred',\n icon: ,\n autoClose: 5000,\n });\n console.error('Error updating artist:', error);\n } finally {\n setIsLoading(false);\n }\n };\n\n return (\n \n \n \n \n \n Edit Artist: {artist.name}\n \n
      \n \n\n \n\n \n\n \n Artist Description\n \n {editor && (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n )}\n\n \n \n \n \n\n \n \n \n \n\n \n \n \n \n\n \n \n \n \n\n \n \n \n \n \n Links\n \n \n \n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n \n \n \n\n \n \n
      \n
      \n
      \n );\n}\n","// FormLayout.tsx\nimport React from 'react';\nimport { MantineProvider, Container, Paper, Title, Box, createTheme } from '@mantine/core';\nimport { Notifications } from '@mantine/notifications';\n\ninterface FormLayoutProps {\n title?: string;\n children: React.ReactNode;\n}\n\n// Define your Mantine theme\nconst theme = createTheme({\n primaryColor: 'orange',\n colors: {\n orange: [\n '#FEF5ED',\n '#FDE3D1',\n '#FCB693',\n '#FA9D73',\n '#F87F4D',\n '#F66A33',\n '#EA580C',\n '#C44B0A',\n '#9E3D08',\n '#783006',\n ],\n },\n fontFamily: 'Poppins, sans-serif',\n headings: {\n fontFamily: 'Poppins, sans-serif',\n },\n components: {\n TextInput: {\n styles: () => ({\n input: {\n fontSize: 16,\n },\n }),\n },\n },\n});\n\nexport default function FormLayout({ title, children }: FormLayoutProps) {\n return (\n \n \n \n ({\n width: '100%',\n maxWidth: '400px',\n margin: '0 auto',\n marginTop: '40px',\n [(theme as any).fn.smallerThan('sm')]: {\n padding: '20px',\n marginTop: '20px',\n },\n })}\n >\n {title && {title}}\n {children}\n \n \n \n );\n}\n","// app/javascript/Pages/DanceStyles/EditDanceStyle.tsx\n\nimport React, { useState } from 'react';\nimport { useForm } from '@mantine/form';\nimport { Inertia } from '@inertiajs/inertia';\nimport { usePage } from '@inertiajs/react';\nimport { TextInput, Textarea, Button, Box, Image, Text, Group, Modal } from '@mantine/core';\nimport { IconCheck, IconAlertCircle, IconUpload, IconPhoto, IconX } from '@tabler/icons-react';\nimport FormLayout from '../../components/FormLayout';\nimport { Notifications, showNotification } from '@mantine/notifications';\nimport ImageUploadModal from '../../components/ImageUploadModal';\nimport '@mantine/core/styles.css';\nimport '@mantine/notifications/styles.css';\n\ninterface DanceStyleData {\n id: number;\n name?: string;\n slug?: string;\n seo_image_url?: string | null;\n seo_image?: File | null;\n}\n\ninterface EditDanceStyleProps extends InertiaPageProps {\n dance_style: DanceStyleData;\n errors?: string[];\n}\n\nfunction slugify(str: string): string {\n return str\n .toLowerCase()\n .trim()\n .replace(/\\s+/g, '-') // replace whitespace with dashes\n .replace(/[^\\w-]+/g, ''); // remove non-word chars\n}\n\nexport default function EditDanceStyle() {\n const { dance_style, errors } = usePage().props;\n const [values, setValues] = useState(dance_style);\n\n const [modalOpen, setModalOpen] = useState(false);\n\n console.log('Seo Image URL:', dance_style.seo_image_url);\n\n const [isLoading, setIsLoading] = useState(false);\n\n // If you want to handle new image + crop:\n\n const [seoImagePreview, setSeoImagePreview] = useState(dance_style.seo_image_url);\n const [isHovering, setIsHovering] = useState(false);\n\n const handleImageChange = (file: File) => {\n console.log('📸 Image selected:', file);\n\n setValues((prevValues) => {\n const newValues = { ...prevValues, seo_image: file };\n console.log('🆕 Updated state:', newValues); // 🔍 Debugging new state\n return newValues;\n });\n\n setSeoImagePreview(URL.createObjectURL(file));\n };\n\n // Mantine form with existing values:\n const form = useForm({\n initialValues: {\n name: dance_style.name || '',\n slug: dance_style.slug || '',\n },\n validate: {\n name: (value) => (value ? null : 'Name is required'),\n },\n });\n\n // Auto-generate slug if name changes\n const handleNameChange = (e: React.ChangeEvent) => {\n const newName = e.target.value;\n form.setFieldValue('name', newName);\n form.setFieldValue('slug', slugify(newName));\n };\n\n // Form submit\n const handleSubmit = async (values: typeof form.values) => {\n console.log('📍 Submitting form with values:', values);\n setIsLoading(true);\n const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content;\n\n try {\n const formData = new FormData();\n formData.append('dance_style[name]', values.name);\n formData.append('dance_style[slug]', values.slug);\n\n if (values.seo_image instanceof File) {\n formData.append('dance_style[seo_image]', values.seo_image);\n } else {\n console.log('😬 No image file detected'); // Debugging\n }\n\n // ✅ Send PUT request with CSRF token\n const response = await fetch(`/dance_styles/${values.slug}`, {\n method: 'PUT',\n headers: {\n Accept: 'application/json',\n 'X-CSRF-Token': csrfToken || '',\n },\n credentials: 'include',\n body: formData,\n });\n\n if (response.ok) {\n showNotification({\n color: 'green',\n title: 'Update Successful',\n position: 'top-right',\n message: 'Dance style was successfully updated!',\n icon: ,\n autoClose: 6000,\n });\n\n // ✅ Redirect to the updated dance style page after success\n setTimeout(() => {\n window.location.href = `/dance_styles/${values.slug}`;\n }, 1500);\n } else {\n const data = await response.json().catch(() => ({}));\n showNotification({\n color: 'red',\n title: 'Update Failed',\n position: 'top-right',\n message: data.error || 'Something went wrong!',\n icon: ,\n autoClose: 5000,\n });\n\n // Show validation errors if available\n if (data.errors) {\n form.setErrors(data.errors);\n }\n }\n } catch (error) {\n showNotification({\n color: 'red',\n title: 'Error',\n position: 'top-right',\n message: 'An unexpected error occurred',\n icon: ,\n autoClose: 5000,\n });\n console.error('Error updating dance style:', error);\n } finally {\n setIsLoading(false);\n }\n };\n\n return (\n \n
      handleSubmit({ ...form.values, seo_image: values.seo_image }))}>\n {/* If there's an image preview, show it with an overlay icon to trigger the modal.\n Otherwise, if no image exists, show the dropzone directly in the main form. */}\n \n\n setValues({ ...values, name: e.target.value })}\n mt=\"md\"\n required\n />\n form.setFieldValue('slug', e.target.value)}\n mt=\"md\"\n />\n\n {/* Server-side errors */}\n {errors && errors.length > 0 && (\n \n {errors.map((err, i) => (\n
      {err}
      \n ))}\n
      \n )}\n\n \n \n
      \n );\n}\n","// app/frontend/Pages/DanceStyles/NewDanceStyle.tsx\n\nimport React, { useState } from 'react';\nimport { useForm } from '@mantine/form';\nimport { Inertia } from '@inertiajs/inertia';\nimport { usePage } from '@inertiajs/react';\nimport { IconUpload, IconPhoto, IconX } from '@tabler/icons-react';\nimport { TextInput, Button, Box, Text, Group } from '@mantine/core';\nimport { Dropzone, IMAGE_MIME_TYPE } from '@mantine/dropzone';\nimport FormLayout from '../../components/FormLayout';\nimport ImageCropper from '../../components/ImageCropper';\n\nimport '@mantine/dropzone/styles.css';\nimport 'cropperjs/dist/cropper.css';\n\n// Define the shape of the props (optional but recommended if using TypeScript)\ninterface DanceStyleProps {\n dance_style?: {\n name?: string;\n slug?: string;\n };\n errors?: string[]; // or a more structured type\n}\n\nfunction slugify(str: string): string {\n return str\n .toLowerCase()\n .trim()\n .replace(/\\s+/g, '-') // replace whitespace with dashes\n .replace(/[^\\w-]+/g, ''); // remove non-word chars if you want\n}\n\nexport default function NewDanceStyle() {\n const { dance_style, errors } = usePage>().props;\n\n // State for storing the selected file as Base64 (for cropping)\n const [imageSrc, setImageSrc] = useState(null);\n const [croppedBlob, setCroppedBlob] = useState(null);\n\n // Mantine form setup\n const form = useForm({\n initialValues: {\n name: dance_style?.name || '',\n slug: '',\n },\n validate: {\n name: (value) => (value ? null : 'Name is required'),\n },\n validateInputOnBlur: true,\n });\n\n // Auto-generate slug from \"name\"\n const handleNameChange = (event: React.ChangeEvent) => {\n const newName = event.target.value;\n form.setFieldValue('name', newName);\n form.setFieldValue('slug', slugify(newName));\n };\n\n // Called when user drops an image in the Dropzone\n const handleDrop = (files: File[]) => {\n if (files && files.length > 0) {\n const file = files[0];\n const reader = new FileReader();\n reader.onload = (e) => {\n if (typeof e.target?.result === 'string') {\n setImageSrc(e.target.result);\n }\n };\n reader.readAsDataURL(file);\n }\n };\n\n // Called when the image is cropped\n function handleCropped(blob: Blob) {\n console.log('Cropped blob:', blob);\n setCroppedBlob(blob);\n }\n\n // Form submit handler\n function handleSubmit(values: typeof form.values) {\n const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content;\n const data = new FormData();\n data.append('dance_style[name]', values.name);\n data.append('dance_style[slug]', values.slug || '');\n\n console.log('Cropped blob: ', croppedBlob);\n if (croppedBlob) {\n data.append('dance_style[seo_image]', croppedBlob, 'dance_style.jpg');\n }\n\n Inertia.post('/dance_styles', data, {\n headers: {\n 'X-CSRF-Token': csrfToken || '',\n },\n onError: (err) => {\n console.error('Error creating dance style:', err);\n },\n });\n }\n\n return (\n \n
      \n {/* Dropzone - call handleDrop to actually set the base64 preview */}\n console.log('rejected files', files)}\n maxSize={5 * 1024 ** 2}\n accept={IMAGE_MIME_TYPE}\n className=\"mb-4\"\n styles={() => ({\n root: {\n backgroundColor: '#fcefe1',\n border: '3px dashed #f6b73c',\n },\n })}\n >\n \n \n \n \n \n \n \n \n \n \n
      \n \n Drag image here or click to select file\n \n \n Image must be under 5 MB\n \n
      \n
      \n \n\n {/* If we have a selected image, show the cropper */}\n {imageSrc && }\n\n \n\n form.setFieldValue('slug', e.target.value)}\n className=\"text-muted\"\n />\n\n \n \n
      \n );\n}\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){\"use strict\";var t=1e3,e=6e4,n=36e5,r=\"millisecond\",i=\"second\",s=\"minute\",u=\"hour\",a=\"day\",o=\"week\",c=\"month\",f=\"quarter\",h=\"year\",d=\"date\",l=\"Invalid Date\",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(t){var e=[\"th\",\"st\",\"nd\",\"rd\"],n=t%100;return\"[\"+t+(e[(n-20)%10]||e[n]||e[0])+\"]\"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t) dayjs(value).locale(locale).format(format);\n if (type === \"default\") {\n return date === null ? \"\" : formatDate(date);\n }\n if (type === \"multiple\") {\n return date.map(formatDate).join(\", \");\n }\n if (type === \"range\" && Array.isArray(date)) {\n if (date[0] && date[1]) {\n return `${formatDate(date[0])} ${labelSeparator} ${formatDate(date[1])}`;\n }\n if (date[0]) {\n return `${formatDate(date[0])} ${labelSeparator} `;\n }\n return \"\";\n }\n return \"\";\n}\nfunction getFormattedDate({ formatter, ...others }) {\n return (formatter || defaultDateFormatter)(others);\n}\n\nexport { defaultDateFormatter, getFormattedDate };\n//# sourceMappingURL=get-formatted-date.mjs.map\n","'use client';\nfunction getNextIndex({ direction, levelIndex, rowIndex, cellIndex, size }) {\n switch (direction) {\n case \"up\":\n if (levelIndex === 0 && rowIndex === 0) {\n return null;\n }\n if (rowIndex === 0) {\n return {\n levelIndex: levelIndex - 1,\n rowIndex: cellIndex <= size[levelIndex - 1][size[levelIndex - 1].length - 1] - 1 ? size[levelIndex - 1].length - 1 : size[levelIndex - 1].length - 2,\n cellIndex\n };\n }\n return {\n levelIndex,\n rowIndex: rowIndex - 1,\n cellIndex\n };\n case \"down\":\n if (rowIndex === size[levelIndex].length - 1) {\n return {\n levelIndex: levelIndex + 1,\n rowIndex: 0,\n cellIndex\n };\n }\n if (rowIndex === size[levelIndex].length - 2 && cellIndex >= size[levelIndex][size[levelIndex].length - 1]) {\n return {\n levelIndex: levelIndex + 1,\n rowIndex: 0,\n cellIndex\n };\n }\n return {\n levelIndex,\n rowIndex: rowIndex + 1,\n cellIndex\n };\n case \"left\":\n if (levelIndex === 0 && rowIndex === 0 && cellIndex === 0) {\n return null;\n }\n if (rowIndex === 0 && cellIndex === 0) {\n return {\n levelIndex: levelIndex - 1,\n rowIndex: size[levelIndex - 1].length - 1,\n cellIndex: size[levelIndex - 1][size[levelIndex - 1].length - 1] - 1\n };\n }\n if (cellIndex === 0) {\n return {\n levelIndex,\n rowIndex: rowIndex - 1,\n cellIndex: size[levelIndex][rowIndex - 1] - 1\n };\n }\n return {\n levelIndex,\n rowIndex,\n cellIndex: cellIndex - 1\n };\n case \"right\":\n if (rowIndex === size[levelIndex].length - 1 && cellIndex === size[levelIndex][rowIndex] - 1) {\n return {\n levelIndex: levelIndex + 1,\n rowIndex: 0,\n cellIndex: 0\n };\n }\n if (cellIndex === size[levelIndex][rowIndex] - 1) {\n return {\n levelIndex,\n rowIndex: rowIndex + 1,\n cellIndex: 0\n };\n }\n return {\n levelIndex,\n rowIndex,\n cellIndex: cellIndex + 1\n };\n default:\n return { levelIndex, rowIndex, cellIndex };\n }\n}\nfunction focusOnNextFocusableControl({\n controlsRef,\n direction,\n levelIndex,\n rowIndex,\n cellIndex,\n size\n}) {\n const nextIndex = getNextIndex({ direction, size, rowIndex, cellIndex, levelIndex });\n if (!nextIndex) {\n return;\n }\n const controlToFocus = controlsRef.current?.[nextIndex.levelIndex]?.[nextIndex.rowIndex]?.[nextIndex.cellIndex];\n if (!controlToFocus) {\n return;\n }\n if (controlToFocus.disabled || controlToFocus.getAttribute(\"data-hidden\") || controlToFocus.getAttribute(\"data-outside\")) {\n focusOnNextFocusableControl({\n controlsRef,\n direction,\n levelIndex: nextIndex.levelIndex,\n cellIndex: nextIndex.cellIndex,\n rowIndex: nextIndex.rowIndex,\n size\n });\n } else {\n controlToFocus.focus();\n }\n}\nfunction getDirection(key) {\n switch (key) {\n case \"ArrowDown\":\n return \"down\";\n case \"ArrowUp\":\n return \"up\";\n case \"ArrowRight\":\n return \"right\";\n case \"ArrowLeft\":\n return \"left\";\n default:\n return null;\n }\n}\nfunction getControlsSize(controlsRef) {\n return controlsRef.current?.map((column) => column.map((row) => row.length));\n}\nfunction handleControlKeyDown({\n controlsRef,\n levelIndex,\n rowIndex,\n cellIndex,\n event\n}) {\n const direction = getDirection(event.key);\n if (direction) {\n event.preventDefault();\n const size = getControlsSize(controlsRef);\n focusOnNextFocusableControl({\n controlsRef,\n direction,\n levelIndex,\n rowIndex,\n cellIndex,\n size\n });\n }\n}\n\nexport { handleControlKeyDown };\n//# sourceMappingURL=handle-control-key-down.mjs.map\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_timezone=e()}(this,(function(){\"use strict\";var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,o){var r,a=function(t,n,i){void 0===i&&(i={});var o=new Date(t),r=function(t,n){void 0===n&&(n={});var i=n.timeZoneName||\"short\",o=t+\"|\"+i,r=e[o];return r||(r=new Intl.DateTimeFormat(\"en-US\",{hour12:!1,timeZone:t,year:\"numeric\",month:\"2-digit\",day:\"2-digit\",hour:\"2-digit\",minute:\"2-digit\",second:\"2-digit\",timeZoneName:i}),e[o]=r),r}(n,i);return r.formatToParts(o)},u=function(e,n){for(var i=a(e,n),r=[],u=0;u=0&&(r[c]=parseInt(m,10))}var d=r[3],l=24===d?0:d,h=r[0]+\"-\"+r[1]+\"-\"+r[2]+\" \"+l+\":\"+r[4]+\":\"+r[5]+\":000\",v=+e;return(o.utc(h).valueOf()-(v-=v%1e3))/6e4},f=i.prototype;f.tz=function(t,e){void 0===t&&(t=r);var n,i=this.utcOffset(),a=this.toDate(),u=a.toLocaleString(\"en-US\",{timeZone:t}),f=Math.round((a-new Date(u))/1e3/60),s=15*-Math.round(a.getTimezoneOffset()/15)-f;if(!Number(s))n=this.utcOffset(0,e);else if(n=o(u,{locale:this.$L}).$set(\"millisecond\",this.$ms).utcOffset(s,!0),e){var m=n.utcOffset();n=n.add(i-m,\"minute\")}return n.$x.$timezone=t,n},f.offsetName=function(t){var e=this.$x.$timezone||o.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find((function(t){return\"timezonename\"===t.type.toLowerCase()}));return n&&n.value};var s=f.startOf;f.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return s.call(this,t,e);var n=o(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\"),{locale:this.$L});return s.call(n,t,e).tz(this.$x.$timezone,!0)},o.tz=function(t,e,n){var i=n&&e,a=n||e||r,f=u(+o(),a);if(\"string\"!=typeof t)return o(t).tz(a);var s=function(t,e,n){var i=t-60*e*1e3,o=u(i,n);if(e===o)return[i,e];var r=u(i-=60*(o-e)*1e3,n);return o===r?[i,o]:[t-60*Math.min(o,r)*1e3,Math.max(o,r)]}(o.utc(t,i).valueOf(),f,a),m=s[0],c=s[1],d=o(m).utcOffset(c);return d.$x.$timezone=a,d},o.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},o.tz.setDefault=function(t){r=t}}}));","!function(t,i){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=i():\"function\"==typeof define&&define.amd?define(i):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_utc=i()}(this,(function(){\"use strict\";var t=\"minute\",i=/[+-]\\d\\d(?::?\\d\\d)?/g,e=/([+-]|\\d\\d)/g;return function(s,f,n){var u=f.prototype;n.utc=function(t){var i={date:t,utc:!0,args:arguments};return new f(i)},u.utc=function(i){var e=n(this.toDate(),{locale:this.$L,utc:!0});return i?e.add(this.utcOffset(),t):e},u.local=function(){return n(this.toDate(),{locale:this.$L,utc:!1})};var o=u.parse;u.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),o.call(this,t)};var r=u.init;u.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else r.call(this)};var a=u.utcOffset;u.utcOffset=function(s,f){var n=this.$utils().u;if(n(s))return this.$u?0:n(this.$offset)?a.call(this):this.$offset;if(\"string\"==typeof s&&(s=function(t){void 0===t&&(t=\"\");var s=t.match(i);if(!s)return null;var f=(\"\"+s[0]).match(e)||[\"-\",0,0],n=f[0],u=60*+f[1]+ +f[2];return 0===u?0:\"+\"===n?u:-u}(s),null===s))return this;var u=Math.abs(s)<=16?60*s:s,o=this;if(f)return o.$offset=u,o.$u=0===s,o;if(0!==s){var r=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(o=this.local().add(u+r,t)).$offset=u,o.$x.$localOffset=r}else o=this.utc();return o};var h=u.format;u.format=function(t){var i=t||(this.$u?\"YYYY-MM-DDTHH:mm:ss[Z]\":\"\");return h.call(this,i)},u.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},u.isUTC=function(){return!!this.$u},u.toISOString=function(){return this.toDate().toISOString()},u.toString=function(){return this.toDate().toUTCString()};var l=u.toDate;u.toDate=function(t){return\"s\"===t&&this.$offset?n(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\")).toDate():l.call(this)};var c=u.diff;u.diff=function(t,i,e){if(t&&this.$u===t.$u)return c.call(this,t,i,e);var s=this.local(),f=n(t).local();return c.call(s,f,i,e)}}}));","'use client';\nimport dayjs from 'dayjs';\nimport timezonePlugin from 'dayjs/plugin/timezone.js';\nimport utcPlugin from 'dayjs/plugin/utc.js';\n\ndayjs.extend(utcPlugin);\ndayjs.extend(timezonePlugin);\nfunction getTimezoneOffset(date, timezone) {\n if (timezone) {\n return dayjs(date).tz(timezone).utcOffset() + date.getTimezoneOffset();\n }\n return 0;\n}\n\nexport { getTimezoneOffset };\n//# sourceMappingURL=get-timezone-offset.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\nimport { getTimezoneOffset } from './get-timezone-offset.mjs';\n\nconst updateTimezone = (date, timezone, direction) => {\n if (!date) {\n return null;\n }\n if (!timezone) {\n return date;\n }\n let offset = getTimezoneOffset(date, timezone);\n if (direction === \"remove\") {\n offset *= -1;\n }\n return dayjs(date).add(offset, \"minutes\").toDate();\n};\nfunction shiftTimezone(direction, date, timezone, disabled) {\n if (disabled || !date) {\n return date;\n }\n if (Array.isArray(date)) {\n return date.map((d) => updateTimezone(d, timezone, direction));\n }\n return updateTimezone(date, timezone, direction);\n}\n\nexport { shiftTimezone };\n//# sourceMappingURL=shift-timezone.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\nimport { shiftTimezone } from './shift-timezone.mjs';\n\nfunction getDefaultClampedDate({ minDate, maxDate, timezone }) {\n const today = shiftTimezone(\"add\", /* @__PURE__ */ new Date(), timezone);\n if (!minDate && !maxDate) {\n return today;\n }\n if (minDate && dayjs(today).isBefore(minDate)) {\n return minDate;\n }\n if (maxDate && dayjs(today).isAfter(maxDate)) {\n return maxDate;\n }\n return today;\n}\n\nexport { getDefaultClampedDate };\n//# sourceMappingURL=get-default-clamped-date.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { createContext } from 'react';\n\nconst DATES_PROVIDER_DEFAULT_SETTINGS = {\n locale: \"en\",\n timezone: null,\n firstDayOfWeek: 1,\n weekendDays: [0, 6],\n labelSeparator: \"\\u2013\",\n consistentWeeks: false\n};\nconst DatesProviderContext = createContext(DATES_PROVIDER_DEFAULT_SETTINGS);\nfunction DatesProvider({ settings, children }) {\n return /* @__PURE__ */ jsx(DatesProviderContext.Provider, { value: { ...DATES_PROVIDER_DEFAULT_SETTINGS, ...settings }, children });\n}\n\nexport { DATES_PROVIDER_DEFAULT_SETTINGS, DatesProvider, DatesProviderContext };\n//# sourceMappingURL=DatesProvider.mjs.map\n","'use client';\nimport { useContext, useCallback } from 'react';\nimport { DatesProviderContext } from './DatesProvider.mjs';\n\nfunction useDatesContext() {\n const ctx = useContext(DatesProviderContext);\n const getLocale = useCallback((input) => input || ctx.locale, [ctx.locale]);\n const getTimezone = useCallback(\n (input) => input || ctx.timezone || void 0,\n [ctx.timezone]\n );\n const getFirstDayOfWeek = useCallback(\n (input) => typeof input === \"number\" ? input : ctx.firstDayOfWeek,\n [ctx.firstDayOfWeek]\n );\n const getWeekendDays = useCallback(\n (input) => Array.isArray(input) ? input : ctx.weekendDays,\n [ctx.weekendDays]\n );\n const getLabelSeparator = useCallback(\n (input) => typeof input === \"string\" ? input : ctx.labelSeparator,\n [ctx.labelSeparator]\n );\n return {\n ...ctx,\n getLocale,\n getTimezone,\n getFirstDayOfWeek,\n getWeekendDays,\n getLabelSeparator\n };\n}\n\nexport { useDatesContext };\n//# sourceMappingURL=use-dates-context.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport 'dayjs';\nimport { shiftTimezone } from '../../utils/shift-timezone.mjs';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\n\nfunction formatValue(value, type) {\n const ctx = useDatesContext();\n const formatDateWithTimezone = (date) => {\n return shiftTimezone(\"remove\", date, ctx.getTimezone()).toISOString();\n };\n if (type === \"range\" && Array.isArray(value)) {\n const [startDate, endDate] = value;\n if (!startDate) {\n return \"\";\n }\n if (!endDate) {\n return `${formatDateWithTimezone(startDate)} \\u2013`;\n }\n return `${formatDateWithTimezone(startDate)} \\u2013 ${formatDateWithTimezone(endDate)}`;\n }\n if (type === \"multiple\" && Array.isArray(value)) {\n return value.map((date) => date && formatDateWithTimezone(date)).filter(Boolean).join(\", \");\n }\n if (!Array.isArray(value) && value) {\n return formatDateWithTimezone(value);\n }\n return \"\";\n}\nfunction HiddenDatesInput({ value, type, name, form }) {\n return /* @__PURE__ */ jsx(\"input\", { type: \"hidden\", value: formatValue(value, type), name, form });\n}\nHiddenDatesInput.displayName = \"@mantine/dates/HiddenDatesInput\";\n\nexport { HiddenDatesInput };\n//# sourceMappingURL=HiddenDatesInput.mjs.map\n","'use client';\nvar classes = {\"input\":\"m_468e7eda\"};\n\nexport { classes as default };\n//# sourceMappingURL=TimeInput.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport cx from 'clsx';\nimport { factory, useProps, useResolvedStylesApi, InputBase } from '@mantine/core';\nimport classes from './TimeInput.module.css.mjs';\n\nconst defaultProps = {};\nconst TimeInput = factory((_props, ref) => {\n const props = useProps(\"TimeInput\", defaultProps, _props);\n const {\n classNames,\n styles,\n unstyled,\n vars,\n withSeconds,\n minTime,\n maxTime,\n value,\n onChange,\n ...others\n } = props;\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n const checkIfTimeLimitExceeded = (val) => {\n if (minTime !== void 0 || maxTime !== void 0) {\n const [hours, minutes, seconds] = val.split(\":\").map(Number);\n if (minTime) {\n const [minHours, minMinutes, minSeconds] = minTime.split(\":\").map(Number);\n if (hours < minHours || hours === minHours && minutes < minMinutes || withSeconds && hours === minHours && minutes === minMinutes && seconds < minSeconds) {\n return -1;\n }\n }\n if (maxTime) {\n const [maxHours, maxMinutes, maxSeconds] = maxTime.split(\":\").map(Number);\n if (hours > maxHours || hours === maxHours && minutes > maxMinutes || withSeconds && hours === maxHours && minutes === maxMinutes && seconds > maxSeconds) {\n return 1;\n }\n }\n }\n return 0;\n };\n const onTimeBlur = (event) => {\n props.onBlur?.(event);\n if (minTime !== void 0 || maxTime !== void 0) {\n const val = event.currentTarget.value;\n if (val) {\n const check = checkIfTimeLimitExceeded(val);\n if (check === 1) {\n event.currentTarget.value = maxTime;\n props.onChange?.(event);\n } else if (check === -1) {\n event.currentTarget.value = minTime;\n props.onChange?.(event);\n }\n }\n }\n };\n return /* @__PURE__ */ jsx(\n InputBase,\n {\n classNames: { ...resolvedClassNames, input: cx(classes.input, resolvedClassNames?.input) },\n styles: resolvedStyles,\n unstyled,\n ref,\n value,\n ...others,\n step: withSeconds ? 1 : 60,\n onChange,\n onBlur: onTimeBlur,\n type: \"time\",\n __staticSelector: \"TimeInput\"\n }\n );\n});\nTimeInput.classes = InputBase.classes;\nTimeInput.displayName = \"@mantine/dates/TimeInput\";\n\nexport { TimeInput };\n//# sourceMappingURL=TimeInput.mjs.map\n","'use client';\nvar classes = {\"day\":\"m_396ce5cb\"};\n\nexport { classes as default };\n//# sourceMappingURL=Day.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { createVarsResolver, getSize, factory, useProps, useStyles, UnstyledButton } from '@mantine/core';\nimport { shiftTimezone } from '../../utils/shift-timezone.mjs';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport classes from './Day.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver((_, { size }) => ({\n day: {\n \"--day-size\": getSize(size, \"day-size\")\n }\n}));\nconst Day = factory((_props, ref) => {\n const props = useProps(\"Day\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n date,\n disabled,\n __staticSelector,\n weekend,\n outside,\n selected,\n renderDay,\n inRange,\n firstInRange,\n lastInRange,\n hidden,\n static: isStatic,\n highlightToday,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector || \"Day\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver,\n rootSelector: \"day\"\n });\n const ctx = useDatesContext();\n return /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ...getStyles(\"day\", { style: hidden ? { display: \"none\" } : void 0 }),\n component: isStatic ? \"div\" : \"button\",\n ref,\n disabled,\n \"data-today\": dayjs(date).isSame(shiftTimezone(\"add\", /* @__PURE__ */ new Date(), ctx.getTimezone()), \"day\") || void 0,\n \"data-hidden\": hidden || void 0,\n \"data-highlight-today\": highlightToday || void 0,\n \"data-disabled\": disabled || void 0,\n \"data-weekend\": !disabled && !outside && weekend || void 0,\n \"data-outside\": !disabled && outside || void 0,\n \"data-selected\": !disabled && selected || void 0,\n \"data-in-range\": inRange && !disabled || void 0,\n \"data-first-in-range\": firstInRange && !disabled || void 0,\n \"data-last-in-range\": lastInRange && !disabled || void 0,\n \"data-static\": isStatic || void 0,\n unstyled,\n ...others,\n children: renderDay?.(date) || dayjs(date).date()\n }\n );\n});\nDay.classes = classes;\nDay.displayName = \"@mantine/dates/Day\";\n\nexport { Day };\n//# sourceMappingURL=Day.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction getWeekdayNames({\n locale,\n format = \"dd\",\n firstDayOfWeek = 1\n}) {\n const baseDate = dayjs().day(firstDayOfWeek);\n const labels = [];\n for (let i = 0; i < 7; i += 1) {\n if (typeof format === \"string\") {\n labels.push(dayjs(baseDate).add(i, \"days\").locale(locale).format(format));\n } else {\n labels.push(format(dayjs(baseDate).add(i, \"days\").toDate()));\n }\n }\n return labels;\n}\n\nexport { getWeekdayNames };\n//# sourceMappingURL=get-weekdays-names.mjs.map\n","'use client';\nvar classes = {\"weekday\":\"m_18a3eca\"};\n\nexport { classes as default };\n//# sourceMappingURL=WeekdaysRow.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { createVarsResolver, getFontSize, getSpacing, factory, useProps, useStyles, Box } from '@mantine/core';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { getWeekdayNames } from './get-weekdays-names/get-weekdays-names.mjs';\nimport classes from './WeekdaysRow.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver((_, { size }) => ({\n weekdaysRow: {\n \"--wr-fz\": getFontSize(size),\n \"--wr-spacing\": getSpacing(size)\n }\n}));\nconst WeekdaysRow = factory((_props, ref) => {\n const props = useProps(\"WeekdaysRow\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n locale,\n firstDayOfWeek,\n weekdayFormat,\n cellComponent: CellComponent = \"th\",\n __staticSelector,\n withWeekNumbers,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector || \"WeekdaysRow\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver,\n rootSelector: \"weekdaysRow\"\n });\n const ctx = useDatesContext();\n const weekdays = getWeekdayNames({\n locale: ctx.getLocale(locale),\n format: weekdayFormat,\n firstDayOfWeek: ctx.getFirstDayOfWeek(firstDayOfWeek)\n }).map((weekday, index) => /* @__PURE__ */ jsx(CellComponent, { ...getStyles(\"weekday\"), children: weekday }, index));\n return /* @__PURE__ */ jsxs(Box, { component: \"tr\", ref, ...getStyles(\"weekdaysRow\"), ...others, children: [\n withWeekNumbers && /* @__PURE__ */ jsx(CellComponent, { ...getStyles(\"weekday\"), children: \"#\" }),\n weekdays\n ] });\n});\nWeekdaysRow.classes = classes;\nWeekdaysRow.displayName = \"@mantine/dates/WeekdaysRow\";\n\nexport { WeekdaysRow };\n//# sourceMappingURL=WeekdaysRow.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction getEndOfWeek(date, firstDayOfWeek = 1) {\n let value = dayjs(date);\n const lastDayOfWeek = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1;\n while (value.day() !== lastDayOfWeek) {\n value = value.add(1, \"day\");\n }\n return value.toDate();\n}\n\nexport { getEndOfWeek };\n//# sourceMappingURL=get-end-of-week.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction getStartOfWeek(date, firstDayOfWeek = 1) {\n let value = dayjs(date);\n while (value.day() !== firstDayOfWeek) {\n value = value.subtract(1, \"day\");\n }\n return value.toDate();\n}\n\nexport { getStartOfWeek };\n//# sourceMappingURL=get-start-of-week.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\nimport { getEndOfWeek } from '../get-end-of-week/get-end-of-week.mjs';\nimport { getStartOfWeek } from '../get-start-of-week/get-start-of-week.mjs';\n\nfunction getMonthDays({\n month,\n firstDayOfWeek = 1,\n consistentWeeks\n}) {\n const day = dayjs(month).subtract(dayjs(month).date() - 1, \"day\");\n const start = dayjs(day).startOf(\"day\");\n const startOfMonth = start.toDate();\n const endOfMonth = start.add(+start.daysInMonth() - 1, \"day\").toDate();\n const endDate = getEndOfWeek(endOfMonth, firstDayOfWeek);\n const date = getStartOfWeek(startOfMonth, firstDayOfWeek);\n const weeks = [];\n while (date <= endDate) {\n const days = [];\n for (let i = 0; i < 7; i += 1) {\n days.push(new Date(date));\n date.setDate(date.getDate() + 1);\n }\n weeks.push(days);\n }\n if (consistentWeeks && weeks.length < 6) {\n const lastWeek = weeks[weeks.length - 1];\n const lastDay = lastWeek[lastWeek.length - 1];\n const nextDay = new Date(lastDay);\n nextDay.setDate(nextDay.getDate() + 1);\n while (weeks.length < 6) {\n const days = [];\n for (let i = 0; i < 7; i += 1) {\n days.push(new Date(nextDay));\n nextDay.setDate(nextDay.getDate() + 1);\n }\n weeks.push(days);\n }\n }\n return weeks;\n}\n\nexport { getMonthDays };\n//# sourceMappingURL=get-month-days.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction isAfterMinDate(date, minDate) {\n return minDate instanceof Date ? dayjs(date).isAfter(dayjs(minDate).subtract(1, \"day\"), \"day\") : true;\n}\n\nexport { isAfterMinDate };\n//# sourceMappingURL=is-after-min-date.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction isBeforeMaxDate(date, maxDate) {\n return maxDate instanceof Date ? dayjs(date).isBefore(dayjs(maxDate).add(1, \"day\"), \"day\") : true;\n}\n\nexport { isBeforeMaxDate };\n//# sourceMappingURL=is-before-max-date.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\nimport { isAfterMinDate } from '../is-after-min-date/is-after-min-date.mjs';\nimport { isBeforeMaxDate } from '../is-before-max-date/is-before-max-date.mjs';\n\nfunction getDateInTabOrder(dates, minDate, maxDate, getDateControlProps, excludeDate, hideOutsideDates, month) {\n const enabledDates = dates.flat().filter(\n (date) => isBeforeMaxDate(date, maxDate) && isAfterMinDate(date, minDate) && !excludeDate?.(date) && !getDateControlProps?.(date)?.disabled && (!hideOutsideDates || dayjs(date).isSame(dayjs(month), \"month\"))\n );\n const selectedDate = enabledDates.find((date) => getDateControlProps?.(date)?.selected);\n if (selectedDate) {\n return selectedDate;\n }\n const currentDate = enabledDates.find((date) => dayjs().isSame(date, \"date\"));\n if (currentDate) {\n return currentDate;\n }\n return enabledDates[0];\n}\n\nexport { getDateInTabOrder };\n//# sourceMappingURL=get-date-in-tab-order.mjs.map\n","!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_plugin_isoWeek=t()}(this,(function(){\"use strict\";var e=\"day\";return function(t,i,s){var a=function(t){return t.add(4-t.isoWeekday(),e)},d=i.prototype;d.isoWeekYear=function(){return a(this).year()},d.isoWeek=function(t){if(!this.$utils().u(t))return this.add(7*(t-this.isoWeek()),e);var i,d,n,o,r=a(this),u=(i=this.isoWeekYear(),d=this.$u,n=(d?s.utc:s)().year(i).startOf(\"year\"),o=4-n.isoWeekday(),n.isoWeekday()>4&&(o+=7),n.add(o,e));return r.diff(u,\"week\")+1},d.isoWeekday=function(e){return this.$utils().u(e)?this.day()||7:this.day(this.day()%7?e:e-7)};var n=d.startOf;d.startOf=function(e,t){var i=this.$utils(),s=!!i.u(t)||t;return\"isoweek\"===i.p(e)?s?this.date(this.date()-(this.isoWeekday()-1)).startOf(\"day\"):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf(\"day\"):n.bind(this)(e,t)}}}));","'use client';\nimport dayjs from 'dayjs';\nimport isoWeek from 'dayjs/plugin/isoWeek.js';\n\ndayjs.extend(isoWeek);\nfunction getWeekNumber(week) {\n const monday = week.find((date) => dayjs(date).day() === 1);\n return dayjs(monday).isoWeek();\n}\n\nexport { getWeekNumber };\n//# sourceMappingURL=get-week-number.mjs.map\n","'use client';\nvar classes = {\"month\":\"m_cc9820d3\",\"monthCell\":\"m_8f457cd5\",\"weekNumber\":\"m_6cff9dea\"};\n\nexport { classes as default };\n//# sourceMappingURL=Month.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { createVarsResolver, getFontSize, getSize, factory, useProps, useStyles, useResolvedStylesApi, Box } from '@mantine/core';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { Day } from '../Day/Day.mjs';\nimport { WeekdaysRow } from '../WeekdaysRow/WeekdaysRow.mjs';\nimport { getDateInTabOrder } from './get-date-in-tab-order/get-date-in-tab-order.mjs';\nimport { getMonthDays } from './get-month-days/get-month-days.mjs';\nimport { getWeekNumber } from './get-week-number/get-week-number.mjs';\nimport { isAfterMinDate } from './is-after-min-date/is-after-min-date.mjs';\nimport { isBeforeMaxDate } from './is-before-max-date/is-before-max-date.mjs';\nimport classes from './Month.module.css.mjs';\n\nconst defaultProps = {\n withCellSpacing: true\n};\nconst varsResolver = createVarsResolver((_, { size }) => ({\n weekNumber: {\n \"--wn-fz\": getFontSize(size),\n \"--wn-size\": getSize(size, \"wn-size\")\n }\n}));\nconst Month = factory((_props, ref) => {\n const props = useProps(\"Month\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n __staticSelector,\n locale,\n firstDayOfWeek,\n weekdayFormat,\n month,\n weekendDays,\n getDayProps,\n excludeDate,\n minDate,\n maxDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n static: isStatic,\n __getDayRef,\n __onDayKeyDown,\n __onDayClick,\n __onDayMouseEnter,\n __preventFocus,\n __stopPropagation,\n withCellSpacing,\n size,\n highlightToday,\n withWeekNumbers,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector || \"Month\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver,\n rootSelector: \"month\"\n });\n const ctx = useDatesContext();\n const dates = getMonthDays({\n month,\n firstDayOfWeek: ctx.getFirstDayOfWeek(firstDayOfWeek),\n consistentWeeks: ctx.consistentWeeks\n });\n const dateInTabOrder = getDateInTabOrder(\n dates,\n minDate,\n maxDate,\n getDayProps,\n excludeDate,\n hideOutsideDates,\n month\n );\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n const rows = dates.map((row, rowIndex) => {\n const cells = row.map((date, cellIndex) => {\n const outside = !dayjs(date).isSame(dayjs(month), \"month\");\n const ariaLabel = getDayAriaLabel?.(date) || dayjs(date).locale(locale || ctx.locale).format(\"D MMMM YYYY\");\n const dayProps = getDayProps?.(date);\n const isDateInTabOrder = dayjs(date).isSame(dateInTabOrder, \"date\");\n return /* @__PURE__ */ jsx(\n \"td\",\n {\n ...getStyles(\"monthCell\"),\n \"data-with-spacing\": withCellSpacing || void 0,\n children: /* @__PURE__ */ jsx(\n Day,\n {\n __staticSelector: __staticSelector || \"Month\",\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n \"data-mantine-stop-propagation\": __stopPropagation || void 0,\n highlightToday,\n renderDay,\n date,\n size,\n weekend: ctx.getWeekendDays(weekendDays).includes(date.getDay()),\n outside,\n hidden: hideOutsideDates ? outside : false,\n \"aria-label\": ariaLabel,\n static: isStatic,\n disabled: excludeDate?.(date) || !isBeforeMaxDate(date, maxDate) || !isAfterMinDate(date, minDate),\n ref: (node) => __getDayRef?.(rowIndex, cellIndex, node),\n ...dayProps,\n onKeyDown: (event) => {\n dayProps?.onKeyDown?.(event);\n __onDayKeyDown?.(event, { rowIndex, cellIndex, date });\n },\n onMouseEnter: (event) => {\n dayProps?.onMouseEnter?.(event);\n __onDayMouseEnter?.(event, date);\n },\n onClick: (event) => {\n dayProps?.onClick?.(event);\n __onDayClick?.(event, date);\n },\n onMouseDown: (event) => {\n dayProps?.onMouseDown?.(event);\n __preventFocus && event.preventDefault();\n },\n tabIndex: __preventFocus || !isDateInTabOrder ? -1 : 0\n }\n )\n },\n date.toString()\n );\n });\n return /* @__PURE__ */ jsxs(\"tr\", { ...getStyles(\"monthRow\"), children: [\n withWeekNumbers && /* @__PURE__ */ jsx(\"td\", { ...getStyles(\"weekNumber\"), children: getWeekNumber(row) }),\n cells\n ] }, rowIndex);\n });\n return /* @__PURE__ */ jsxs(Box, { component: \"table\", ...getStyles(\"month\"), size, ref, ...others, children: [\n !hideWeekdays && /* @__PURE__ */ jsx(\"thead\", { ...getStyles(\"monthThead\"), children: /* @__PURE__ */ jsx(\n WeekdaysRow,\n {\n __staticSelector: __staticSelector || \"Month\",\n locale,\n firstDayOfWeek,\n weekdayFormat,\n size,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n withWeekNumbers\n }\n ) }),\n /* @__PURE__ */ jsx(\"tbody\", { ...getStyles(\"monthTbody\"), children: rows })\n ] });\n});\nMonth.classes = classes;\nMonth.displayName = \"@mantine/dates/Month\";\n\nexport { Month };\n//# sourceMappingURL=Month.mjs.map\n","'use client';\nvar classes = {\"pickerControl\":\"m_dc6a3c71\"};\n\nexport { classes as default };\n//# sourceMappingURL=PickerControl.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { createVarsResolver, getFontSize, getSize, factory, useProps, useStyles, UnstyledButton } from '@mantine/core';\nimport classes from './PickerControl.module.css.mjs';\n\nconst defaultProps = {};\nconst varsResolver = createVarsResolver((_, { size }) => ({\n pickerControl: {\n \"--dpc-fz\": getFontSize(size),\n \"--dpc-size\": getSize(size, \"dpc-size\")\n }\n}));\nconst PickerControl = factory((_props, ref) => {\n const props = useProps(\"PickerControl\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n firstInRange,\n lastInRange,\n inRange,\n __staticSelector,\n selected,\n disabled,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector || \"PickerControl\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver,\n rootSelector: \"pickerControl\"\n });\n return /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ...getStyles(\"pickerControl\"),\n ref,\n unstyled,\n \"data-picker-control\": true,\n \"data-selected\": selected && !disabled || void 0,\n \"data-disabled\": disabled || void 0,\n \"data-in-range\": inRange && !disabled && !selected || void 0,\n \"data-first-in-range\": firstInRange && !disabled || void 0,\n \"data-last-in-range\": lastInRange && !disabled || void 0,\n disabled,\n ...others\n }\n );\n});\nPickerControl.classes = classes;\nPickerControl.displayName = \"@mantine/dates/PickerControl\";\n\nexport { PickerControl };\n//# sourceMappingURL=PickerControl.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction isYearDisabled(year, minDate, maxDate) {\n if (!minDate && !maxDate) {\n return false;\n }\n if (minDate && dayjs(year).isBefore(minDate, \"year\")) {\n return true;\n }\n if (maxDate && dayjs(year).isAfter(maxDate, \"year\")) {\n return true;\n }\n return false;\n}\n\nexport { isYearDisabled };\n//# sourceMappingURL=is-year-disabled.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\nimport { isYearDisabled } from '../is-year-disabled/is-year-disabled.mjs';\n\nfunction getYearInTabOrder(years, minDate, maxDate, getYearControlProps) {\n const enabledYears = years.flat().filter(\n (year) => !isYearDisabled(year, minDate, maxDate) && !getYearControlProps?.(year)?.disabled\n );\n const selectedYear = enabledYears.find((year) => getYearControlProps?.(year)?.selected);\n if (selectedYear) {\n return selectedYear;\n }\n const currentYear = enabledYears.find((year) => dayjs().isSame(year, \"year\"));\n if (currentYear) {\n return currentYear;\n }\n return enabledYears[0];\n}\n\nexport { getYearInTabOrder };\n//# sourceMappingURL=get-year-in-tab-order.mjs.map\n","'use client';\nfunction getYearsData(decade) {\n const year = decade.getFullYear();\n const rounded = year - year % 10;\n let currentYearIndex = 0;\n const results = [[], [], [], []];\n for (let i = 0; i < 4; i += 1) {\n const max = i === 3 ? 1 : 3;\n for (let j = 0; j < max; j += 1) {\n results[i].push(new Date(rounded + currentYearIndex, 0));\n currentYearIndex += 1;\n }\n }\n return results;\n}\n\nexport { getYearsData };\n//# sourceMappingURL=get-years-data.mjs.map\n","'use client';\nvar classes = {\"yearsList\":\"m_9206547b\",\"yearsListCell\":\"m_c5a19c7d\"};\n\nexport { classes as default };\n//# sourceMappingURL=YearsList.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { factory, useProps, useStyles, Box } from '@mantine/core';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { PickerControl } from '../PickerControl/PickerControl.mjs';\nimport { getYearInTabOrder } from './get-year-in-tab-order/get-year-in-tab-order.mjs';\nimport { getYearsData } from './get-years-data/get-years-data.mjs';\nimport { isYearDisabled } from './is-year-disabled/is-year-disabled.mjs';\nimport classes from './YearsList.module.css.mjs';\n\nconst defaultProps = {\n yearsListFormat: \"YYYY\",\n withCellSpacing: true\n};\nconst YearsList = factory((_props, ref) => {\n const props = useProps(\"YearsList\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n decade,\n yearsListFormat,\n locale,\n minDate,\n maxDate,\n getYearControlProps,\n __staticSelector,\n __getControlRef,\n __onControlKeyDown,\n __onControlClick,\n __onControlMouseEnter,\n __preventFocus,\n __stopPropagation,\n withCellSpacing,\n size,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector || \"YearsList\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n rootSelector: \"yearsList\"\n });\n const ctx = useDatesContext();\n const years = getYearsData(decade);\n const yearInTabOrder = getYearInTabOrder(years, minDate, maxDate, getYearControlProps);\n const rows = years.map((yearsRow, rowIndex) => {\n const cells = yearsRow.map((year, cellIndex) => {\n const controlProps = getYearControlProps?.(year);\n const isYearInTabOrder = dayjs(year).isSame(yearInTabOrder, \"year\");\n return /* @__PURE__ */ jsx(\n \"td\",\n {\n ...getStyles(\"yearsListCell\"),\n \"data-with-spacing\": withCellSpacing || void 0,\n children: /* @__PURE__ */ jsx(\n PickerControl,\n {\n ...getStyles(\"yearsListControl\"),\n size,\n unstyled,\n \"data-mantine-stop-propagation\": __stopPropagation || void 0,\n disabled: isYearDisabled(year, minDate, maxDate),\n ref: (node) => __getControlRef?.(rowIndex, cellIndex, node),\n ...controlProps,\n onKeyDown: (event) => {\n controlProps?.onKeyDown?.(event);\n __onControlKeyDown?.(event, { rowIndex, cellIndex, date: year });\n },\n onClick: (event) => {\n controlProps?.onClick?.(event);\n __onControlClick?.(event, year);\n },\n onMouseEnter: (event) => {\n controlProps?.onMouseEnter?.(event);\n __onControlMouseEnter?.(event, year);\n },\n onMouseDown: (event) => {\n controlProps?.onMouseDown?.(event);\n __preventFocus && event.preventDefault();\n },\n tabIndex: __preventFocus || !isYearInTabOrder ? -1 : 0,\n children: dayjs(year).locale(ctx.getLocale(locale)).format(yearsListFormat)\n }\n )\n },\n cellIndex\n );\n });\n return /* @__PURE__ */ jsx(\"tr\", { ...getStyles(\"yearsListRow\"), children: cells }, rowIndex);\n });\n return /* @__PURE__ */ jsx(Box, { component: \"table\", ref, size, ...getStyles(\"yearsList\"), ...others, children: /* @__PURE__ */ jsx(\"tbody\", { children: rows }) });\n});\nYearsList.classes = classes;\nYearsList.displayName = \"@mantine/dates/YearsList\";\n\nexport { YearsList };\n//# sourceMappingURL=YearsList.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction isMonthDisabled(month, minDate, maxDate) {\n if (!minDate && !maxDate) {\n return false;\n }\n if (minDate && dayjs(month).isBefore(minDate, \"month\")) {\n return true;\n }\n if (maxDate && dayjs(month).isAfter(maxDate, \"month\")) {\n return true;\n }\n return false;\n}\n\nexport { isMonthDisabled };\n//# sourceMappingURL=is-month-disabled.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\nimport { isMonthDisabled } from '../is-month-disabled/is-month-disabled.mjs';\n\nfunction getMonthInTabOrder(months, minDate, maxDate, getMonthControlProps) {\n const enabledMonths = months.flat().filter(\n (month) => !isMonthDisabled(month, minDate, maxDate) && !getMonthControlProps?.(month)?.disabled\n );\n const selectedMonth = enabledMonths.find((month) => getMonthControlProps?.(month)?.selected);\n if (selectedMonth) {\n return selectedMonth;\n }\n const currentMonth = enabledMonths.find((month) => dayjs().isSame(month, \"month\"));\n if (currentMonth) {\n return currentMonth;\n }\n return enabledMonths[0];\n}\n\nexport { getMonthInTabOrder };\n//# sourceMappingURL=get-month-in-tab-order.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction getMonthsData(year) {\n const startOfYear = dayjs(year).startOf(\"year\").toDate();\n const results = [[], [], [], []];\n let currentMonthIndex = 0;\n for (let i = 0; i < 4; i += 1) {\n for (let j = 0; j < 3; j += 1) {\n results[i].push(dayjs(startOfYear).add(currentMonthIndex, \"months\").toDate());\n currentMonthIndex += 1;\n }\n }\n return results;\n}\n\nexport { getMonthsData };\n//# sourceMappingURL=get-months-data.mjs.map\n","'use client';\nvar classes = {\"monthsList\":\"m_2a6c32d\",\"monthsListCell\":\"m_fe27622f\"};\n\nexport { classes as default };\n//# sourceMappingURL=MonthsList.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { factory, useProps, useStyles, Box } from '@mantine/core';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { PickerControl } from '../PickerControl/PickerControl.mjs';\nimport { getMonthInTabOrder } from './get-month-in-tab-order/get-month-in-tab-order.mjs';\nimport { getMonthsData } from './get-months-data/get-months-data.mjs';\nimport { isMonthDisabled } from './is-month-disabled/is-month-disabled.mjs';\nimport classes from './MonthsList.module.css.mjs';\n\nconst defaultProps = {\n monthsListFormat: \"MMM\",\n withCellSpacing: true\n};\nconst MonthsList = factory((_props, ref) => {\n const props = useProps(\"MonthsList\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n __staticSelector,\n year,\n monthsListFormat,\n locale,\n minDate,\n maxDate,\n getMonthControlProps,\n __getControlRef,\n __onControlKeyDown,\n __onControlClick,\n __onControlMouseEnter,\n __preventFocus,\n __stopPropagation,\n withCellSpacing,\n size,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector || \"MonthsList\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n rootSelector: \"monthsList\"\n });\n const ctx = useDatesContext();\n const months = getMonthsData(year);\n const monthInTabOrder = getMonthInTabOrder(months, minDate, maxDate, getMonthControlProps);\n const rows = months.map((monthsRow, rowIndex) => {\n const cells = monthsRow.map((month, cellIndex) => {\n const controlProps = getMonthControlProps?.(month);\n const isMonthInTabOrder = dayjs(month).isSame(monthInTabOrder, \"month\");\n return /* @__PURE__ */ jsx(\n \"td\",\n {\n ...getStyles(\"monthsListCell\"),\n \"data-with-spacing\": withCellSpacing || void 0,\n children: /* @__PURE__ */ jsx(\n PickerControl,\n {\n ...getStyles(\"monthsListControl\"),\n size,\n unstyled,\n __staticSelector: __staticSelector || \"MonthsList\",\n \"data-mantine-stop-propagation\": __stopPropagation || void 0,\n disabled: isMonthDisabled(month, minDate, maxDate),\n ref: (node) => __getControlRef?.(rowIndex, cellIndex, node),\n ...controlProps,\n onKeyDown: (event) => {\n controlProps?.onKeyDown?.(event);\n __onControlKeyDown?.(event, { rowIndex, cellIndex, date: month });\n },\n onClick: (event) => {\n controlProps?.onClick?.(event);\n __onControlClick?.(event, month);\n },\n onMouseEnter: (event) => {\n controlProps?.onMouseEnter?.(event);\n __onControlMouseEnter?.(event, month);\n },\n onMouseDown: (event) => {\n controlProps?.onMouseDown?.(event);\n __preventFocus && event.preventDefault();\n },\n tabIndex: __preventFocus || !isMonthInTabOrder ? -1 : 0,\n children: dayjs(month).locale(ctx.getLocale(locale)).format(monthsListFormat)\n }\n )\n },\n cellIndex\n );\n });\n return /* @__PURE__ */ jsx(\"tr\", { ...getStyles(\"monthsListRow\"), children: cells }, rowIndex);\n });\n return /* @__PURE__ */ jsx(Box, { component: \"table\", ref, size, ...getStyles(\"monthsList\"), ...others, children: /* @__PURE__ */ jsx(\"tbody\", { children: rows }) });\n});\nMonthsList.classes = classes;\nMonthsList.displayName = \"@mantine/dates/MonthsList\";\n\nexport { MonthsList };\n//# sourceMappingURL=MonthsList.mjs.map\n","'use client';\nvar classes = {\"calendarHeader\":\"m_730a79ed\",\"calendarHeaderLevel\":\"m_f6645d97\",\"calendarHeaderControl\":\"m_2351eeb0\",\"calendarHeaderControlIcon\":\"m_367dc749\"};\n\nexport { classes as default };\n//# sourceMappingURL=CalendarHeader.module.css.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { createVarsResolver, getSize, getFontSize, factory, useProps, useStyles, Box, UnstyledButton, AccordionChevron } from '@mantine/core';\nimport classes from './CalendarHeader.module.css.mjs';\n\nconst defaultProps = {\n nextDisabled: false,\n previousDisabled: false,\n hasNextLevel: true,\n withNext: true,\n withPrevious: true\n};\nconst varsResolver = createVarsResolver((_, { size }) => ({\n calendarHeader: {\n \"--dch-control-size\": getSize(size, \"dch-control-size\"),\n \"--dch-fz\": getFontSize(size)\n }\n}));\nconst CalendarHeader = factory((_props, ref) => {\n const props = useProps(\"CalendarHeader\", defaultProps, _props);\n const {\n classNames,\n className,\n style,\n styles,\n unstyled,\n vars,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n label,\n nextDisabled,\n previousDisabled,\n hasNextLevel,\n levelControlAriaLabel,\n withNext,\n withPrevious,\n __staticSelector,\n __preventFocus,\n __stopPropagation,\n ...others\n } = props;\n const getStyles = useStyles({\n name: __staticSelector || \"CalendarHeader\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n varsResolver,\n rootSelector: \"calendarHeader\"\n });\n const preventFocus = __preventFocus ? (event) => event.preventDefault() : void 0;\n return /* @__PURE__ */ jsxs(Box, { ...getStyles(\"calendarHeader\"), ref, ...others, children: [\n withPrevious && /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ...getStyles(\"calendarHeaderControl\"),\n \"data-direction\": \"previous\",\n \"aria-label\": previousLabel,\n onClick: onPrevious,\n unstyled,\n onMouseDown: preventFocus,\n disabled: previousDisabled,\n \"data-disabled\": previousDisabled || void 0,\n tabIndex: __preventFocus || previousDisabled ? -1 : 0,\n \"data-mantine-stop-propagation\": __stopPropagation || void 0,\n children: previousIcon || /* @__PURE__ */ jsx(\n AccordionChevron,\n {\n ...getStyles(\"calendarHeaderControlIcon\"),\n \"data-direction\": \"previous\",\n size: \"45%\"\n }\n )\n }\n ),\n /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n component: hasNextLevel ? \"button\" : \"div\",\n ...getStyles(\"calendarHeaderLevel\"),\n onClick: hasNextLevel ? onLevelClick : void 0,\n unstyled,\n onMouseDown: hasNextLevel ? preventFocus : void 0,\n disabled: !hasNextLevel,\n \"data-static\": !hasNextLevel || void 0,\n \"aria-label\": levelControlAriaLabel,\n tabIndex: __preventFocus || !hasNextLevel ? -1 : 0,\n \"data-mantine-stop-propagation\": __stopPropagation || void 0,\n children: label\n }\n ),\n withNext && /* @__PURE__ */ jsx(\n UnstyledButton,\n {\n ...getStyles(\"calendarHeaderControl\"),\n \"data-direction\": \"next\",\n \"aria-label\": nextLabel,\n onClick: onNext,\n unstyled,\n onMouseDown: preventFocus,\n disabled: nextDisabled,\n \"data-disabled\": nextDisabled || void 0,\n tabIndex: __preventFocus || nextDisabled ? -1 : 0,\n \"data-mantine-stop-propagation\": __stopPropagation || void 0,\n children: nextIcon || /* @__PURE__ */ jsx(\n AccordionChevron,\n {\n ...getStyles(\"calendarHeaderControlIcon\"),\n \"data-direction\": \"next\",\n size: \"45%\"\n }\n )\n }\n )\n ] });\n});\nCalendarHeader.classes = classes;\nCalendarHeader.displayName = \"@mantine/dates/CalendarHeader\";\n\nexport { CalendarHeader };\n//# sourceMappingURL=CalendarHeader.mjs.map\n","'use client';\nimport { getYearsData } from '../../YearsList/get-years-data/get-years-data.mjs';\n\nfunction getDecadeRange(decade) {\n const years = getYearsData(decade);\n return [years[0][0], years[3][0]];\n}\n\nexport { getDecadeRange };\n//# sourceMappingURL=get-decade-range.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { factory, useProps, Box } from '@mantine/core';\nimport { CalendarHeader } from '../CalendarHeader/CalendarHeader.mjs';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { YearsList } from '../YearsList/YearsList.mjs';\nimport { getDecadeRange } from './get-decade-range/get-decade-range.mjs';\n\nconst defaultProps = {\n decadeLabelFormat: \"YYYY\"\n};\nconst DecadeLevel = factory((_props, ref) => {\n const props = useProps(\"DecadeLevel\", defaultProps, _props);\n const {\n // YearsList settings\n decade,\n locale,\n minDate,\n maxDate,\n yearsListFormat,\n getYearControlProps,\n __getControlRef,\n __onControlKeyDown,\n __onControlClick,\n __onControlMouseEnter,\n withCellSpacing,\n // CalendarHeader settings\n __preventFocus,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n nextDisabled,\n previousDisabled,\n levelControlAriaLabel,\n withNext,\n withPrevious,\n // Other props\n decadeLabelFormat,\n classNames,\n styles,\n unstyled,\n __staticSelector,\n __stopPropagation,\n size,\n ...others\n } = props;\n const ctx = useDatesContext();\n const [startOfDecade, endOfDecade] = getDecadeRange(decade);\n const stylesApiProps = {\n __staticSelector: __staticSelector || \"DecadeLevel\",\n classNames,\n styles,\n unstyled,\n size\n };\n const _nextDisabled = typeof nextDisabled === \"boolean\" ? nextDisabled : maxDate ? !dayjs(endOfDecade).endOf(\"year\").isBefore(maxDate) : false;\n const _previousDisabled = typeof previousDisabled === \"boolean\" ? previousDisabled : minDate ? !dayjs(startOfDecade).startOf(\"year\").isAfter(minDate) : false;\n const formatDecade = (date, format) => dayjs(date).locale(locale || ctx.locale).format(format);\n return /* @__PURE__ */ jsxs(Box, { \"data-decade-level\": true, size, ref, ...others, children: [\n /* @__PURE__ */ jsx(\n CalendarHeader,\n {\n label: typeof decadeLabelFormat === \"function\" ? decadeLabelFormat(startOfDecade, endOfDecade) : `${formatDecade(startOfDecade, decadeLabelFormat)} \\u2013 ${formatDecade(\n endOfDecade,\n decadeLabelFormat\n )}`,\n __preventFocus,\n __stopPropagation,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n nextDisabled: _nextDisabled,\n previousDisabled: _previousDisabled,\n hasNextLevel: false,\n levelControlAriaLabel,\n withNext,\n withPrevious,\n ...stylesApiProps\n }\n ),\n /* @__PURE__ */ jsx(\n YearsList,\n {\n decade,\n locale,\n minDate,\n maxDate,\n yearsListFormat,\n getYearControlProps,\n __getControlRef,\n __onControlKeyDown,\n __onControlClick,\n __onControlMouseEnter,\n __preventFocus,\n __stopPropagation,\n withCellSpacing,\n ...stylesApiProps\n }\n )\n ] });\n});\nDecadeLevel.classes = { ...YearsList.classes, ...CalendarHeader.classes };\nDecadeLevel.displayName = \"@mantine/dates/DecadeLevel\";\n\nexport { DecadeLevel };\n//# sourceMappingURL=DecadeLevel.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { factory, useProps, Box } from '@mantine/core';\nimport { CalendarHeader } from '../CalendarHeader/CalendarHeader.mjs';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { MonthsList } from '../MonthsList/MonthsList.mjs';\n\nconst defaultProps = {\n yearLabelFormat: \"YYYY\"\n};\nconst YearLevel = factory((_props, ref) => {\n const props = useProps(\"YearLevel\", defaultProps, _props);\n const {\n // MonthsList settings\n year,\n locale,\n minDate,\n maxDate,\n monthsListFormat,\n getMonthControlProps,\n __getControlRef,\n __onControlKeyDown,\n __onControlClick,\n __onControlMouseEnter,\n withCellSpacing,\n // CalendarHeader settings\n __preventFocus,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n nextDisabled,\n previousDisabled,\n hasNextLevel,\n levelControlAriaLabel,\n withNext,\n withPrevious,\n // Other props\n yearLabelFormat,\n __staticSelector,\n __stopPropagation,\n size,\n classNames,\n styles,\n unstyled,\n ...others\n } = props;\n const ctx = useDatesContext();\n const stylesApiProps = {\n __staticSelector: __staticSelector || \"YearLevel\",\n classNames,\n styles,\n unstyled,\n size\n };\n const _nextDisabled = typeof nextDisabled === \"boolean\" ? nextDisabled : maxDate ? !dayjs(year).endOf(\"year\").isBefore(maxDate) : false;\n const _previousDisabled = typeof previousDisabled === \"boolean\" ? previousDisabled : minDate ? !dayjs(year).startOf(\"year\").isAfter(minDate) : false;\n return /* @__PURE__ */ jsxs(Box, { \"data-year-level\": true, size, ref, ...others, children: [\n /* @__PURE__ */ jsx(\n CalendarHeader,\n {\n label: typeof yearLabelFormat === \"function\" ? yearLabelFormat(year) : dayjs(year).locale(locale || ctx.locale).format(yearLabelFormat),\n __preventFocus,\n __stopPropagation,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n nextDisabled: _nextDisabled,\n previousDisabled: _previousDisabled,\n hasNextLevel,\n levelControlAriaLabel,\n withNext,\n withPrevious,\n ...stylesApiProps\n }\n ),\n /* @__PURE__ */ jsx(\n MonthsList,\n {\n year,\n locale,\n minDate,\n maxDate,\n monthsListFormat,\n getMonthControlProps,\n __getControlRef,\n __onControlKeyDown,\n __onControlClick,\n __onControlMouseEnter,\n __preventFocus,\n __stopPropagation,\n withCellSpacing,\n ...stylesApiProps\n }\n )\n ] });\n});\nYearLevel.classes = { ...CalendarHeader.classes, ...MonthsList.classes };\nYearLevel.displayName = \"@mantine/dates/YearLevel\";\n\nexport { YearLevel };\n//# sourceMappingURL=YearLevel.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { factory, useProps, Box } from '@mantine/core';\nimport { CalendarHeader } from '../CalendarHeader/CalendarHeader.mjs';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { Month } from '../Month/Month.mjs';\n\nconst defaultProps = {\n monthLabelFormat: \"MMMM YYYY\"\n};\nconst MonthLevel = factory((_props, ref) => {\n const props = useProps(\"MonthLevel\", defaultProps, _props);\n const {\n // Month settings\n month,\n locale,\n firstDayOfWeek,\n weekdayFormat,\n weekendDays,\n getDayProps,\n excludeDate,\n minDate,\n maxDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n __getDayRef,\n __onDayKeyDown,\n __onDayClick,\n __onDayMouseEnter,\n withCellSpacing,\n highlightToday,\n withWeekNumbers,\n // CalendarHeader settings\n __preventFocus,\n __stopPropagation,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n nextDisabled,\n previousDisabled,\n hasNextLevel,\n levelControlAriaLabel,\n withNext,\n withPrevious,\n // Other props\n monthLabelFormat,\n classNames,\n styles,\n unstyled,\n __staticSelector,\n size,\n static: isStatic,\n ...others\n } = props;\n const ctx = useDatesContext();\n const stylesApiProps = {\n __staticSelector: __staticSelector || \"MonthLevel\",\n classNames,\n styles,\n unstyled,\n size\n };\n const _nextDisabled = typeof nextDisabled === \"boolean\" ? nextDisabled : maxDate ? !dayjs(month).endOf(\"month\").isBefore(maxDate) : false;\n const _previousDisabled = typeof previousDisabled === \"boolean\" ? previousDisabled : minDate ? !dayjs(month).startOf(\"month\").isAfter(minDate) : false;\n return /* @__PURE__ */ jsxs(Box, { \"data-month-level\": true, size, ref, ...others, children: [\n /* @__PURE__ */ jsx(\n CalendarHeader,\n {\n label: typeof monthLabelFormat === \"function\" ? monthLabelFormat(month) : dayjs(month).locale(locale || ctx.locale).format(monthLabelFormat),\n __preventFocus,\n __stopPropagation,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n nextDisabled: _nextDisabled,\n previousDisabled: _previousDisabled,\n hasNextLevel,\n levelControlAriaLabel,\n withNext,\n withPrevious,\n ...stylesApiProps\n }\n ),\n /* @__PURE__ */ jsx(\n Month,\n {\n month,\n locale,\n firstDayOfWeek,\n weekdayFormat,\n weekendDays,\n getDayProps,\n excludeDate,\n minDate,\n maxDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n __getDayRef,\n __onDayKeyDown,\n __onDayClick,\n __onDayMouseEnter,\n __preventFocus,\n __stopPropagation,\n static: isStatic,\n withCellSpacing,\n highlightToday,\n withWeekNumbers,\n ...stylesApiProps\n }\n )\n ] });\n});\nMonthLevel.classes = { ...Month.classes, ...CalendarHeader.classes };\nMonthLevel.displayName = \"@mantine/dates/MonthLevel\";\n\nexport { MonthLevel };\n//# sourceMappingURL=MonthLevel.mjs.map\n","'use client';\nvar classes = {\"levelsGroup\":\"m_30b26e33\"};\n\nexport { classes as default };\n//# sourceMappingURL=LevelsGroup.module.css.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { factory, useProps, useStyles, Box } from '@mantine/core';\nimport classes from './LevelsGroup.module.css.mjs';\n\nconst defaultProps = {};\nconst LevelsGroup = factory((_props, ref) => {\n const props = useProps(\"LevelsGroup\", defaultProps, _props);\n const { classNames, className, style, styles, unstyled, vars, __staticSelector, ...others } = props;\n const getStyles = useStyles({\n name: __staticSelector || \"LevelsGroup\",\n classes,\n props,\n className,\n style,\n classNames,\n styles,\n unstyled,\n vars,\n rootSelector: \"levelsGroup\"\n });\n return /* @__PURE__ */ jsx(Box, { ref, ...getStyles(\"levelsGroup\"), ...others });\n});\nLevelsGroup.classes = classes;\nLevelsGroup.displayName = \"@mantine/dates/LevelsGroup\";\n\nexport { LevelsGroup };\n//# sourceMappingURL=LevelsGroup.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { useRef } from 'react';\nimport { factory, useProps } from '@mantine/core';\nimport { handleControlKeyDown } from '../../utils/handle-control-key-down.mjs';\nimport '../../utils/get-timezone-offset.mjs';\nimport { DecadeLevel } from '../DecadeLevel/DecadeLevel.mjs';\nimport { LevelsGroup } from '../LevelsGroup/LevelsGroup.mjs';\n\nconst defaultProps = {\n numberOfColumns: 1\n};\nconst DecadeLevelGroup = factory((_props, ref) => {\n const props = useProps(\"DecadeLevelGroup\", defaultProps, _props);\n const {\n // DecadeLevel settings\n decade,\n locale,\n minDate,\n maxDate,\n yearsListFormat,\n getYearControlProps,\n __onControlClick,\n __onControlMouseEnter,\n withCellSpacing,\n // CalendarHeader settings\n __preventFocus,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n nextDisabled,\n previousDisabled,\n // Other settings\n classNames,\n styles,\n unstyled,\n __staticSelector,\n __stopPropagation,\n numberOfColumns,\n levelControlAriaLabel,\n decadeLabelFormat,\n size,\n vars,\n ...others\n } = props;\n const controlsRef = useRef([]);\n const decades = Array(numberOfColumns).fill(0).map((_, decadeIndex) => {\n const currentDecade = dayjs(decade).add(decadeIndex * 10, \"years\").toDate();\n return /* @__PURE__ */ jsx(\n DecadeLevel,\n {\n size,\n yearsListFormat,\n decade: currentDecade,\n withNext: decadeIndex === numberOfColumns - 1,\n withPrevious: decadeIndex === 0,\n decadeLabelFormat,\n __onControlClick,\n __onControlMouseEnter,\n __onControlKeyDown: (event, payload) => handleControlKeyDown({\n levelIndex: decadeIndex,\n rowIndex: payload.rowIndex,\n cellIndex: payload.cellIndex,\n event,\n controlsRef\n }),\n __getControlRef: (rowIndex, cellIndex, node) => {\n if (!Array.isArray(controlsRef.current[decadeIndex])) {\n controlsRef.current[decadeIndex] = [];\n }\n if (!Array.isArray(controlsRef.current[decadeIndex][rowIndex])) {\n controlsRef.current[decadeIndex][rowIndex] = [];\n }\n controlsRef.current[decadeIndex][rowIndex][cellIndex] = node;\n },\n levelControlAriaLabel: typeof levelControlAriaLabel === \"function\" ? levelControlAriaLabel(currentDecade) : levelControlAriaLabel,\n locale,\n minDate,\n maxDate,\n __preventFocus,\n __stopPropagation,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n nextDisabled,\n previousDisabled,\n getYearControlProps,\n __staticSelector: __staticSelector || \"DecadeLevelGroup\",\n classNames,\n styles,\n unstyled,\n withCellSpacing\n },\n decadeIndex\n );\n });\n return /* @__PURE__ */ jsx(\n LevelsGroup,\n {\n classNames,\n styles,\n __staticSelector: __staticSelector || \"DecadeLevelGroup\",\n ref,\n size,\n unstyled,\n ...others,\n children: decades\n }\n );\n});\nDecadeLevelGroup.classes = { ...LevelsGroup.classes, ...DecadeLevel.classes };\nDecadeLevelGroup.displayName = \"@mantine/dates/DecadeLevelGroup\";\n\nexport { DecadeLevelGroup };\n//# sourceMappingURL=DecadeLevelGroup.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { useRef } from 'react';\nimport { factory, useProps } from '@mantine/core';\nimport { handleControlKeyDown } from '../../utils/handle-control-key-down.mjs';\nimport '../../utils/get-timezone-offset.mjs';\nimport { LevelsGroup } from '../LevelsGroup/LevelsGroup.mjs';\nimport { YearLevel } from '../YearLevel/YearLevel.mjs';\n\nconst defaultProps = {\n numberOfColumns: 1\n};\nconst YearLevelGroup = factory((_props, ref) => {\n const props = useProps(\"YearLevelGroup\", defaultProps, _props);\n const {\n // YearLevel settings\n year,\n locale,\n minDate,\n maxDate,\n monthsListFormat,\n getMonthControlProps,\n __onControlClick,\n __onControlMouseEnter,\n withCellSpacing,\n // CalendarHeader settings\n __preventFocus,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n nextDisabled,\n previousDisabled,\n hasNextLevel,\n // Other settings\n classNames,\n styles,\n unstyled,\n __staticSelector,\n __stopPropagation,\n numberOfColumns,\n levelControlAriaLabel,\n yearLabelFormat,\n size,\n vars,\n ...others\n } = props;\n const controlsRef = useRef([]);\n const years = Array(numberOfColumns).fill(0).map((_, yearIndex) => {\n const currentYear = dayjs(year).add(yearIndex, \"years\").toDate();\n return /* @__PURE__ */ jsx(\n YearLevel,\n {\n size,\n monthsListFormat,\n year: currentYear,\n withNext: yearIndex === numberOfColumns - 1,\n withPrevious: yearIndex === 0,\n yearLabelFormat,\n __stopPropagation,\n __onControlClick,\n __onControlMouseEnter,\n __onControlKeyDown: (event, payload) => handleControlKeyDown({\n levelIndex: yearIndex,\n rowIndex: payload.rowIndex,\n cellIndex: payload.cellIndex,\n event,\n controlsRef\n }),\n __getControlRef: (rowIndex, cellIndex, node) => {\n if (!Array.isArray(controlsRef.current[yearIndex])) {\n controlsRef.current[yearIndex] = [];\n }\n if (!Array.isArray(controlsRef.current[yearIndex][rowIndex])) {\n controlsRef.current[yearIndex][rowIndex] = [];\n }\n controlsRef.current[yearIndex][rowIndex][cellIndex] = node;\n },\n levelControlAriaLabel: typeof levelControlAriaLabel === \"function\" ? levelControlAriaLabel(currentYear) : levelControlAriaLabel,\n locale,\n minDate,\n maxDate,\n __preventFocus,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n nextDisabled,\n previousDisabled,\n hasNextLevel,\n getMonthControlProps,\n classNames,\n styles,\n unstyled,\n __staticSelector: __staticSelector || \"YearLevelGroup\",\n withCellSpacing\n },\n yearIndex\n );\n });\n return /* @__PURE__ */ jsx(\n LevelsGroup,\n {\n classNames,\n styles,\n __staticSelector: __staticSelector || \"YearLevelGroup\",\n ref,\n size,\n unstyled,\n ...others,\n children: years\n }\n );\n});\nYearLevelGroup.classes = { ...YearLevel.classes, ...LevelsGroup.classes };\nYearLevelGroup.displayName = \"@mantine/dates/YearLevelGroup\";\n\nexport { YearLevelGroup };\n//# sourceMappingURL=YearLevelGroup.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { useRef } from 'react';\nimport { factory, useProps } from '@mantine/core';\nimport { handleControlKeyDown } from '../../utils/handle-control-key-down.mjs';\nimport '../../utils/get-timezone-offset.mjs';\nimport { LevelsGroup } from '../LevelsGroup/LevelsGroup.mjs';\nimport { MonthLevel } from '../MonthLevel/MonthLevel.mjs';\n\nconst defaultProps = {\n numberOfColumns: 1\n};\nconst MonthLevelGroup = factory((_props, ref) => {\n const props = useProps(\"MonthLevelGroup\", defaultProps, _props);\n const {\n // Month settings\n month,\n locale,\n firstDayOfWeek,\n weekdayFormat,\n weekendDays,\n getDayProps,\n excludeDate,\n minDate,\n maxDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n __onDayClick,\n __onDayMouseEnter,\n withCellSpacing,\n highlightToday,\n withWeekNumbers,\n // CalendarHeader settings\n __preventFocus,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n nextDisabled,\n previousDisabled,\n hasNextLevel,\n // Other settings\n classNames,\n styles,\n unstyled,\n numberOfColumns,\n levelControlAriaLabel,\n monthLabelFormat,\n __staticSelector,\n __stopPropagation,\n size,\n static: isStatic,\n vars,\n ...others\n } = props;\n const daysRefs = useRef([]);\n const months = Array(numberOfColumns).fill(0).map((_, monthIndex) => {\n const currentMonth = dayjs(month).add(monthIndex, \"months\").toDate();\n return /* @__PURE__ */ jsx(\n MonthLevel,\n {\n month: currentMonth,\n withNext: monthIndex === numberOfColumns - 1,\n withPrevious: monthIndex === 0,\n monthLabelFormat,\n __stopPropagation,\n __onDayClick,\n __onDayMouseEnter,\n __onDayKeyDown: (event, payload) => handleControlKeyDown({\n levelIndex: monthIndex,\n rowIndex: payload.rowIndex,\n cellIndex: payload.cellIndex,\n event,\n controlsRef: daysRefs\n }),\n __getDayRef: (rowIndex, cellIndex, node) => {\n if (!Array.isArray(daysRefs.current[monthIndex])) {\n daysRefs.current[monthIndex] = [];\n }\n if (!Array.isArray(daysRefs.current[monthIndex][rowIndex])) {\n daysRefs.current[monthIndex][rowIndex] = [];\n }\n daysRefs.current[monthIndex][rowIndex][cellIndex] = node;\n },\n levelControlAriaLabel: typeof levelControlAriaLabel === \"function\" ? levelControlAriaLabel(currentMonth) : levelControlAriaLabel,\n locale,\n firstDayOfWeek,\n weekdayFormat,\n weekendDays,\n getDayProps,\n excludeDate,\n minDate,\n maxDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n __preventFocus,\n nextIcon,\n previousIcon,\n nextLabel,\n previousLabel,\n onNext,\n onPrevious,\n onLevelClick,\n nextDisabled,\n previousDisabled,\n hasNextLevel,\n classNames,\n styles,\n unstyled,\n __staticSelector: __staticSelector || \"MonthLevelGroup\",\n size,\n static: isStatic,\n withCellSpacing,\n highlightToday,\n withWeekNumbers\n },\n monthIndex\n );\n });\n return /* @__PURE__ */ jsx(\n LevelsGroup,\n {\n classNames,\n styles,\n __staticSelector: __staticSelector || \"MonthLevelGroup\",\n ref,\n size,\n ...others,\n children: months\n }\n );\n});\nMonthLevelGroup.classes = { ...LevelsGroup.classes, ...MonthLevel.classes };\nMonthLevelGroup.displayName = \"@mantine/dates/MonthLevelGroup\";\n\nexport { MonthLevelGroup };\n//# sourceMappingURL=MonthLevelGroup.mjs.map\n","'use client';\nvar classes = {\"input\":\"m_6fa5e2aa\"};\n\nexport { classes as default };\n//# sourceMappingURL=PickerInputBase.module.css.mjs.map\n","'use client';\nimport { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport cx from 'clsx';\nimport { factory, useInputProps, Input, Modal, Popover } from '@mantine/core';\nimport { HiddenDatesInput } from '../HiddenDatesInput/HiddenDatesInput.mjs';\nimport classes from './PickerInputBase.module.css.mjs';\n\nconst defaultProps = {};\nconst PickerInputBase = factory((_props, ref) => {\n const {\n inputProps,\n wrapperProps,\n placeholder,\n classNames,\n styles,\n unstyled,\n popoverProps,\n modalProps,\n dropdownType,\n children,\n formattedValue,\n dropdownHandlers,\n dropdownOpened,\n onClick,\n clearable,\n onClear,\n clearButtonProps,\n rightSection,\n shouldClear,\n readOnly,\n disabled,\n value,\n name,\n form,\n type,\n ...others\n } = useInputProps(\"PickerInputBase\", defaultProps, _props);\n const clearButton = /* @__PURE__ */ jsx(Input.ClearButton, { onClick: onClear, unstyled, ...clearButtonProps });\n const handleClose = () => {\n const isInvalidRangeValue = type === \"range\" && Array.isArray(value) && value[0] && !value[1];\n if (isInvalidRangeValue) {\n onClear();\n }\n dropdownHandlers.close();\n };\n return /* @__PURE__ */ jsxs(Fragment, { children: [\n dropdownType === \"modal\" && !readOnly && /* @__PURE__ */ jsx(\n Modal,\n {\n opened: dropdownOpened,\n onClose: handleClose,\n withCloseButton: false,\n size: \"auto\",\n \"data-dates-modal\": true,\n unstyled,\n ...modalProps,\n children\n }\n ),\n /* @__PURE__ */ jsx(Input.Wrapper, { ...wrapperProps, children: /* @__PURE__ */ jsxs(\n Popover,\n {\n position: \"bottom-start\",\n opened: dropdownOpened,\n trapFocus: true,\n returnFocus: false,\n unstyled,\n ...popoverProps,\n disabled: popoverProps?.disabled || dropdownType === \"modal\" || readOnly,\n onChange: (_opened) => {\n if (!_opened) {\n popoverProps?.onClose?.();\n handleClose();\n }\n },\n children: [\n /* @__PURE__ */ jsx(Popover.Target, { children: /* @__PURE__ */ jsx(\n Input,\n {\n \"data-dates-input\": true,\n \"data-read-only\": readOnly || void 0,\n disabled,\n component: \"button\",\n type: \"button\",\n multiline: true,\n onClick: (event) => {\n onClick?.(event);\n dropdownHandlers.toggle();\n },\n __clearSection: clearButton,\n __clearable: clearable && shouldClear && !readOnly && !disabled,\n rightSection,\n ...inputProps,\n ref,\n classNames: { ...classNames, input: cx(classes.input, classNames?.input) },\n ...others,\n children: formattedValue || /* @__PURE__ */ jsx(\n Input.Placeholder,\n {\n error: inputProps.error,\n unstyled,\n className: classNames?.placeholder,\n style: styles?.placeholder,\n children: placeholder\n }\n )\n }\n ) }),\n /* @__PURE__ */ jsx(Popover.Dropdown, { \"data-dates-dropdown\": true, children })\n ]\n }\n ) }),\n /* @__PURE__ */ jsx(HiddenDatesInput, { value, name, form, type })\n ] });\n});\nPickerInputBase.classes = classes;\nPickerInputBase.displayName = \"@mantine/dates/PickerInputBase\";\n\nexport { PickerInputBase };\n//# sourceMappingURL=PickerInputBase.mjs.map\n","'use client';\nimport { useRef } from 'react';\nimport { useUncontrolled } from '@mantine/hooks';\nimport '../../components/DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../../components/DatesProvider/use-dates-context.mjs';\nimport 'dayjs';\nimport { shiftTimezone } from '../../utils/shift-timezone.mjs';\n\nconst getEmptyValue = (type) => type === \"range\" ? [null, null] : type === \"multiple\" ? [] : null;\nfunction useUncontrolledDates({\n type,\n value,\n defaultValue,\n onChange,\n applyTimezone = true\n}) {\n const storedType = useRef(type);\n const ctx = useDatesContext();\n const [_value, _setValue, controlled] = useUncontrolled({\n value: shiftTimezone(\"add\", value, ctx.getTimezone(), !applyTimezone),\n defaultValue: shiftTimezone(\"add\", defaultValue, ctx.getTimezone(), !applyTimezone),\n finalValue: getEmptyValue(type),\n onChange: (newDate) => {\n onChange?.(shiftTimezone(\"remove\", newDate, ctx.getTimezone(), !applyTimezone));\n }\n });\n let _finalValue = _value;\n if (storedType.current !== type) {\n storedType.current = type;\n if (value === void 0) {\n _finalValue = defaultValue !== void 0 ? defaultValue : getEmptyValue(type);\n _setValue(_finalValue);\n } else if (process.env.NODE_ENV === \"development\") {\n switch (type) {\n case \"default\":\n if (value !== null && typeof value !== \"string\") {\n console.error(\n \"[@mantine/dates/use-uncontrolled-dates] Value must be type of `null` or `string`\"\n );\n }\n break;\n case \"multiple\":\n if (!(value instanceof Array)) {\n console.error(\n \"[@mantine/dates/use-uncontrolled-dates] Value must be type of `string[]`\"\n );\n }\n break;\n case \"range\":\n if (!(value instanceof Array) || value.length !== 2) {\n console.error(\n \"[@mantine/dates/use-uncontrolled-dates] Value must be type of `[string, string]`\"\n );\n }\n break;\n }\n }\n }\n return [_finalValue, _setValue, controlled];\n}\n\nexport { useUncontrolledDates };\n//# sourceMappingURL=use-uncontrolled-dates.mjs.map\n","'use client';\nimport { clamp } from '@mantine/hooks';\n\nfunction levelToNumber(level, fallback) {\n if (!level) {\n return fallback || 0;\n }\n return level === \"month\" ? 0 : level === \"year\" ? 1 : 2;\n}\nfunction levelNumberToLevel(levelNumber) {\n return levelNumber === 0 ? \"month\" : levelNumber === 1 ? \"year\" : \"decade\";\n}\nfunction clampLevel(level, minLevel, maxLevel) {\n return levelNumberToLevel(\n clamp(\n levelToNumber(level, 0),\n levelToNumber(minLevel, 0),\n levelToNumber(maxLevel, 2)\n )\n );\n}\n\nexport { clampLevel };\n//# sourceMappingURL=clamp-level.mjs.map\n","'use client';\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport dayjs from 'dayjs';\nimport { factory, useProps, useResolvedStylesApi, Box } from '@mantine/core';\nimport { useUncontrolled } from '@mantine/hooks';\nimport 'react';\nimport { useUncontrolledDates } from '../../hooks/use-uncontrolled-dates/use-uncontrolled-dates.mjs';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { shiftTimezone } from '../../utils/shift-timezone.mjs';\nimport { DecadeLevelGroup } from '../DecadeLevelGroup/DecadeLevelGroup.mjs';\nimport { MonthLevelGroup } from '../MonthLevelGroup/MonthLevelGroup.mjs';\nimport { YearLevelGroup } from '../YearLevelGroup/YearLevelGroup.mjs';\nimport { clampLevel } from './clamp-level/clamp-level.mjs';\n\nconst defaultProps = {\n maxLevel: \"decade\",\n minLevel: \"month\",\n __updateDateOnYearSelect: true,\n __updateDateOnMonthSelect: true\n};\nconst Calendar = factory((_props, ref) => {\n const props = useProps(\"Calendar\", defaultProps, _props);\n const {\n vars,\n // CalendarLevel props\n maxLevel,\n minLevel,\n defaultLevel,\n level,\n onLevelChange,\n date,\n defaultDate,\n onDateChange,\n numberOfColumns,\n columnsToScroll,\n ariaLabels,\n nextLabel,\n previousLabel,\n onYearSelect,\n onMonthSelect,\n onYearMouseEnter,\n onMonthMouseEnter,\n __updateDateOnYearSelect,\n __updateDateOnMonthSelect,\n // MonthLevelGroup props\n firstDayOfWeek,\n weekdayFormat,\n weekendDays,\n getDayProps,\n excludeDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n monthLabelFormat,\n nextIcon,\n previousIcon,\n __onDayClick,\n __onDayMouseEnter,\n withCellSpacing,\n highlightToday,\n withWeekNumbers,\n // YearLevelGroup props\n monthsListFormat,\n getMonthControlProps,\n yearLabelFormat,\n // DecadeLevelGroup props\n yearsListFormat,\n getYearControlProps,\n decadeLabelFormat,\n // Other props\n classNames,\n styles,\n unstyled,\n minDate,\n maxDate,\n locale,\n __staticSelector,\n size,\n __preventFocus,\n __stopPropagation,\n onNextDecade,\n onPreviousDecade,\n onNextYear,\n onPreviousYear,\n onNextMonth,\n onPreviousMonth,\n static: isStatic,\n __timezoneApplied,\n ...others\n } = props;\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n const [_level, setLevel] = useUncontrolled({\n value: level ? clampLevel(level, minLevel, maxLevel) : void 0,\n defaultValue: defaultLevel ? clampLevel(defaultLevel, minLevel, maxLevel) : void 0,\n finalValue: clampLevel(void 0, minLevel, maxLevel),\n onChange: onLevelChange\n });\n const [_date, setDate] = useUncontrolledDates({\n type: \"default\",\n value: date,\n defaultValue: defaultDate,\n onChange: onDateChange,\n applyTimezone: !__timezoneApplied\n });\n const stylesApiProps = {\n __staticSelector: __staticSelector || \"Calendar\",\n styles: resolvedStyles,\n classNames: resolvedClassNames,\n unstyled,\n size\n };\n const ctx = useDatesContext();\n const _columnsToScroll = columnsToScroll || numberOfColumns || 1;\n const now = /* @__PURE__ */ new Date();\n const fallbackDate = minDate && minDate > now ? minDate : now;\n const currentDate = _date || shiftTimezone(\"add\", fallbackDate, ctx.getTimezone());\n const handleNextMonth = () => {\n const nextDate = dayjs(currentDate).add(_columnsToScroll, \"month\").toDate();\n onNextMonth?.(nextDate);\n setDate(nextDate);\n };\n const handlePreviousMonth = () => {\n const nextDate = dayjs(currentDate).subtract(_columnsToScroll, \"month\").toDate();\n onPreviousMonth?.(nextDate);\n setDate(nextDate);\n };\n const handleNextYear = () => {\n const nextDate = dayjs(currentDate).add(_columnsToScroll, \"year\").toDate();\n onNextYear?.(nextDate);\n setDate(nextDate);\n };\n const handlePreviousYear = () => {\n const nextDate = dayjs(currentDate).subtract(_columnsToScroll, \"year\").toDate();\n onPreviousYear?.(nextDate);\n setDate(nextDate);\n };\n const handleNextDecade = () => {\n const nextDate = dayjs(currentDate).add(10 * _columnsToScroll, \"year\").toDate();\n onNextDecade?.(nextDate);\n setDate(nextDate);\n };\n const handlePreviousDecade = () => {\n const nextDate = dayjs(currentDate).subtract(10 * _columnsToScroll, \"year\").toDate();\n onPreviousDecade?.(nextDate);\n setDate(nextDate);\n };\n return /* @__PURE__ */ jsxs(Box, { ref, size, \"data-calendar\": true, ...others, children: [\n _level === \"month\" && /* @__PURE__ */ jsx(\n MonthLevelGroup,\n {\n month: currentDate,\n minDate,\n maxDate,\n firstDayOfWeek,\n weekdayFormat,\n weekendDays,\n getDayProps,\n excludeDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n onNext: handleNextMonth,\n onPrevious: handlePreviousMonth,\n hasNextLevel: maxLevel !== \"month\",\n onLevelClick: () => setLevel(\"year\"),\n numberOfColumns,\n locale,\n levelControlAriaLabel: ariaLabels?.monthLevelControl,\n nextLabel: ariaLabels?.nextMonth ?? nextLabel,\n nextIcon,\n previousLabel: ariaLabels?.previousMonth ?? previousLabel,\n previousIcon,\n monthLabelFormat,\n __onDayClick,\n __onDayMouseEnter,\n __preventFocus,\n __stopPropagation,\n static: isStatic,\n withCellSpacing,\n highlightToday,\n withWeekNumbers,\n ...stylesApiProps\n }\n ),\n _level === \"year\" && /* @__PURE__ */ jsx(\n YearLevelGroup,\n {\n year: currentDate,\n numberOfColumns,\n minDate,\n maxDate,\n monthsListFormat,\n getMonthControlProps,\n locale,\n onNext: handleNextYear,\n onPrevious: handlePreviousYear,\n hasNextLevel: maxLevel !== \"month\" && maxLevel !== \"year\",\n onLevelClick: () => setLevel(\"decade\"),\n levelControlAriaLabel: ariaLabels?.yearLevelControl,\n nextLabel: ariaLabels?.nextYear ?? nextLabel,\n nextIcon,\n previousLabel: ariaLabels?.previousYear ?? previousLabel,\n previousIcon,\n yearLabelFormat,\n __onControlMouseEnter: onMonthMouseEnter,\n __onControlClick: (_event, payload) => {\n __updateDateOnMonthSelect && setDate(payload);\n setLevel(clampLevel(\"month\", minLevel, maxLevel));\n onMonthSelect?.(payload);\n },\n __preventFocus,\n __stopPropagation,\n withCellSpacing,\n ...stylesApiProps\n }\n ),\n _level === \"decade\" && /* @__PURE__ */ jsx(\n DecadeLevelGroup,\n {\n decade: currentDate,\n minDate,\n maxDate,\n yearsListFormat,\n getYearControlProps,\n locale,\n onNext: handleNextDecade,\n onPrevious: handlePreviousDecade,\n numberOfColumns,\n nextLabel: ariaLabels?.nextDecade ?? nextLabel,\n nextIcon,\n previousLabel: ariaLabels?.previousDecade ?? previousLabel,\n previousIcon,\n decadeLabelFormat,\n __onControlMouseEnter: onYearMouseEnter,\n __onControlClick: (_event, payload) => {\n __updateDateOnYearSelect && setDate(payload);\n setLevel(clampLevel(\"year\", minLevel, maxLevel));\n onYearSelect?.(payload);\n },\n __preventFocus,\n __stopPropagation,\n withCellSpacing,\n ...stylesApiProps\n }\n )\n ] });\n});\nCalendar.classes = {\n ...DecadeLevelGroup.classes,\n ...YearLevelGroup.classes,\n ...MonthLevelGroup.classes\n};\nCalendar.displayName = \"@mantine/dates/Calendar\";\n\nexport { Calendar };\n//# sourceMappingURL=Calendar.mjs.map\n","'use client';\nfunction pickCalendarProps(props) {\n const {\n maxLevel,\n minLevel,\n defaultLevel,\n level,\n onLevelChange,\n nextIcon,\n previousIcon,\n date,\n defaultDate,\n onDateChange,\n numberOfColumns,\n columnsToScroll,\n ariaLabels,\n nextLabel,\n previousLabel,\n onYearSelect,\n onMonthSelect,\n onYearMouseEnter,\n onMonthMouseEnter,\n onNextMonth,\n onPreviousMonth,\n onNextYear,\n onPreviousYear,\n onNextDecade,\n onPreviousDecade,\n withCellSpacing,\n highlightToday,\n __updateDateOnYearSelect,\n __updateDateOnMonthSelect,\n withWeekNumbers,\n // MonthLevelGroup props\n firstDayOfWeek,\n weekdayFormat,\n weekendDays,\n getDayProps,\n excludeDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n monthLabelFormat,\n // YearLevelGroup props\n monthsListFormat,\n getMonthControlProps,\n yearLabelFormat,\n // DecadeLevelGroup props\n yearsListFormat,\n getYearControlProps,\n decadeLabelFormat,\n // External picker props\n allowSingleDateInRange,\n allowDeselect,\n // Other props\n minDate,\n maxDate,\n locale,\n ...others\n } = props;\n return {\n calendarProps: {\n maxLevel,\n minLevel,\n defaultLevel,\n level,\n onLevelChange,\n nextIcon,\n previousIcon,\n date,\n defaultDate,\n onDateChange,\n numberOfColumns,\n columnsToScroll,\n ariaLabels,\n nextLabel,\n previousLabel,\n onYearSelect,\n onMonthSelect,\n onYearMouseEnter,\n onMonthMouseEnter,\n onNextMonth,\n onPreviousMonth,\n onNextYear,\n onPreviousYear,\n onNextDecade,\n onPreviousDecade,\n withCellSpacing,\n highlightToday,\n __updateDateOnYearSelect,\n __updateDateOnMonthSelect,\n withWeekNumbers,\n // MonthLevelGroup props\n firstDayOfWeek,\n weekdayFormat,\n weekendDays,\n getDayProps,\n excludeDate,\n renderDay,\n hideOutsideDates,\n hideWeekdays,\n getDayAriaLabel,\n monthLabelFormat,\n // YearLevelGroup props\n monthsListFormat,\n getMonthControlProps,\n yearLabelFormat,\n // DecadeLevelGroup props\n yearsListFormat,\n getYearControlProps,\n decadeLabelFormat,\n // External picker props\n allowSingleDateInRange,\n allowDeselect,\n // Other props\n minDate,\n maxDate,\n locale\n },\n others\n };\n}\n\nexport { pickCalendarProps };\n//# sourceMappingURL=pick-calendar-levels-props.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\n\nfunction isInRange(date, range) {\n const _range = [...range].sort((a, b) => a.getTime() - b.getTime());\n return dayjs(_range[0]).startOf(\"day\").subtract(1, \"ms\").isBefore(date) && dayjs(_range[1]).endOf(\"day\").add(1, \"ms\").isAfter(date);\n}\n\nexport { isInRange };\n//# sourceMappingURL=is-in-range.mjs.map\n","'use client';\nimport dayjs from 'dayjs';\nimport { useState, useEffect } from 'react';\nimport { useUncontrolledDates } from '../use-uncontrolled-dates/use-uncontrolled-dates.mjs';\nimport { isInRange } from './is-in-range/is-in-range.mjs';\n\nfunction useDatesState({\n type,\n level,\n value,\n defaultValue,\n onChange,\n allowSingleDateInRange,\n allowDeselect,\n onMouseLeave,\n applyTimezone = true\n}) {\n const [_value, setValue] = useUncontrolledDates({\n type,\n value,\n defaultValue,\n onChange,\n applyTimezone\n });\n const [pickedDate, setPickedDate] = useState(\n type === \"range\" ? _value[0] && !_value[1] ? _value[0] : null : null\n );\n const [hoveredDate, setHoveredDate] = useState(null);\n const onDateChange = (date) => {\n if (type === \"range\") {\n if (pickedDate instanceof Date && !_value[1]) {\n if (dayjs(date).isSame(pickedDate, level) && !allowSingleDateInRange) {\n setPickedDate(null);\n setHoveredDate(null);\n setValue([null, null]);\n return;\n }\n const result = [date, pickedDate];\n result.sort((a, b) => a.getTime() - b.getTime());\n setValue(result);\n setHoveredDate(null);\n setPickedDate(null);\n return;\n }\n if (_value[0] && !_value[1] && dayjs(date).isSame(_value[0], level) && !allowSingleDateInRange) {\n setPickedDate(null);\n setHoveredDate(null);\n setValue([null, null]);\n return;\n }\n setValue([date, null]);\n setHoveredDate(null);\n setPickedDate(date);\n return;\n }\n if (type === \"multiple\") {\n if (_value.some((selected) => dayjs(selected).isSame(date, level))) {\n setValue(_value.filter((selected) => !dayjs(selected).isSame(date, level)));\n } else {\n setValue([..._value, date]);\n }\n return;\n }\n if (_value && allowDeselect && dayjs(date).isSame(_value, level)) {\n setValue(null);\n } else {\n setValue(date);\n }\n };\n const isDateInRange = (date) => {\n if (pickedDate instanceof Date && hoveredDate instanceof Date) {\n return isInRange(date, [hoveredDate, pickedDate]);\n }\n if (_value[0] instanceof Date && _value[1] instanceof Date) {\n return isInRange(date, _value);\n }\n return false;\n };\n const onRootMouseLeave = type === \"range\" ? (event) => {\n onMouseLeave?.(event);\n setHoveredDate(null);\n } : onMouseLeave;\n const isFirstInRange = (date) => {\n if (!(_value[0] instanceof Date)) {\n return false;\n }\n if (dayjs(date).isSame(_value[0], level)) {\n return !(hoveredDate && dayjs(hoveredDate).isBefore(_value[0]));\n }\n return false;\n };\n const isLastInRange = (date) => {\n if (_value[1] instanceof Date) {\n return dayjs(date).isSame(_value[1], level);\n }\n if (!(_value[0] instanceof Date) || !hoveredDate) {\n return false;\n }\n return dayjs(hoveredDate).isBefore(_value[0]) && dayjs(date).isSame(_value[0], level);\n };\n const getControlProps = (date) => {\n if (type === \"range\") {\n return {\n selected: _value.some(\n (selection) => selection && dayjs(selection).isSame(date, level)\n ),\n inRange: isDateInRange(date),\n firstInRange: isFirstInRange(date),\n lastInRange: isLastInRange(date),\n \"data-autofocus\": !!_value[0] && dayjs(_value[0]).isSame(date, level) || void 0\n };\n }\n if (type === \"multiple\") {\n return {\n selected: _value.some(\n (selection) => selection && dayjs(selection).isSame(date, level)\n ),\n \"data-autofocus\": !!_value[0] && dayjs(_value[0]).isSame(date, level) || void 0\n };\n }\n const selected = dayjs(_value).isSame(date, level);\n return { selected, \"data-autofocus\": selected || void 0 };\n };\n const onHoveredDateChange = type === \"range\" && pickedDate ? setHoveredDate : () => {\n };\n useEffect(() => {\n if (type !== \"range\") {\n return;\n }\n if (_value[0] && !_value[1] && pickedDate?.getTime() !== _value[0].getTime()) {\n setPickedDate(_value[0]);\n } else {\n const isNeitherSelected = _value[0] == null && _value[1] == null;\n const isBothSelected = _value[0] != null && _value[1] != null;\n if (isNeitherSelected || isBothSelected) {\n setPickedDate(null);\n setHoveredDate(null);\n }\n }\n }, [_value]);\n return {\n onDateChange,\n onRootMouseLeave,\n onHoveredDateChange,\n getControlProps,\n _value,\n setValue\n };\n}\n\nexport { useDatesState };\n//# sourceMappingURL=use-dates-state.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { factory, useProps, useResolvedStylesApi } from '@mantine/core';\nimport { useDatesState } from '../../hooks/use-dates-state/use-dates-state.mjs';\nimport '@mantine/hooks';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport 'dayjs';\nimport { shiftTimezone } from '../../utils/shift-timezone.mjs';\nimport 'react';\nimport { Calendar } from '../Calendar/Calendar.mjs';\n\nconst defaultProps = {\n type: \"default\",\n defaultLevel: \"month\",\n numberOfColumns: 1\n};\nconst DatePicker = factory((_props, ref) => {\n const props = useProps(\"DatePicker\", defaultProps, _props);\n const {\n classNames,\n styles,\n vars,\n type,\n defaultValue,\n value,\n onChange,\n __staticSelector,\n getDayProps,\n allowSingleDateInRange,\n allowDeselect,\n onMouseLeave,\n numberOfColumns,\n hideOutsideDates,\n __onDayMouseEnter,\n __onDayClick,\n __timezoneApplied,\n ...others\n } = props;\n const { onDateChange, onRootMouseLeave, onHoveredDateChange, getControlProps } = useDatesState({\n type,\n level: \"day\",\n allowDeselect,\n allowSingleDateInRange,\n value,\n defaultValue,\n onChange,\n onMouseLeave,\n applyTimezone: !__timezoneApplied\n });\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n const ctx = useDatesContext();\n return /* @__PURE__ */ jsx(\n Calendar,\n {\n ref,\n minLevel: \"month\",\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n __staticSelector: __staticSelector || \"DatePicker\",\n onMouseLeave: onRootMouseLeave,\n numberOfColumns,\n hideOutsideDates: hideOutsideDates ?? numberOfColumns !== 1,\n __onDayMouseEnter: (_event, date) => {\n onHoveredDateChange(date);\n __onDayMouseEnter?.(_event, date);\n },\n __onDayClick: (_event, date) => {\n onDateChange(date);\n __onDayClick?.(_event, date);\n },\n getDayProps: (date) => ({\n ...getControlProps(date),\n ...getDayProps?.(date)\n }),\n ...others,\n date: shiftTimezone(\"add\", others.date, ctx.getTimezone(), __timezoneApplied),\n __timezoneApplied: true\n }\n );\n});\nDatePicker.classes = Calendar.classes;\nDatePicker.displayName = \"@mantine/dates/DatePicker\";\n\nexport { DatePicker };\n//# sourceMappingURL=DatePicker.mjs.map\n","'use client';\nimport { useDisclosure } from '@mantine/hooks';\nimport '../../components/DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../../components/DatesProvider/use-dates-context.mjs';\nimport { getFormattedDate } from '../../utils/get-formatted-date.mjs';\nimport 'dayjs';\nimport '../../utils/get-timezone-offset.mjs';\nimport { useUncontrolledDates } from '../use-uncontrolled-dates/use-uncontrolled-dates.mjs';\n\nfunction useDatesInput({\n type,\n value,\n defaultValue,\n onChange,\n locale,\n format,\n closeOnChange,\n sortDates,\n labelSeparator,\n valueFormatter\n}) {\n const ctx = useDatesContext();\n const [dropdownOpened, dropdownHandlers] = useDisclosure(false);\n const [_value, _setValue] = useUncontrolledDates({\n type,\n value,\n defaultValue,\n onChange\n });\n const formattedValue = getFormattedDate({\n type,\n date: _value,\n locale: ctx.getLocale(locale),\n format,\n labelSeparator: ctx.getLabelSeparator(labelSeparator),\n formatter: valueFormatter\n });\n const setValue = (val) => {\n if (closeOnChange) {\n if (type === \"default\") {\n dropdownHandlers.close();\n }\n if (type === \"range\" && val[0] && val[1]) {\n dropdownHandlers.close();\n }\n }\n if (sortDates && type === \"multiple\") {\n _setValue([...val].sort((a, b) => a.getTime() - b.getTime()));\n } else {\n _setValue(val);\n }\n };\n const onClear = () => setValue(type === \"range\" ? [null, null] : type === \"multiple\" ? [] : null);\n const shouldClear = type === \"range\" ? !!_value[0] : type === \"multiple\" ? _value.length > 0 : _value !== null;\n return {\n _value,\n setValue,\n onClear,\n shouldClear,\n formattedValue,\n dropdownOpened,\n dropdownHandlers\n };\n}\n\nexport { useDatesInput };\n//# sourceMappingURL=use-dates-input.mjs.map\n","'use client';\nimport { jsx } from 'react/jsx-runtime';\nimport { factory, useProps, useResolvedStylesApi } from '@mantine/core';\nimport 'dayjs';\nimport 'react';\nimport '@mantine/hooks';\nimport '../DatesProvider/DatesProvider.mjs';\nimport { useDatesContext } from '../DatesProvider/use-dates-context.mjs';\nimport { getDefaultClampedDate } from '../../utils/get-default-clamped-date.mjs';\nimport { shiftTimezone } from '../../utils/shift-timezone.mjs';\nimport { useDatesInput } from '../../hooks/use-dates-input/use-dates-input.mjs';\nimport '../Calendar/Calendar.mjs';\nimport { pickCalendarProps } from '../Calendar/pick-calendar-levels-props/pick-calendar-levels-props.mjs';\nimport { DatePicker } from '../DatePicker/DatePicker.mjs';\nimport { PickerInputBase } from '../PickerInputBase/PickerInputBase.mjs';\n\nconst defaultProps = {\n type: \"default\",\n valueFormat: \"MMMM D, YYYY\",\n closeOnChange: true,\n sortDates: true,\n dropdownType: \"popover\"\n};\nconst DatePickerInput = factory(\n (_props, ref) => {\n const props = useProps(\"DatePickerInput\", defaultProps, _props);\n const {\n type,\n value,\n defaultValue,\n onChange,\n valueFormat,\n labelSeparator,\n locale,\n classNames,\n styles,\n unstyled,\n closeOnChange,\n size,\n variant,\n dropdownType,\n sortDates,\n minDate,\n maxDate,\n vars,\n defaultDate,\n valueFormatter,\n ...rest\n } = props;\n const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({\n classNames,\n styles,\n props\n });\n const { calendarProps, others } = pickCalendarProps(rest);\n const {\n _value,\n setValue,\n formattedValue,\n dropdownHandlers,\n dropdownOpened,\n onClear,\n shouldClear\n } = useDatesInput({\n type,\n value,\n defaultValue,\n onChange,\n locale,\n format: valueFormat,\n labelSeparator,\n closeOnChange,\n sortDates,\n valueFormatter\n });\n const _defaultDate = Array.isArray(_value) ? _value[0] || defaultDate : _value || defaultDate;\n const ctx = useDatesContext();\n return /* @__PURE__ */ jsx(\n PickerInputBase,\n {\n formattedValue,\n dropdownOpened,\n dropdownHandlers,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n ref,\n onClear,\n shouldClear,\n value: _value,\n size,\n variant,\n dropdownType,\n ...others,\n type,\n __staticSelector: \"DatePickerInput\",\n children: /* @__PURE__ */ jsx(\n DatePicker,\n {\n ...calendarProps,\n size,\n variant,\n type,\n value: _value,\n defaultDate: _defaultDate || getDefaultClampedDate({ maxDate, minDate, timezone: ctx.getTimezone() }),\n onChange: setValue,\n locale,\n classNames: resolvedClassNames,\n styles: resolvedStyles,\n unstyled,\n __staticSelector: \"DatePickerInput\",\n __stopPropagation: dropdownType === \"popover\",\n minDate,\n maxDate,\n date: shiftTimezone(\"add\", calendarProps.date, ctx.getTimezone()),\n __timezoneApplied: true\n }\n )\n }\n );\n }\n);\nDatePickerInput.classes = { ...PickerInputBase.classes, ...DatePicker.classes };\nDatePickerInput.displayName = \"@mantine/dates/DatePickerInput\";\n\nexport { DatePickerInput };\n//# sourceMappingURL=DatePickerInput.mjs.map\n","import { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { createContext, useContext, memo, useState, useRef, useEffect, PureComponent, useMemo, Children, isValidElement, cloneElement, createRef } from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { createPortal } from 'react-dom';\n\nfunction _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\n\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\n\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n\nfunction _defineProperty(e, r, t) {\n return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\n\nfunction getDefaultExportFromCjs$1 (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\n/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nvar invariant_1;\nvar hasRequiredInvariant;\nfunction requireInvariant() {\n if (hasRequiredInvariant) return invariant_1;\n hasRequiredInvariant = 1;\n\n /**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\n var NODE_ENV = process.env.NODE_ENV;\n var invariant = function invariant(condition, format, a, b, c, d, e, f) {\n if (NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error(format.replace(/%s/g, function () {\n return args[argIndex++];\n }));\n error.name = 'Invariant Violation';\n }\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n };\n invariant_1 = invariant;\n return invariant_1;\n}\n\nvar invariantExports = requireInvariant();\nvar invariant = /*@__PURE__*/getDefaultExportFromCjs$1(invariantExports);\n\nvar MapContext = createContext(null);\nfunction useGoogleMap() {\n invariant(!!useContext, 'useGoogleMap is React hook and requires React version 16.8+');\n var map = useContext(MapContext);\n invariant(!!map, 'useGoogleMap needs a GoogleMap available up in the tree');\n return map;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction reduce(obj, fn, acc) {\n return Object.keys(obj).reduce(function reducer(newAcc, key) {\n return fn(newAcc, obj[key], key);\n }, acc);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction forEach(obj, fn) {\n Object.keys(obj).forEach(key => {\n return fn(obj[key], key);\n });\n}\n\n/* global google */\n/* eslint-disable filenames/match-regex */\nfunction applyUpdaterToNextProps(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nupdaterMap,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nprevProps,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nnextProps,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninstance\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n var map = {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n var iter = (fn, key) => {\n var nextValue = nextProps[key];\n if (nextValue !== prevProps[key]) {\n map[key] = nextValue;\n fn(instance, nextValue);\n }\n };\n forEach(updaterMap, iter);\n return map;\n}\nfunction registerEvents(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nprops,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninstance, eventMap) {\n var registeredList = reduce(eventMap, function reducer(acc, googleEventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onEventName) {\n if (typeof props[onEventName] === 'function') {\n acc.push(google.maps.event.addListener(instance, googleEventName, props[onEventName]));\n }\n return acc;\n }, []);\n return registeredList;\n}\nfunction unregisterEvent(registered) {\n google.maps.event.removeListener(registered);\n}\nfunction unregisterEvents() {\n var events = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n events.forEach(unregisterEvent);\n}\nfunction applyUpdatersToPropsAndRegisterEvents(_ref) {\n var {\n updaterMap,\n eventMap,\n prevProps,\n nextProps,\n instance\n } = _ref;\n var registeredEvents = registerEvents(nextProps, instance, eventMap);\n applyUpdaterToNextProps(updaterMap, prevProps, nextProps, instance);\n return registeredEvents;\n}\n\nvar eventMap$i = {\n onDblClick: 'dblclick',\n onDragEnd: 'dragend',\n onDragStart: 'dragstart',\n onMapTypeIdChanged: 'maptypeid_changed',\n onMouseMove: 'mousemove',\n onMouseOut: 'mouseout',\n onMouseOver: 'mouseover',\n onMouseDown: 'mousedown',\n onMouseUp: 'mouseup',\n onRightClick: 'rightclick',\n onTilesLoaded: 'tilesloaded',\n onBoundsChanged: 'bounds_changed',\n onCenterChanged: 'center_changed',\n onClick: 'click',\n onDrag: 'drag',\n onHeadingChanged: 'heading_changed',\n onIdle: 'idle',\n onProjectionChanged: 'projection_changed',\n onResize: 'resize',\n onTiltChanged: 'tilt_changed',\n onZoomChanged: 'zoom_changed'\n};\nvar updaterMap$i = {\n extraMapTypes(map, extra) {\n extra.forEach(function forEachExtra(it, i) {\n map.mapTypes.set(String(i), it);\n });\n },\n center(map, center) {\n map.setCenter(center);\n },\n clickableIcons(map, clickable) {\n map.setClickableIcons(clickable);\n },\n heading(map, heading) {\n map.setHeading(heading);\n },\n mapTypeId(map, mapTypeId) {\n map.setMapTypeId(mapTypeId);\n },\n options(map, options) {\n map.setOptions(options);\n },\n streetView(map, streetView) {\n map.setStreetView(streetView);\n },\n tilt(map, tilt) {\n map.setTilt(tilt);\n },\n zoom(map, zoom) {\n map.setZoom(zoom);\n }\n};\n// TODO: unfinished!\nfunction GoogleMapFunctional(_ref) {\n var {\n children,\n options,\n id,\n mapContainerStyle,\n mapContainerClassName,\n center,\n // clickableIcons,\n // extraMapTypes,\n // heading,\n // mapTypeId,\n onClick,\n onDblClick,\n onDrag,\n onDragEnd,\n onDragStart,\n onMouseMove,\n onMouseOut,\n onMouseOver,\n onMouseDown,\n onMouseUp,\n onRightClick,\n // onMapTypeIdChanged,\n // onTilesLoaded,\n // onBoundsChanged,\n onCenterChanged,\n // onHeadingChanged,\n // onIdle,\n // onProjectionChanged,\n // onResize,\n // onTiltChanged,\n // onZoomChanged,\n onLoad,\n onUnmount\n } = _ref;\n var [map, setMap] = useState(null);\n var ref = useRef(null);\n // const [extraMapTypesListener, setExtraMapTypesListener] = useState(null)\n var [centerChangedListener, setCenterChangedListener] = useState(null);\n var [dblclickListener, setDblclickListener] = useState(null);\n var [dragendListener, setDragendListener] = useState(null);\n var [dragstartListener, setDragstartListener] = useState(null);\n var [mousedownListener, setMousedownListener] = useState(null);\n var [mousemoveListener, setMousemoveListener] = useState(null);\n var [mouseoutListener, setMouseoutListener] = useState(null);\n var [mouseoverListener, setMouseoverListener] = useState(null);\n var [mouseupListener, setMouseupListener] = useState(null);\n var [rightclickListener, setRightclickListener] = useState(null);\n var [clickListener, setClickListener] = useState(null);\n var [dragListener, setDragListener] = useState(null);\n // Order does matter\n useEffect(() => {\n if (options && map !== null) {\n map.setOptions(options);\n }\n }, [map, options]);\n useEffect(() => {\n if (map !== null && typeof center !== 'undefined') {\n map.setCenter(center);\n }\n }, [map, center]);\n useEffect(() => {\n if (map && onDblClick) {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n setDblclickListener(google.maps.event.addListener(map, 'dblclick', onDblClick));\n }\n }, [onDblClick]);\n useEffect(() => {\n if (map && onDragEnd) {\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n setDragendListener(google.maps.event.addListener(map, 'dragend', onDragEnd));\n }\n }, [onDragEnd]);\n useEffect(() => {\n if (map && onDragStart) {\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n setDragstartListener(google.maps.event.addListener(map, 'dragstart', onDragStart));\n }\n }, [onDragStart]);\n useEffect(() => {\n if (map && onMouseDown) {\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n setMousedownListener(google.maps.event.addListener(map, 'mousedown', onMouseDown));\n }\n }, [onMouseDown]);\n useEffect(() => {\n if (map && onMouseMove) {\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n setMousemoveListener(google.maps.event.addListener(map, 'mousemove', onMouseMove));\n }\n }, [onMouseMove]);\n useEffect(() => {\n if (map && onMouseOut) {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n setMouseoutListener(google.maps.event.addListener(map, 'mouseout', onMouseOut));\n }\n }, [onMouseOut]);\n useEffect(() => {\n if (map && onMouseOver) {\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n setMouseoverListener(google.maps.event.addListener(map, 'mouseover', onMouseOver));\n }\n }, [onMouseOver]);\n useEffect(() => {\n if (map && onMouseUp) {\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n setMouseupListener(google.maps.event.addListener(map, 'mouseup', onMouseUp));\n }\n }, [onMouseUp]);\n useEffect(() => {\n if (map && onRightClick) {\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n setRightclickListener(google.maps.event.addListener(map, 'rightclick', onRightClick));\n }\n }, [onRightClick]);\n useEffect(() => {\n if (map && onClick) {\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n setClickListener(google.maps.event.addListener(map, 'click', onClick));\n }\n }, [onClick]);\n useEffect(() => {\n if (map && onDrag) {\n if (dragListener !== null) {\n google.maps.event.removeListener(dragListener);\n }\n setDragListener(google.maps.event.addListener(map, 'drag', onDrag));\n }\n }, [onDrag]);\n useEffect(() => {\n if (map && onCenterChanged) {\n if (centerChangedListener !== null) {\n google.maps.event.removeListener(centerChangedListener);\n }\n setCenterChangedListener(google.maps.event.addListener(map, 'center_changed', onCenterChanged));\n }\n }, [onClick]);\n useEffect(() => {\n var map = ref.current === null ? null : new google.maps.Map(ref.current, options);\n setMap(map);\n if (map !== null && onLoad) {\n onLoad(map);\n }\n return () => {\n if (map !== null) {\n if (onUnmount) {\n onUnmount(map);\n }\n }\n };\n }, []);\n return jsx(\"div\", {\n id: id,\n ref: ref,\n style: mapContainerStyle,\n className: mapContainerClassName,\n children: jsx(MapContext.Provider, {\n value: map,\n children: map !== null ? children : null\n })\n });\n}\nmemo(GoogleMapFunctional);\nclass GoogleMap extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n map: null\n });\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"mapRef\", null);\n _defineProperty(this, \"getInstance\", () => {\n if (this.mapRef === null) {\n return null;\n }\n return new google.maps.Map(this.mapRef, this.props.options);\n });\n _defineProperty(this, \"panTo\", latLng => {\n var map = this.getInstance();\n if (map) {\n map.panTo(latLng);\n }\n });\n _defineProperty(this, \"setMapCallback\", () => {\n if (this.state.map !== null) {\n if (this.props.onLoad) {\n this.props.onLoad(this.state.map);\n }\n }\n });\n _defineProperty(this, \"getRef\", ref => {\n this.mapRef = ref;\n });\n }\n componentDidMount() {\n var map = this.getInstance();\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$i,\n eventMap: eventMap$i,\n prevProps: {},\n nextProps: this.props,\n instance: map\n });\n this.setState(function setMap() {\n return {\n map\n };\n }, this.setMapCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.map !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$i,\n eventMap: eventMap$i,\n prevProps,\n nextProps: this.props,\n instance: this.state.map\n });\n }\n }\n componentWillUnmount() {\n if (this.state.map !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.map);\n }\n unregisterEvents(this.registeredEvents);\n }\n }\n render() {\n return jsx(\"div\", {\n id: this.props.id,\n ref: this.getRef,\n style: this.props.mapContainerStyle,\n className: this.props.mapContainerClassName,\n children: jsx(MapContext.Provider, {\n value: this.state.map,\n children: this.state.map !== null ? this.props.children : null\n })\n });\n }\n}\n\nfunction asyncGeneratorStep(n, t, e, r, o, a, c) {\n try {\n var i = n[a](c),\n u = i.value;\n } catch (n) {\n return void e(n);\n }\n i.done ? t(u) : Promise.resolve(u).then(r, o);\n}\nfunction _asyncToGenerator(n) {\n return function () {\n var t = this,\n e = arguments;\n return new Promise(function (r, o) {\n var a = n.apply(t, e);\n function _next(n) {\n asyncGeneratorStep(a, r, o, _next, _throw, \"next\", n);\n }\n function _throw(n) {\n asyncGeneratorStep(a, r, o, _next, _throw, \"throw\", n);\n }\n _next(void 0);\n });\n };\n}\n\nfunction makeLoadScriptUrl(_ref) {\n var {\n googleMapsApiKey,\n googleMapsClientId,\n version = 'weekly',\n language,\n region,\n libraries,\n channel,\n mapIds,\n authReferrerPolicy\n } = _ref;\n var params = [];\n invariant(googleMapsApiKey && googleMapsClientId || !(googleMapsApiKey && googleMapsClientId), 'You need to specify either googleMapsApiKey or googleMapsClientId for @react-google-maps/api load script to work. You cannot use both at the same time.');\n if (googleMapsApiKey) {\n params.push(\"key=\".concat(googleMapsApiKey));\n } else if (googleMapsClientId) {\n params.push(\"client=\".concat(googleMapsClientId));\n }\n if (version) {\n params.push(\"v=\".concat(version));\n }\n if (language) {\n params.push(\"language=\".concat(language));\n }\n if (region) {\n params.push(\"region=\".concat(region));\n }\n if (libraries && libraries.length) {\n params.push(\"libraries=\".concat(libraries.sort().join(',')));\n }\n if (channel) {\n params.push(\"channel=\".concat(channel));\n }\n if (mapIds && mapIds.length) {\n params.push(\"map_ids=\".concat(mapIds.join(',')));\n }\n if (authReferrerPolicy) {\n params.push(\"auth_referrer_policy=\".concat(authReferrerPolicy));\n }\n params.push('loading=async');\n params.push('callback=initMap');\n return \"https://maps.googleapis.com/maps/api/js?\".concat(params.join('&'));\n}\n\nvar isBrowser = typeof document !== 'undefined';\n\nfunction injectScript(_ref) {\n var {\n url,\n id,\n nonce\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } = _ref;\n if (!isBrowser) {\n return Promise.reject(new Error('document is undefined'));\n }\n return new Promise(function injectScriptCallback(resolve, reject) {\n var existingScript = document.getElementById(id);\n var windowWithGoogleMap = window;\n if (existingScript) {\n // Same script id/url: keep same script\n var dataStateAttribute = existingScript.getAttribute('data-state');\n if (existingScript.src === url && dataStateAttribute !== 'error') {\n if (dataStateAttribute === 'ready') {\n return resolve(id);\n } else {\n var originalInitMap = windowWithGoogleMap.initMap;\n var originalErrorCallback = existingScript.onerror;\n windowWithGoogleMap.initMap = function initMap() {\n if (originalInitMap) {\n originalInitMap();\n }\n resolve(id);\n };\n existingScript.onerror = function (err) {\n if (originalErrorCallback) {\n originalErrorCallback(err);\n }\n reject(err);\n };\n return;\n }\n }\n // Same script id, but either\n // 1. requested URL is different\n // 2. script failed to load\n else {\n existingScript.remove();\n }\n }\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = url;\n script.id = id;\n script.async = true;\n script.nonce = nonce || '';\n script.onerror = function onerror(err) {\n script.setAttribute('data-state', 'error');\n reject(err);\n };\n windowWithGoogleMap.initMap = function onload() {\n script.setAttribute('data-state', 'ready');\n resolve(id);\n };\n document.head.appendChild(script);\n }).catch(err => {\n console.error('injectScript error: ', err);\n throw err;\n });\n}\n\nfunction isGoogleFontStyle(element) {\n // 'Roboto' or 'Google Sans Text' font download\n var href = element.href;\n if (href && (href.indexOf('https://fonts.googleapis.com/css?family=Roboto') === 0 || href.indexOf('https://fonts.googleapis.com/css?family=Google+Sans+Text') === 0)) {\n return true;\n }\n // font style elements\n if (\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.tagName.toLowerCase() === 'style' &&\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.styleSheet &&\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.styleSheet.cssText &&\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.styleSheet.cssText.replace('\\r\\n', '').indexOf('.gm-style') === 0) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.styleSheet.cssText = '';\n return true;\n }\n // font style elements for other browsers\n if (\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.tagName.toLowerCase() === 'style' &&\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.innerHTML &&\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.innerHTML.replace('\\r\\n', '').indexOf('.gm-style') === 0) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.innerHTML = '';\n return true;\n }\n // when google tries to add empty style\n if (\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n element.tagName.toLowerCase() === 'style' &&\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n !element.styleSheet &&\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n !element.innerHTML) {\n return true;\n }\n return false;\n}\n// Preventing the Google Maps library from downloading an extra font\nfunction preventGoogleFonts() {\n // we override these methods only for one particular head element\n // default methods for other elements are not affected\n var head = document.getElementsByTagName('head')[0];\n if (head) {\n var trueInsertBefore = head.insertBefore.bind(head);\n // TODO: adding return before reflect solves the TS issue\n head.insertBefore = function insertBefore(newElement, referenceElement) {\n if (!isGoogleFontStyle(newElement)) {\n Reflect.apply(trueInsertBefore, head, [newElement, referenceElement]);\n }\n return newElement;\n };\n var trueAppend = head.appendChild.bind(head);\n // TODO: adding return before reflect solves the TS issue\n head.appendChild = function appendChild(textNode) {\n if (!isGoogleFontStyle(textNode)) {\n Reflect.apply(trueAppend, head, [textNode]);\n }\n return textNode;\n };\n }\n}\n\nvar cleaningUp = false;\nfunction DefaultLoadingElement() {\n return jsx(\"div\", {\n children: \"Loading...\"\n });\n}\nvar defaultLoadScriptProps = {\n id: 'script-loader',\n version: 'weekly'\n};\nclass LoadScript extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"check\", null);\n _defineProperty(this, \"state\", {\n loaded: false\n });\n _defineProperty(this, \"cleanupCallback\", () => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n delete window.google.maps;\n this.injectScript();\n });\n _defineProperty(this, \"isCleaningUp\", /*#__PURE__*/_asyncToGenerator(function* () {\n function promiseCallback(resolve) {\n if (!cleaningUp) {\n resolve();\n } else {\n if (isBrowser) {\n var timer = window.setInterval(function interval() {\n if (!cleaningUp) {\n window.clearInterval(timer);\n resolve();\n }\n }, 1);\n }\n }\n return;\n }\n return new Promise(promiseCallback);\n }));\n _defineProperty(this, \"cleanup\", () => {\n cleaningUp = true;\n var script = document.getElementById(this.props.id);\n if (script && script.parentNode) {\n script.parentNode.removeChild(script);\n }\n Array.prototype.slice.call(document.getElementsByTagName('script')).filter(function filter(script) {\n return typeof script.src === 'string' && script.src.includes('maps.googleapis');\n }).forEach(function forEach(script) {\n if (script.parentNode) {\n script.parentNode.removeChild(script);\n }\n });\n Array.prototype.slice.call(document.getElementsByTagName('link')).filter(function filter(link) {\n return link.href === 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Google+Sans';\n }).forEach(function forEach(link) {\n if (link.parentNode) {\n link.parentNode.removeChild(link);\n }\n });\n Array.prototype.slice.call(document.getElementsByTagName('style')).filter(function filter(style) {\n return style.innerText !== undefined && style.innerText.length > 0 && style.innerText.includes('.gm-');\n }).forEach(function forEach(style) {\n if (style.parentNode) {\n style.parentNode.removeChild(style);\n }\n });\n });\n _defineProperty(this, \"injectScript\", () => {\n if (this.props.preventGoogleFontsLoading) {\n preventGoogleFonts();\n }\n invariant(!!this.props.id, 'LoadScript requires \"id\" prop to be a string: %s', this.props.id);\n var injectScriptOptions = {\n id: this.props.id,\n nonce: this.props.nonce,\n url: makeLoadScriptUrl(this.props)\n };\n injectScript(injectScriptOptions).then(() => {\n if (this.props.onLoad) {\n this.props.onLoad();\n }\n this.setState(function setLoaded() {\n return {\n loaded: true\n };\n });\n return;\n }).catch(err => {\n if (this.props.onError) {\n this.props.onError(err);\n }\n console.error(\"\\n There has been an Error with loading Google Maps API script, please check that you provided correct google API key (\".concat(this.props.googleMapsApiKey || '-', \") or Client ID (\").concat(this.props.googleMapsClientId || '-', \") to \\n Otherwise it is a Network issue.\\n \"));\n });\n });\n _defineProperty(this, \"getRef\", el => {\n this.check = el;\n });\n }\n componentDidMount() {\n if (isBrowser) {\n if (window.google && window.google.maps && !cleaningUp) {\n console.error('google api is already presented');\n return;\n }\n this.isCleaningUp().then(this.injectScript).catch(function error(err) {\n console.error('Error at injecting script after cleaning up: ', err);\n });\n }\n }\n componentDidUpdate(prevProps) {\n if (this.props.libraries !== prevProps.libraries) {\n console.warn('Performance warning! LoadScript has been reloaded unintentionally! You should not pass `libraries` prop as new array. Please keep an array of libraries as static class property for Components and PureComponents, or just a const variable outside of component, or somewhere in config files or ENV variables');\n }\n if (isBrowser && prevProps.language !== this.props.language) {\n this.cleanup();\n // TODO: refactor to use gDSFP maybe... wait for hooks refactoring.\n this.setState(function setLoaded() {\n return {\n loaded: false\n };\n }, this.cleanupCallback);\n }\n }\n componentWillUnmount() {\n if (isBrowser) {\n this.cleanup();\n var timeoutCallback = () => {\n if (!this.check) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n delete window.google;\n cleaningUp = false;\n }\n };\n window.setTimeout(timeoutCallback, 1);\n if (this.props.onUnmount) {\n this.props.onUnmount();\n }\n }\n }\n render() {\n return jsxs(Fragment, {\n children: [jsx(\"div\", {\n ref: this.getRef\n }), this.state.loaded ? this.props.children : this.props.loadingElement || jsx(DefaultLoadingElement, {})]\n });\n }\n}\n_defineProperty(LoadScript, \"defaultProps\", defaultLoadScriptProps);\n\nfunction _objectWithoutPropertiesLoose(r, e) {\n if (null == r) return {};\n var t = {};\n for (var n in r) if ({}.hasOwnProperty.call(r, n)) {\n if (e.includes(n)) continue;\n t[n] = r[n];\n }\n return t;\n}\n\nfunction _objectWithoutProperties(e, t) {\n if (null == e) return {};\n var o,\n r,\n i = _objectWithoutPropertiesLoose(e, t);\n if (Object.getOwnPropertySymbols) {\n var s = Object.getOwnPropertySymbols(e);\n for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);\n }\n return i;\n}\n\n/* eslint-disable filenames/match-regex */\nvar previouslyLoadedUrl;\nfunction useLoadScript(_ref) {\n var {\n id = defaultLoadScriptProps.id,\n version = defaultLoadScriptProps.version,\n nonce,\n googleMapsApiKey,\n googleMapsClientId,\n language,\n region,\n libraries,\n preventGoogleFontsLoading,\n channel,\n mapIds,\n authReferrerPolicy\n } = _ref;\n var isMounted = useRef(false);\n var [isLoaded, setLoaded] = useState(false);\n var [loadError, setLoadError] = useState(undefined);\n useEffect(function trackMountedState() {\n isMounted.current = true;\n return () => {\n isMounted.current = false;\n };\n }, []);\n useEffect(function applyPreventGoogleFonts() {\n if (isBrowser && preventGoogleFontsLoading) {\n preventGoogleFonts();\n }\n }, [preventGoogleFontsLoading]);\n useEffect(function validateLoadedState() {\n if (isLoaded) {\n invariant(!!window.google, 'useLoadScript was marked as loaded, but window.google is not present. Something went wrong.');\n }\n }, [isLoaded]);\n var url = makeLoadScriptUrl({\n version,\n googleMapsApiKey,\n googleMapsClientId,\n language,\n region,\n libraries,\n channel,\n mapIds,\n authReferrerPolicy\n });\n useEffect(function loadScriptAndModifyLoadedState() {\n if (!isBrowser) {\n return;\n }\n function setLoadedIfMounted() {\n if (isMounted.current) {\n setLoaded(true);\n previouslyLoadedUrl = url;\n }\n }\n if (window.google && window.google.maps && previouslyLoadedUrl === url) {\n setLoadedIfMounted();\n return;\n }\n injectScript({\n id,\n url,\n nonce\n }).then(setLoadedIfMounted).catch(function handleInjectError(err) {\n if (isMounted.current) {\n setLoadError(err);\n }\n console.warn(\"\\n There has been an Error with loading Google Maps API script, please check that you provided correct google API key (\".concat(googleMapsApiKey || '-', \") or Client ID (\").concat(googleMapsClientId || '-', \")\\n Otherwise it is a Network issue.\\n \"));\n console.error(err);\n });\n }, [id, url, nonce]);\n var prevLibraries = useRef(undefined);\n useEffect(function checkPerformance() {\n if (prevLibraries.current && libraries !== prevLibraries.current) {\n console.warn('Performance warning! LoadScript has been reloaded unintentionally! You should not pass `libraries` prop as new array. Please keep an array of libraries as static class property for Components and PureComponents, or just a const variable outside of component, or somewhere in config files or ENV variables');\n }\n prevLibraries.current = libraries;\n }, [libraries]);\n return {\n isLoaded,\n loadError,\n url\n };\n}\n\nvar _excluded$1 = [\"loadingElement\", \"onLoad\", \"onError\", \"onUnmount\", \"children\"];\nvar defaultLoadingElement = jsx(DefaultLoadingElement, {});\nfunction LoadScriptNext(_ref) {\n var {\n loadingElement,\n onLoad,\n onError,\n onUnmount,\n children\n } = _ref,\n hookOptions = _objectWithoutProperties(_ref, _excluded$1);\n var {\n isLoaded,\n loadError\n } = useLoadScript(hookOptions);\n useEffect(function handleOnLoad() {\n if (isLoaded && typeof onLoad === 'function') {\n onLoad();\n }\n }, [isLoaded, onLoad]);\n useEffect(function handleOnError() {\n if (loadError && typeof onError === 'function') {\n onError(loadError);\n }\n }, [loadError, onError]);\n useEffect(function handleOnUnmount() {\n return () => {\n if (onUnmount) {\n onUnmount();\n }\n };\n }, [onUnmount]);\n return isLoaded ? children : loadingElement || defaultLoadingElement;\n}\nvar LoadScriptNext$1 = memo(LoadScriptNext);\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nfunction __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) {\n return value instanceof P ? value : new P(function (resolve) {\n resolve(value);\n });\n }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) {\n try {\n step(generator.next(value));\n } catch (e) {\n reject(e);\n }\n }\n function rejected(value) {\n try {\n step(generator[\"throw\"](value));\n } catch (e) {\n reject(e);\n }\n }\n function step(result) {\n result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);\n }\n step((generator = generator.apply(thisArg, [])).next());\n });\n}\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\nfunction getDefaultExportFromCjs(x) {\n return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\n// do not edit .js files directly - edit src/index.jst\n\nvar fastDeepEqual$1 = function equal(a, b) {\n if (a === b) return true;\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;\n return true;\n }\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n if (!equal(a[key], b[key])) return false;\n }\n return true;\n }\n\n // true if both NaN, false otherwise\n return a !== a && b !== b;\n};\nvar isEqual = /*@__PURE__*/getDefaultExportFromCjs(fastDeepEqual$1);\n\n/**\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at.\n *\n * Http://www.apache.org/licenses/LICENSE-2.0.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar DEFAULT_ID = \"__googleMapsScriptId\";\n/**\n * The status of the [[Loader]].\n */\nvar LoaderStatus;\n(function (LoaderStatus) {\n LoaderStatus[LoaderStatus[\"INITIALIZED\"] = 0] = \"INITIALIZED\";\n LoaderStatus[LoaderStatus[\"LOADING\"] = 1] = \"LOADING\";\n LoaderStatus[LoaderStatus[\"SUCCESS\"] = 2] = \"SUCCESS\";\n LoaderStatus[LoaderStatus[\"FAILURE\"] = 3] = \"FAILURE\";\n})(LoaderStatus || (LoaderStatus = {}));\n/**\n * [[Loader]] makes it easier to add Google Maps JavaScript API to your application\n * dynamically using\n * [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n * It works by dynamically creating and appending a script node to the the\n * document head and wrapping the callback function so as to return a promise.\n *\n * ```\n * const loader = new Loader({\n * apiKey: \"\",\n * version: \"weekly\",\n * libraries: [\"places\"]\n * });\n *\n * loader.load().then((google) => {\n * const map = new google.maps.Map(...)\n * })\n * ```\n */\nclass Loader {\n /**\n * Creates an instance of Loader using [[LoaderOptions]]. No defaults are set\n * using this library, instead the defaults are set by the Google Maps\n * JavaScript API server.\n *\n * ```\n * const loader = Loader({apiKey, version: 'weekly', libraries: ['places']});\n * ```\n */\n constructor(_ref) {\n var {\n apiKey,\n authReferrerPolicy,\n channel,\n client,\n id = DEFAULT_ID,\n language,\n libraries = [],\n mapIds,\n nonce,\n region,\n retries = 3,\n url = \"https://maps.googleapis.com/maps/api/js\",\n version\n } = _ref;\n this.callbacks = [];\n this.done = false;\n this.loading = false;\n this.errors = [];\n this.apiKey = apiKey;\n this.authReferrerPolicy = authReferrerPolicy;\n this.channel = channel;\n this.client = client;\n this.id = id || DEFAULT_ID; // Do not allow empty string\n this.language = language;\n this.libraries = libraries;\n this.mapIds = mapIds;\n this.nonce = nonce;\n this.region = region;\n this.retries = retries;\n this.url = url;\n this.version = version;\n if (Loader.instance) {\n if (!isEqual(this.options, Loader.instance.options)) {\n throw new Error(\"Loader must not be called again with different options. \".concat(JSON.stringify(this.options), \" !== \").concat(JSON.stringify(Loader.instance.options)));\n }\n return Loader.instance;\n }\n Loader.instance = this;\n }\n get options() {\n return {\n version: this.version,\n apiKey: this.apiKey,\n channel: this.channel,\n client: this.client,\n id: this.id,\n libraries: this.libraries,\n language: this.language,\n region: this.region,\n mapIds: this.mapIds,\n nonce: this.nonce,\n url: this.url,\n authReferrerPolicy: this.authReferrerPolicy\n };\n }\n get status() {\n if (this.errors.length) {\n return LoaderStatus.FAILURE;\n }\n if (this.done) {\n return LoaderStatus.SUCCESS;\n }\n if (this.loading) {\n return LoaderStatus.LOADING;\n }\n return LoaderStatus.INITIALIZED;\n }\n get failed() {\n return this.done && !this.loading && this.errors.length >= this.retries + 1;\n }\n /**\n * CreateUrl returns the Google Maps JavaScript API script url given the [[LoaderOptions]].\n *\n * @ignore\n * @deprecated\n */\n createUrl() {\n var url = this.url;\n url += \"?callback=__googleMapsCallback&loading=async\";\n if (this.apiKey) {\n url += \"&key=\".concat(this.apiKey);\n }\n if (this.channel) {\n url += \"&channel=\".concat(this.channel);\n }\n if (this.client) {\n url += \"&client=\".concat(this.client);\n }\n if (this.libraries.length > 0) {\n url += \"&libraries=\".concat(this.libraries.join(\",\"));\n }\n if (this.language) {\n url += \"&language=\".concat(this.language);\n }\n if (this.region) {\n url += \"®ion=\".concat(this.region);\n }\n if (this.version) {\n url += \"&v=\".concat(this.version);\n }\n if (this.mapIds) {\n url += \"&map_ids=\".concat(this.mapIds.join(\",\"));\n }\n if (this.authReferrerPolicy) {\n url += \"&auth_referrer_policy=\".concat(this.authReferrerPolicy);\n }\n return url;\n }\n deleteScript() {\n var script = document.getElementById(this.id);\n if (script) {\n script.remove();\n }\n }\n /**\n * Load the Google Maps JavaScript API script and return a Promise.\n * @deprecated, use importLibrary() instead.\n */\n load() {\n return this.loadPromise();\n }\n /**\n * Load the Google Maps JavaScript API script and return a Promise.\n *\n * @ignore\n * @deprecated, use importLibrary() instead.\n */\n loadPromise() {\n return new Promise((resolve, reject) => {\n this.loadCallback(err => {\n if (!err) {\n resolve(window.google);\n } else {\n reject(err.error);\n }\n });\n });\n }\n importLibrary(name) {\n this.execute();\n return google.maps.importLibrary(name);\n }\n /**\n * Load the Google Maps JavaScript API script with a callback.\n * @deprecated, use importLibrary() instead.\n */\n loadCallback(fn) {\n this.callbacks.push(fn);\n this.execute();\n }\n /**\n * Set the script on document.\n */\n setScript() {\n var _a, _b;\n if (document.getElementById(this.id)) {\n // TODO wrap onerror callback for cases where the script was loaded elsewhere\n this.callback();\n return;\n }\n var params = {\n key: this.apiKey,\n channel: this.channel,\n client: this.client,\n libraries: this.libraries.length && this.libraries,\n v: this.version,\n mapIds: this.mapIds,\n language: this.language,\n region: this.region,\n authReferrerPolicy: this.authReferrerPolicy\n };\n // keep the URL minimal:\n Object.keys(params).forEach(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n key => !params[key] && delete params[key]);\n if (!((_b = (_a = window === null || window === void 0 ? void 0 : window.google) === null || _a === void 0 ? void 0 : _a.maps) === null || _b === void 0 ? void 0 : _b.importLibrary)) {\n // tweaked copy of https://developers.google.com/maps/documentation/javascript/load-maps-js-api#dynamic-library-import\n // which also sets the base url, the id, and the nonce\n /* eslint-disable */\n (g => {\n // @ts-ignore\n var h,\n a,\n k,\n p = \"The Google Maps JavaScript API\",\n c = \"google\",\n l = \"importLibrary\",\n q = \"__ib__\",\n m = document,\n b = window;\n // @ts-ignore\n b = b[c] || (b[c] = {});\n // @ts-ignore\n var d = b.maps || (b.maps = {}),\n r = new Set(),\n e = new URLSearchParams(),\n u = () =>\n // @ts-ignore\n h || (h = new Promise((f, n) => __awaiter(this, void 0, void 0, function* () {\n var _a;\n yield a = m.createElement(\"script\");\n a.id = this.id;\n e.set(\"libraries\", [...r] + \"\");\n // @ts-ignore\n for (k in g) e.set(k.replace(/[A-Z]/g, t => \"_\" + t[0].toLowerCase()), g[k]);\n e.set(\"callback\", c + \".maps.\" + q);\n a.src = this.url + \"?\" + e;\n d[q] = f;\n a.onerror = () => h = n(Error(p + \" could not load.\"));\n // @ts-ignore\n a.nonce = this.nonce || ((_a = m.querySelector(\"script[nonce]\")) === null || _a === void 0 ? void 0 : _a.nonce) || \"\";\n m.head.append(a);\n })));\n // @ts-ignore\n d[l] ? console.warn(p + \" only loads once. Ignoring:\", g) : d[l] = function (f) {\n for (var _len = arguments.length, n = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n n[_key - 1] = arguments[_key];\n }\n return r.add(f) && u().then(() => d[l](f, ...n));\n };\n })(params);\n /* eslint-enable */\n }\n // While most libraries populate the global namespace when loaded via bootstrap params,\n // this is not the case for \"marker\" when used with the inline bootstrap loader\n // (and maybe others in the future). So ensure there is an importLibrary for each:\n var libraryPromises = this.libraries.map(library => this.importLibrary(library));\n // ensure at least one library, to kick off loading...\n if (!libraryPromises.length) {\n libraryPromises.push(this.importLibrary(\"core\"));\n }\n Promise.all(libraryPromises).then(() => this.callback(), error => {\n var event = new ErrorEvent(\"error\", {\n error\n }); // for backwards compat\n this.loadErrorCallback(event);\n });\n }\n /**\n * Reset the loader state.\n */\n reset() {\n this.deleteScript();\n this.done = false;\n this.loading = false;\n this.errors = [];\n this.onerrorEvent = null;\n }\n resetIfRetryingFailed() {\n if (this.failed) {\n this.reset();\n }\n }\n loadErrorCallback(e) {\n this.errors.push(e);\n if (this.errors.length <= this.retries) {\n var delay = this.errors.length * Math.pow(2, this.errors.length);\n console.error(\"Failed to load Google Maps script, retrying in \".concat(delay, \" ms.\"));\n setTimeout(() => {\n this.deleteScript();\n this.setScript();\n }, delay);\n } else {\n this.onerrorEvent = e;\n this.callback();\n }\n }\n callback() {\n this.done = true;\n this.loading = false;\n this.callbacks.forEach(cb => {\n cb(this.onerrorEvent);\n });\n this.callbacks = [];\n }\n execute() {\n this.resetIfRetryingFailed();\n if (this.loading) {\n // do nothing but wait\n return;\n }\n if (this.done) {\n this.callback();\n } else {\n // short circuit and warn if google.maps is already loaded\n if (window.google && window.google.maps && window.google.maps.version) {\n console.warn(\"Google Maps already loaded outside @googlemaps/js-api-loader. \" + \"This may result in undesirable behavior as options and script parameters may not match.\");\n this.callback();\n return;\n }\n this.loading = true;\n this.setScript();\n }\n }\n}\n\nvar defaultLibraries = ['maps'];\nfunction useJsApiLoader(_ref) {\n var {\n id = defaultLoadScriptProps.id,\n version = defaultLoadScriptProps.version,\n nonce,\n googleMapsApiKey,\n // googleMapsClientId,\n language,\n region,\n libraries = defaultLibraries,\n preventGoogleFontsLoading,\n // channel,\n mapIds,\n authReferrerPolicy\n } = _ref;\n var isMounted = useRef(false);\n var [isLoaded, setLoaded] = useState(false);\n var [loadError, setLoadError] = useState(undefined);\n useEffect(function trackMountedState() {\n isMounted.current = true;\n return () => {\n isMounted.current = false;\n };\n }, []);\n var loader = useMemo(() => {\n return new Loader({\n id,\n apiKey: googleMapsApiKey,\n version,\n libraries,\n language: language || 'en',\n region: region || 'US',\n mapIds: mapIds || [],\n nonce: nonce || '',\n authReferrerPolicy: authReferrerPolicy || 'origin'\n });\n }, [id, googleMapsApiKey, version, libraries, language, region, mapIds, nonce, authReferrerPolicy]);\n useEffect(function effect() {\n if (isLoaded) {\n return;\n } else {\n loader.load().then(() => {\n if (isMounted.current) {\n setLoaded(true);\n }\n return;\n }).catch(error => {\n setLoadError(error);\n });\n }\n }, []);\n useEffect(() => {\n if (isBrowser && preventGoogleFontsLoading) {\n preventGoogleFonts();\n }\n }, [preventGoogleFontsLoading]);\n var prevLibraries = useRef();\n useEffect(() => {\n if (prevLibraries.current && libraries !== prevLibraries.current) {\n console.warn('Performance warning! LoadScript has been reloaded unintentionally! You should not pass `libraries` prop as new array. Please keep an array of libraries as static class property for Components and PureComponents, or just a const variable outside of component, or somewhere in config files or ENV variables');\n }\n prevLibraries.current = libraries;\n }, [libraries]);\n return {\n isLoaded,\n loadError\n };\n}\n\nfunction ownKeys$f(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$f(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$f(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$f(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$h = {};\nvar updaterMap$h = {\n options(instance, options) {\n instance.setOptions(options);\n }\n};\nfunction TrafficLayerFunctional(_ref) {\n var {\n options,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (options && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n var trafficLayer = new google.maps.TrafficLayer(_objectSpread$f(_objectSpread$f({}, options), {}, {\n map\n }));\n setInstance(trafficLayer);\n if (onLoad) {\n onLoad(trafficLayer);\n }\n return () => {\n if (instance !== null) {\n if (onUnmount) {\n onUnmount(instance);\n }\n instance.setMap(null);\n }\n };\n }, []);\n return null;\n}\nvar TrafficLayerF = memo(TrafficLayerFunctional);\nclass TrafficLayer extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n trafficLayer: null\n });\n _defineProperty(this, \"setTrafficLayerCallback\", () => {\n if (this.state.trafficLayer !== null && this.props.onLoad) {\n this.props.onLoad(this.state.trafficLayer);\n }\n });\n _defineProperty(this, \"registeredEvents\", []);\n }\n componentDidMount() {\n var trafficLayer = new google.maps.TrafficLayer(_objectSpread$f(_objectSpread$f({}, this.props.options), {}, {\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$h,\n eventMap: eventMap$h,\n prevProps: {},\n nextProps: this.props,\n instance: trafficLayer\n });\n this.setState(function setTrafficLayer() {\n return {\n trafficLayer\n };\n }, this.setTrafficLayerCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.trafficLayer !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$h,\n eventMap: eventMap$h,\n prevProps,\n nextProps: this.props,\n instance: this.state.trafficLayer\n });\n }\n }\n componentWillUnmount() {\n if (this.state.trafficLayer !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.trafficLayer);\n }\n unregisterEvents(this.registeredEvents);\n this.state.trafficLayer.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(TrafficLayer, \"contextType\", MapContext);\n\nfunction BicyclingLayerFunctional(_ref) {\n var {\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n var bicyclingLayer = new google.maps.BicyclingLayer();\n setInstance(bicyclingLayer);\n bicyclingLayer.setMap(map);\n if (onLoad) {\n onLoad(bicyclingLayer);\n }\n return () => {\n if (bicyclingLayer !== null) {\n if (onUnmount) {\n onUnmount(bicyclingLayer);\n }\n bicyclingLayer.setMap(null);\n }\n };\n }, []);\n return null;\n}\nvar BicyclingLayerF = memo(BicyclingLayerFunctional);\nclass BicyclingLayer extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n bicyclingLayer: null\n });\n _defineProperty(this, \"setBicyclingLayerCallback\", () => {\n if (this.state.bicyclingLayer !== null) {\n this.state.bicyclingLayer.setMap(this.context);\n if (this.props.onLoad) {\n this.props.onLoad(this.state.bicyclingLayer);\n }\n }\n });\n }\n componentDidMount() {\n var bicyclingLayer = new google.maps.BicyclingLayer();\n this.setState(() => {\n return {\n bicyclingLayer\n };\n }, this.setBicyclingLayerCallback);\n }\n componentWillUnmount() {\n if (this.state.bicyclingLayer !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.bicyclingLayer);\n }\n this.state.bicyclingLayer.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(BicyclingLayer, \"contextType\", MapContext);\n\nfunction TransitLayerFunctional(_ref) {\n var {\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n var transitLayer = new google.maps.TransitLayer();\n setInstance(transitLayer);\n transitLayer.setMap(map);\n if (onLoad) {\n onLoad(transitLayer);\n }\n return () => {\n if (instance !== null) {\n if (onUnmount) {\n onUnmount(instance);\n }\n instance.setMap(null);\n }\n };\n }, []);\n return null;\n}\nvar TransitLayerF = memo(TransitLayerFunctional);\nclass TransitLayer extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n transitLayer: null\n });\n _defineProperty(this, \"setTransitLayerCallback\", () => {\n if (this.state.transitLayer !== null) {\n this.state.transitLayer.setMap(this.context);\n if (this.props.onLoad) {\n this.props.onLoad(this.state.transitLayer);\n }\n }\n });\n }\n componentDidMount() {\n var transitLayer = new google.maps.TransitLayer();\n this.setState(function setTransitLayer() {\n return {\n transitLayer\n };\n }, this.setTransitLayerCallback);\n }\n componentWillUnmount() {\n if (this.state.transitLayer !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.transitLayer);\n }\n this.state.transitLayer.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(TransitLayer, \"contextType\", MapContext);\n\nfunction ownKeys$e(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$e(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$e(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$e(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$g = {\n onCircleComplete: 'circlecomplete',\n onMarkerComplete: 'markercomplete',\n onOverlayComplete: 'overlaycomplete',\n onPolygonComplete: 'polygoncomplete',\n onPolylineComplete: 'polylinecomplete',\n onRectangleComplete: 'rectanglecomplete'\n};\nvar updaterMap$g = {\n drawingMode(instance, drawingMode) {\n instance.setDrawingMode(drawingMode);\n },\n options(instance, options) {\n instance.setOptions(options);\n }\n};\nfunction DrawingManagerFunctional(_ref) {\n var {\n options,\n drawingMode,\n onCircleComplete,\n onMarkerComplete,\n onOverlayComplete,\n onPolygonComplete,\n onPolylineComplete,\n onRectangleComplete,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [circlecompleteListener, setCircleCompleteListener] = useState(null);\n var [markercompleteListener, setMarkerCompleteListener] = useState(null);\n var [overlaycompleteListener, setOverlayCompleteListener] = useState(null);\n var [polygoncompleteListener, setPolygonCompleteListener] = useState(null);\n var [polylinecompleteListener, setPolylineCompleteListener] = useState(null);\n var [rectanglecompleteListener, setRectangleCompleteListener] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (options && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n if (instance !== null) {\n instance.setDrawingMode(drawingMode !== null && drawingMode !== void 0 ? drawingMode : null);\n }\n }, [instance, drawingMode]);\n useEffect(() => {\n if (instance && onCircleComplete) {\n if (circlecompleteListener !== null) {\n google.maps.event.removeListener(circlecompleteListener);\n }\n setCircleCompleteListener(google.maps.event.addListener(instance, 'circlecomplete', onCircleComplete));\n }\n }, [instance, onCircleComplete]);\n useEffect(() => {\n if (instance && onMarkerComplete) {\n if (markercompleteListener !== null) {\n google.maps.event.removeListener(markercompleteListener);\n }\n setMarkerCompleteListener(google.maps.event.addListener(instance, 'markercomplete', onMarkerComplete));\n }\n }, [instance, onMarkerComplete]);\n useEffect(() => {\n if (instance && onOverlayComplete) {\n if (overlaycompleteListener !== null) {\n google.maps.event.removeListener(overlaycompleteListener);\n }\n setOverlayCompleteListener(google.maps.event.addListener(instance, 'overlaycomplete', onOverlayComplete));\n }\n }, [instance, onOverlayComplete]);\n useEffect(() => {\n if (instance && onPolygonComplete) {\n if (polygoncompleteListener !== null) {\n google.maps.event.removeListener(polygoncompleteListener);\n }\n setPolygonCompleteListener(google.maps.event.addListener(instance, 'polygoncomplete', onPolygonComplete));\n }\n }, [instance, onPolygonComplete]);\n useEffect(() => {\n if (instance && onPolylineComplete) {\n if (polylinecompleteListener !== null) {\n google.maps.event.removeListener(polylinecompleteListener);\n }\n setPolylineCompleteListener(google.maps.event.addListener(instance, 'polylinecomplete', onPolylineComplete));\n }\n }, [instance, onPolylineComplete]);\n useEffect(() => {\n if (instance && onRectangleComplete) {\n if (rectanglecompleteListener !== null) {\n google.maps.event.removeListener(rectanglecompleteListener);\n }\n setRectangleCompleteListener(google.maps.event.addListener(instance, 'rectanglecomplete', onRectangleComplete));\n }\n }, [instance, onRectangleComplete]);\n useEffect(() => {\n invariant(!!google.maps.drawing, \"Did you include prop libraries={['drawing']} in the URL? %s\", google.maps.drawing);\n var drawingManager = new google.maps.drawing.DrawingManager(_objectSpread$e(_objectSpread$e({}, options), {}, {\n map\n }));\n if (drawingMode) {\n drawingManager.setDrawingMode(drawingMode);\n }\n if (onCircleComplete) {\n setCircleCompleteListener(google.maps.event.addListener(drawingManager, 'circlecomplete', onCircleComplete));\n }\n if (onMarkerComplete) {\n setMarkerCompleteListener(google.maps.event.addListener(drawingManager, 'markercomplete', onMarkerComplete));\n }\n if (onOverlayComplete) {\n setOverlayCompleteListener(google.maps.event.addListener(drawingManager, 'overlaycomplete', onOverlayComplete));\n }\n if (onPolygonComplete) {\n setPolygonCompleteListener(google.maps.event.addListener(drawingManager, 'polygoncomplete', onPolygonComplete));\n }\n if (onPolylineComplete) {\n setPolylineCompleteListener(google.maps.event.addListener(drawingManager, 'polylinecomplete', onPolylineComplete));\n }\n if (onRectangleComplete) {\n setRectangleCompleteListener(google.maps.event.addListener(drawingManager, 'rectanglecomplete', onRectangleComplete));\n }\n setInstance(drawingManager);\n if (onLoad) {\n onLoad(drawingManager);\n }\n return () => {\n if (instance !== null) {\n if (circlecompleteListener) {\n google.maps.event.removeListener(circlecompleteListener);\n }\n if (markercompleteListener) {\n google.maps.event.removeListener(markercompleteListener);\n }\n if (overlaycompleteListener) {\n google.maps.event.removeListener(overlaycompleteListener);\n }\n if (polygoncompleteListener) {\n google.maps.event.removeListener(polygoncompleteListener);\n }\n if (polylinecompleteListener) {\n google.maps.event.removeListener(polylinecompleteListener);\n }\n if (rectanglecompleteListener) {\n google.maps.event.removeListener(rectanglecompleteListener);\n }\n if (onUnmount) {\n onUnmount(instance);\n }\n instance.setMap(null);\n }\n };\n }, []);\n return null;\n}\nvar DrawingManagerF = memo(DrawingManagerFunctional);\nclass DrawingManager extends PureComponent {\n constructor(props) {\n super(props);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n drawingManager: null\n });\n _defineProperty(this, \"setDrawingManagerCallback\", () => {\n if (this.state.drawingManager !== null && this.props.onLoad) {\n this.props.onLoad(this.state.drawingManager);\n }\n });\n invariant(!!google.maps.drawing, \"Did you include prop libraries={['drawing']} in the URL? %s\", google.maps.drawing);\n }\n componentDidMount() {\n var drawingManager = new google.maps.drawing.DrawingManager(_objectSpread$e(_objectSpread$e({}, this.props.options), {}, {\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$g,\n eventMap: eventMap$g,\n prevProps: {},\n nextProps: this.props,\n instance: drawingManager\n });\n this.setState(function setDrawingManager() {\n return {\n drawingManager\n };\n }, this.setDrawingManagerCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.drawingManager !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$g,\n eventMap: eventMap$g,\n prevProps,\n nextProps: this.props,\n instance: this.state.drawingManager\n });\n }\n }\n componentWillUnmount() {\n if (this.state.drawingManager !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.drawingManager);\n }\n unregisterEvents(this.registeredEvents);\n this.state.drawingManager.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(DrawingManager, \"contextType\", MapContext);\n\nfunction ownKeys$d(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$d(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$d(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$d(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$f = {\n onAnimationChanged: 'animation_changed',\n onClick: 'click',\n onClickableChanged: 'clickable_changed',\n onCursorChanged: 'cursor_changed',\n onDblClick: 'dblclick',\n onDrag: 'drag',\n onDragEnd: 'dragend',\n onDraggableChanged: 'draggable_changed',\n onDragStart: 'dragstart',\n onFlatChanged: 'flat_changed',\n onIconChanged: 'icon_changed',\n onMouseDown: 'mousedown',\n onMouseOut: 'mouseout',\n onMouseOver: 'mouseover',\n onMouseUp: 'mouseup',\n onPositionChanged: 'position_changed',\n onRightClick: 'rightclick',\n onShapeChanged: 'shape_changed',\n onTitleChanged: 'title_changed',\n onVisibleChanged: 'visible_changed',\n onZindexChanged: 'zindex_changed'\n};\nvar updaterMap$f = {\n animation(instance, animation) {\n instance.setAnimation(animation);\n },\n clickable(instance, clickable) {\n instance.setClickable(clickable);\n },\n cursor(instance, cursor) {\n instance.setCursor(cursor);\n },\n draggable(instance, draggable) {\n instance.setDraggable(draggable);\n },\n icon(instance, icon) {\n instance.setIcon(icon);\n },\n label(instance, label) {\n instance.setLabel(label);\n },\n map(instance, map) {\n instance.setMap(map);\n },\n opacity(instance, opacity) {\n instance.setOpacity(opacity);\n },\n options(instance, options) {\n instance.setOptions(options);\n },\n position(instance, position) {\n instance.setPosition(position);\n },\n shape(instance, shape) {\n instance.setShape(shape);\n },\n title(instance, title) {\n instance.setTitle(title);\n },\n visible(instance, visible) {\n instance.setVisible(visible);\n },\n zIndex(instance, zIndex) {\n instance.setZIndex(zIndex);\n }\n};\nvar defaultOptions$5 = {};\nfunction MarkerFunctional(_ref) {\n var {\n position,\n options,\n clusterer,\n noClustererRedraw,\n children,\n draggable,\n visible,\n animation,\n clickable,\n cursor,\n icon,\n label,\n opacity,\n shape,\n title,\n zIndex,\n onClick,\n onDblClick,\n onDrag,\n onDragEnd,\n onDragStart,\n onMouseOut,\n onMouseOver,\n onMouseUp,\n onMouseDown,\n onRightClick,\n onClickableChanged,\n onCursorChanged,\n onAnimationChanged,\n onDraggableChanged,\n onFlatChanged,\n onIconChanged,\n onPositionChanged,\n onShapeChanged,\n onTitleChanged,\n onVisibleChanged,\n onZindexChanged,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [dblclickListener, setDblclickListener] = useState(null);\n var [dragendListener, setDragendListener] = useState(null);\n var [dragstartListener, setDragstartListener] = useState(null);\n var [mousedownListener, setMousedownListener] = useState(null);\n var [mouseoutListener, setMouseoutListener] = useState(null);\n var [mouseoverListener, setMouseoverListener] = useState(null);\n var [mouseupListener, setMouseupListener] = useState(null);\n var [rightclickListener, setRightclickListener] = useState(null);\n var [clickListener, setClickListener] = useState(null);\n var [dragListener, setDragListener] = useState(null);\n var [clickableChangedListener, setClickableChangedListener] = useState(null);\n var [cursorChangedListener, setCursorChangedListener] = useState(null);\n var [animationChangedListener, setAnimationChangedListener] = useState(null);\n var [draggableChangedListener, setDraggableChangedListener] = useState(null);\n var [flatChangedListener, setFlatChangedListener] = useState(null);\n var [iconChangedListener, setIconChangedListener] = useState(null);\n var [positionChangedListener, setPositionChangedListener] = useState(null);\n var [shapeChangedListener, setShapeChangedListener] = useState(null);\n var [titleChangedListener, setTitleChangedListener] = useState(null);\n var [visibleChangedListener, setVisibleChangedListener] = useState(null);\n var [zIndexChangedListener, setZindexChangedListener] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (typeof options !== 'undefined' && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n if (typeof draggable !== 'undefined' && instance !== null) {\n instance.setDraggable(draggable);\n }\n }, [instance, draggable]);\n useEffect(() => {\n if (position && instance !== null) {\n instance.setPosition(position);\n }\n }, [instance, position]);\n useEffect(() => {\n if (typeof visible !== 'undefined' && instance !== null) {\n instance.setVisible(visible);\n }\n }, [instance, visible]);\n useEffect(() => {\n instance === null || instance === void 0 || instance.setAnimation(animation);\n }, [instance, animation]);\n useEffect(() => {\n if (instance && clickable !== undefined) {\n instance.setClickable(clickable);\n }\n }, [instance, clickable]);\n useEffect(() => {\n if (instance && cursor !== undefined) {\n instance.setCursor(cursor);\n }\n }, [instance, cursor]);\n useEffect(() => {\n if (instance && icon !== undefined) {\n instance.setIcon(icon);\n }\n }, [instance, icon]);\n useEffect(() => {\n if (instance && label !== undefined) {\n instance.setLabel(label);\n }\n }, [instance, label]);\n useEffect(() => {\n if (instance && opacity !== undefined) {\n instance.setOpacity(opacity);\n }\n }, [instance, opacity]);\n useEffect(() => {\n if (instance && shape !== undefined) {\n instance.setShape(shape);\n }\n }, [instance, shape]);\n useEffect(() => {\n if (instance && title !== undefined) {\n instance.setTitle(title);\n }\n }, [instance, title]);\n useEffect(() => {\n if (instance && zIndex !== undefined) {\n instance.setZIndex(zIndex);\n }\n }, [instance, zIndex]);\n useEffect(() => {\n if (instance && onDblClick) {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n setDblclickListener(google.maps.event.addListener(instance, 'dblclick', onDblClick));\n }\n }, [onDblClick]);\n useEffect(() => {\n if (instance && onDragEnd) {\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n setDragendListener(google.maps.event.addListener(instance, 'dragend', onDragEnd));\n }\n }, [onDragEnd]);\n useEffect(() => {\n if (instance && onDragStart) {\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n setDragstartListener(google.maps.event.addListener(instance, 'dragstart', onDragStart));\n }\n }, [onDragStart]);\n useEffect(() => {\n if (instance && onMouseDown) {\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n setMousedownListener(google.maps.event.addListener(instance, 'mousedown', onMouseDown));\n }\n }, [onMouseDown]);\n useEffect(() => {\n if (instance && onMouseOut) {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n setMouseoutListener(google.maps.event.addListener(instance, 'mouseout', onMouseOut));\n }\n }, [onMouseOut]);\n useEffect(() => {\n if (instance && onMouseOver) {\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n setMouseoverListener(google.maps.event.addListener(instance, 'mouseover', onMouseOver));\n }\n }, [onMouseOver]);\n useEffect(() => {\n if (instance && onMouseUp) {\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n setMouseupListener(google.maps.event.addListener(instance, 'mouseup', onMouseUp));\n }\n }, [onMouseUp]);\n useEffect(() => {\n if (instance && onRightClick) {\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n setRightclickListener(google.maps.event.addListener(instance, 'rightclick', onRightClick));\n }\n }, [onRightClick]);\n useEffect(() => {\n if (instance && onClick) {\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n setClickListener(google.maps.event.addListener(instance, 'click', onClick));\n }\n }, [onClick]);\n useEffect(() => {\n if (instance && onDrag) {\n if (dragListener !== null) {\n google.maps.event.removeListener(dragListener);\n }\n setDragListener(google.maps.event.addListener(instance, 'drag', onDrag));\n }\n }, [onDrag]);\n useEffect(() => {\n if (instance && onClickableChanged) {\n if (clickableChangedListener !== null) {\n google.maps.event.removeListener(clickableChangedListener);\n }\n setClickableChangedListener(google.maps.event.addListener(instance, 'clickable_changed', onClickableChanged));\n }\n }, [onClickableChanged]);\n useEffect(() => {\n if (instance && onCursorChanged) {\n if (cursorChangedListener !== null) {\n google.maps.event.removeListener(cursorChangedListener);\n }\n setCursorChangedListener(google.maps.event.addListener(instance, 'cursor_changed', onCursorChanged));\n }\n }, [onCursorChanged]);\n useEffect(() => {\n if (instance && onAnimationChanged) {\n if (animationChangedListener !== null) {\n google.maps.event.removeListener(animationChangedListener);\n }\n setAnimationChangedListener(google.maps.event.addListener(instance, 'animation_changed', onAnimationChanged));\n }\n }, [onAnimationChanged]);\n useEffect(() => {\n if (instance && onDraggableChanged) {\n if (draggableChangedListener !== null) {\n google.maps.event.removeListener(draggableChangedListener);\n }\n setDraggableChangedListener(google.maps.event.addListener(instance, 'draggable_changed', onDraggableChanged));\n }\n }, [onDraggableChanged]);\n useEffect(() => {\n if (instance && onFlatChanged) {\n if (flatChangedListener !== null) {\n google.maps.event.removeListener(flatChangedListener);\n }\n setFlatChangedListener(google.maps.event.addListener(instance, 'flat_changed', onFlatChanged));\n }\n }, [onFlatChanged]);\n useEffect(() => {\n if (instance && onIconChanged) {\n if (iconChangedListener !== null) {\n google.maps.event.removeListener(iconChangedListener);\n }\n setIconChangedListener(google.maps.event.addListener(instance, 'icon_changed', onIconChanged));\n }\n }, [onIconChanged]);\n useEffect(() => {\n if (instance && onPositionChanged) {\n if (positionChangedListener !== null) {\n google.maps.event.removeListener(positionChangedListener);\n }\n setPositionChangedListener(google.maps.event.addListener(instance, 'position_changed', onPositionChanged));\n }\n }, [onPositionChanged]);\n useEffect(() => {\n if (instance && onShapeChanged) {\n if (shapeChangedListener !== null) {\n google.maps.event.removeListener(shapeChangedListener);\n }\n setShapeChangedListener(google.maps.event.addListener(instance, 'shape_changed', onShapeChanged));\n }\n }, [onShapeChanged]);\n useEffect(() => {\n if (instance && onTitleChanged) {\n if (titleChangedListener !== null) {\n google.maps.event.removeListener(titleChangedListener);\n }\n setTitleChangedListener(google.maps.event.addListener(instance, 'title_changed', onTitleChanged));\n }\n }, [onTitleChanged]);\n useEffect(() => {\n if (instance && onVisibleChanged) {\n if (visibleChangedListener !== null) {\n google.maps.event.removeListener(visibleChangedListener);\n }\n setVisibleChangedListener(google.maps.event.addListener(instance, 'visible_changed', onVisibleChanged));\n }\n }, [onVisibleChanged]);\n useEffect(() => {\n if (instance && onZindexChanged) {\n if (zIndexChangedListener !== null) {\n google.maps.event.removeListener(zIndexChangedListener);\n }\n setZindexChangedListener(google.maps.event.addListener(instance, 'zindex_changed', onZindexChanged));\n }\n }, [onZindexChanged]);\n useEffect(() => {\n var markerOptions = _objectSpread$d(_objectSpread$d(_objectSpread$d({}, options || defaultOptions$5), clusterer ? defaultOptions$5 : {\n map\n }), {}, {\n position\n });\n var marker = new google.maps.Marker(markerOptions);\n if (clusterer) {\n clusterer.addMarker(marker, !!noClustererRedraw);\n } else {\n marker.setMap(map);\n }\n if (position) {\n marker.setPosition(position);\n }\n if (typeof visible !== 'undefined') {\n marker.setVisible(visible);\n }\n if (typeof draggable !== 'undefined') {\n marker.setDraggable(draggable);\n }\n if (typeof clickable !== 'undefined') {\n marker.setClickable(clickable);\n }\n if (typeof cursor === 'string') {\n marker.setCursor(cursor);\n }\n if (icon) {\n marker.setIcon(icon);\n }\n if (typeof label !== 'undefined') {\n marker.setLabel(label);\n }\n if (typeof opacity !== 'undefined') {\n marker.setOpacity(opacity);\n }\n if (shape) {\n marker.setShape(shape);\n }\n if (typeof title === 'string') {\n marker.setTitle(title);\n }\n if (typeof zIndex === 'number') {\n marker.setZIndex(zIndex);\n }\n if (onDblClick) {\n setDblclickListener(google.maps.event.addListener(marker, 'dblclick', onDblClick));\n }\n if (onDragEnd) {\n setDragendListener(google.maps.event.addListener(marker, 'dragend', onDragEnd));\n }\n if (onDragStart) {\n setDragstartListener(google.maps.event.addListener(marker, 'dragstart', onDragStart));\n }\n if (onMouseDown) {\n setMousedownListener(google.maps.event.addListener(marker, 'mousedown', onMouseDown));\n }\n if (onMouseOut) {\n setMouseoutListener(google.maps.event.addListener(marker, 'mouseout', onMouseOut));\n }\n if (onMouseOver) {\n setMouseoverListener(google.maps.event.addListener(marker, 'mouseover', onMouseOver));\n }\n if (onMouseUp) {\n setMouseupListener(google.maps.event.addListener(marker, 'mouseup', onMouseUp));\n }\n if (onRightClick) {\n setRightclickListener(google.maps.event.addListener(marker, 'rightclick', onRightClick));\n }\n if (onClick) {\n setClickListener(google.maps.event.addListener(marker, 'click', onClick));\n }\n if (onDrag) {\n setDragListener(google.maps.event.addListener(marker, 'drag', onDrag));\n }\n if (onClickableChanged) {\n setClickableChangedListener(google.maps.event.addListener(marker, 'clickable_changed', onClickableChanged));\n }\n if (onCursorChanged) {\n setCursorChangedListener(google.maps.event.addListener(marker, 'cursor_changed', onCursorChanged));\n }\n if (onAnimationChanged) {\n setAnimationChangedListener(google.maps.event.addListener(marker, 'animation_changed', onAnimationChanged));\n }\n if (onDraggableChanged) {\n setDraggableChangedListener(google.maps.event.addListener(marker, 'draggable_changed', onDraggableChanged));\n }\n if (onFlatChanged) {\n setFlatChangedListener(google.maps.event.addListener(marker, 'flat_changed', onFlatChanged));\n }\n if (onIconChanged) {\n setIconChangedListener(google.maps.event.addListener(marker, 'icon_changed', onIconChanged));\n }\n if (onPositionChanged) {\n setPositionChangedListener(google.maps.event.addListener(marker, 'position_changed', onPositionChanged));\n }\n if (onShapeChanged) {\n setShapeChangedListener(google.maps.event.addListener(marker, 'shape_changed', onShapeChanged));\n }\n if (onTitleChanged) {\n setTitleChangedListener(google.maps.event.addListener(marker, 'title_changed', onTitleChanged));\n }\n if (onVisibleChanged) {\n setVisibleChangedListener(google.maps.event.addListener(marker, 'visible_changed', onVisibleChanged));\n }\n if (onZindexChanged) {\n setZindexChangedListener(google.maps.event.addListener(marker, 'zindex_changed', onZindexChanged));\n }\n setInstance(marker);\n if (onLoad) {\n onLoad(marker);\n }\n return () => {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n if (clickableChangedListener !== null) {\n google.maps.event.removeListener(clickableChangedListener);\n }\n if (cursorChangedListener !== null) {\n google.maps.event.removeListener(cursorChangedListener);\n }\n if (animationChangedListener !== null) {\n google.maps.event.removeListener(animationChangedListener);\n }\n if (draggableChangedListener !== null) {\n google.maps.event.removeListener(draggableChangedListener);\n }\n if (flatChangedListener !== null) {\n google.maps.event.removeListener(flatChangedListener);\n }\n if (iconChangedListener !== null) {\n google.maps.event.removeListener(iconChangedListener);\n }\n if (positionChangedListener !== null) {\n google.maps.event.removeListener(positionChangedListener);\n }\n if (titleChangedListener !== null) {\n google.maps.event.removeListener(titleChangedListener);\n }\n if (visibleChangedListener !== null) {\n google.maps.event.removeListener(visibleChangedListener);\n }\n if (zIndexChangedListener !== null) {\n google.maps.event.removeListener(zIndexChangedListener);\n }\n if (onUnmount) {\n onUnmount(marker);\n }\n if (clusterer) {\n clusterer.removeMarker(marker, !!noClustererRedraw);\n } else if (marker) {\n marker.setMap(null);\n }\n };\n }, []);\n var chx = useMemo(() => {\n return children ? Children.map(children, child => {\n if (!isValidElement(child)) {\n return child;\n }\n var elementChild = child;\n return cloneElement(elementChild, {\n anchor: instance\n });\n }) : null;\n }, [children, instance]);\n return jsx(Fragment, {\n children: chx\n }) || null;\n}\nvar MarkerF = memo(MarkerFunctional);\nclass Marker extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n }\n componentDidMount() {\n var _this = this;\n return _asyncToGenerator(function* () {\n var markerOptions = _objectSpread$d(_objectSpread$d(_objectSpread$d({}, _this.props.options || defaultOptions$5), _this.props.clusterer ? defaultOptions$5 : {\n map: _this.context\n }), {}, {\n position: _this.props.position\n });\n // Unfortunately we can't just do this in the contstructor, because the\n // `MapContext` might not be filled in yet.\n _this.marker = new google.maps.Marker(markerOptions);\n if (_this.props.clusterer) {\n _this.props.clusterer.addMarker(_this.marker, !!_this.props.noClustererRedraw);\n } else {\n _this.marker.setMap(_this.context);\n }\n _this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$f,\n eventMap: eventMap$f,\n prevProps: {},\n nextProps: _this.props,\n instance: _this.marker\n });\n if (_this.props.onLoad) {\n _this.props.onLoad(_this.marker);\n }\n })();\n }\n componentDidUpdate(prevProps) {\n if (this.marker) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$f,\n eventMap: eventMap$f,\n prevProps,\n nextProps: this.props,\n instance: this.marker\n });\n }\n }\n componentWillUnmount() {\n if (!this.marker) {\n return;\n }\n if (this.props.onUnmount) {\n this.props.onUnmount(this.marker);\n }\n unregisterEvents(this.registeredEvents);\n if (this.props.clusterer) {\n this.props.clusterer.removeMarker(this.marker, !!this.props.noClustererRedraw);\n } else if (this.marker) {\n this.marker.setMap(null);\n }\n }\n render() {\n var children = this.props.children ? Children.map(this.props.children, child => {\n if (!isValidElement(child)) {\n return child;\n }\n var elementChild = child;\n return cloneElement(elementChild, {\n anchor: this.marker\n });\n }) : null;\n return children || null;\n }\n}\n_defineProperty(Marker, \"contextType\", MapContext);\n\nvar ClusterIcon = /** @class */function () {\n function ClusterIcon(cluster, styles) {\n cluster.getClusterer().extend(ClusterIcon, google.maps.OverlayView);\n this.cluster = cluster;\n this.clusterClassName = this.cluster.getClusterer().getClusterClass();\n this.className = this.clusterClassName;\n this.styles = styles;\n this.center = undefined;\n this.div = null;\n this.sums = null;\n this.visible = false;\n this.boundsChangedListener = null;\n this.url = '';\n this.height = 0;\n this.width = 0;\n this.anchorText = [0, 0];\n this.anchorIcon = [0, 0];\n this.textColor = 'black';\n this.textSize = 11;\n this.textDecoration = 'none';\n this.fontWeight = 'bold';\n this.fontStyle = 'normal';\n this.fontFamily = 'Arial,sans-serif';\n this.backgroundPosition = '0 0';\n this.cMouseDownInCluster = null;\n this.cDraggingMapByCluster = null;\n this.timeOut = null;\n this.setMap(cluster.getMap()); // Note: this causes onAdd to be called\n this.onBoundsChanged = this.onBoundsChanged.bind(this);\n this.onMouseDown = this.onMouseDown.bind(this);\n this.onClick = this.onClick.bind(this);\n this.onMouseOver = this.onMouseOver.bind(this);\n this.onMouseOut = this.onMouseOut.bind(this);\n this.onAdd = this.onAdd.bind(this);\n this.onRemove = this.onRemove.bind(this);\n this.draw = this.draw.bind(this);\n this.hide = this.hide.bind(this);\n this.show = this.show.bind(this);\n this.useStyle = this.useStyle.bind(this);\n this.setCenter = this.setCenter.bind(this);\n this.getPosFromLatLng = this.getPosFromLatLng.bind(this);\n }\n ClusterIcon.prototype.onBoundsChanged = function () {\n this.cDraggingMapByCluster = this.cMouseDownInCluster;\n };\n ClusterIcon.prototype.onMouseDown = function () {\n this.cMouseDownInCluster = true;\n this.cDraggingMapByCluster = false;\n };\n ClusterIcon.prototype.onClick = function (event) {\n this.cMouseDownInCluster = false;\n if (!this.cDraggingMapByCluster) {\n var markerClusterer_1 = this.cluster.getClusterer();\n /**\n * This event is fired when a cluster marker is clicked.\n * @name MarkerClusterer#click\n * @param {Cluster} c The cluster that was clicked.\n * @event\n */\n google.maps.event.trigger(markerClusterer_1, 'click', this.cluster);\n google.maps.event.trigger(markerClusterer_1, 'clusterclick', this.cluster); // deprecated name\n // The default click handler follows. Disable it by setting\n // the zoomOnClick property to false.\n if (markerClusterer_1.getZoomOnClick()) {\n // Zoom into the cluster.\n var maxZoom_1 = markerClusterer_1.getMaxZoom();\n var bounds_1 = this.cluster.getBounds();\n var map = markerClusterer_1.getMap();\n if (map !== null && 'fitBounds' in map) {\n map.fitBounds(bounds_1);\n }\n // There is a fix for Issue 170 here:\n this.timeOut = window.setTimeout(function () {\n var map = markerClusterer_1.getMap();\n if (map !== null) {\n if ('fitBounds' in map) {\n map.fitBounds(bounds_1);\n }\n var zoom = map.getZoom() || 0;\n // Don't zoom beyond the max zoom level\n if (maxZoom_1 !== null && zoom > maxZoom_1) {\n map.setZoom(maxZoom_1 + 1);\n }\n }\n }, 100);\n }\n // Prevent event propagation to the map:\n event.cancelBubble = true;\n if (event.stopPropagation) {\n event.stopPropagation();\n }\n }\n };\n ClusterIcon.prototype.onMouseOver = function () {\n /**\n * This event is fired when the mouse moves over a cluster marker.\n * @name MarkerClusterer#mouseover\n * @param {Cluster} c The cluster that the mouse moved over.\n * @event\n */\n google.maps.event.trigger(this.cluster.getClusterer(), 'mouseover', this.cluster);\n };\n ClusterIcon.prototype.onMouseOut = function () {\n /**\n * This event is fired when the mouse moves out of a cluster marker.\n * @name MarkerClusterer#mouseout\n * @param {Cluster} c The cluster that the mouse moved out of.\n * @event\n */\n google.maps.event.trigger(this.cluster.getClusterer(), 'mouseout', this.cluster);\n };\n ClusterIcon.prototype.onAdd = function () {\n var _a;\n this.div = document.createElement('div');\n this.div.className = this.className;\n if (this.visible) {\n this.show();\n }\n (_a = this.getPanes()) === null || _a === void 0 ? void 0 : _a.overlayMouseTarget.appendChild(this.div);\n var map = this.getMap();\n if (map !== null) {\n // Fix for Issue 157\n this.boundsChangedListener = google.maps.event.addListener(map, 'bounds_changed', this.onBoundsChanged);\n this.div.addEventListener('mousedown', this.onMouseDown);\n this.div.addEventListener('click', this.onClick);\n this.div.addEventListener('mouseover', this.onMouseOver);\n this.div.addEventListener('mouseout', this.onMouseOut);\n }\n };\n ClusterIcon.prototype.onRemove = function () {\n if (this.div && this.div.parentNode) {\n this.hide();\n if (this.boundsChangedListener !== null) {\n google.maps.event.removeListener(this.boundsChangedListener);\n }\n this.div.removeEventListener('mousedown', this.onMouseDown);\n this.div.removeEventListener('click', this.onClick);\n this.div.removeEventListener('mouseover', this.onMouseOver);\n this.div.removeEventListener('mouseout', this.onMouseOut);\n this.div.parentNode.removeChild(this.div);\n if (this.timeOut !== null) {\n window.clearTimeout(this.timeOut);\n this.timeOut = null;\n }\n this.div = null;\n }\n };\n ClusterIcon.prototype.draw = function () {\n if (this.visible && this.div !== null && this.center) {\n var pos = this.getPosFromLatLng(this.center);\n this.div.style.top = pos !== null ? \"\".concat(pos.y, \"px\") : '0';\n this.div.style.left = pos !== null ? \"\".concat(pos.x, \"px\") : '0';\n }\n };\n ClusterIcon.prototype.hide = function () {\n if (this.div) {\n this.div.style.display = 'none';\n }\n this.visible = false;\n };\n ClusterIcon.prototype.show = function () {\n var _a, _b, _c, _d, _e, _f;\n if (this.div && this.center) {\n var divTitle = this.sums === null || typeof this.sums.title === 'undefined' || this.sums.title === '' ? this.cluster.getClusterer().getTitle() : this.sums.title;\n // NOTE: values must be specified in px units\n var bp = this.backgroundPosition.split(' ');\n var spriteH = parseInt(((_a = bp[0]) === null || _a === void 0 ? void 0 : _a.replace(/^\\s+|\\s+$/g, '')) || '0', 10);\n var spriteV = parseInt(((_b = bp[1]) === null || _b === void 0 ? void 0 : _b.replace(/^\\s+|\\s+$/g, '')) || '0', 10);\n var pos = this.getPosFromLatLng(this.center);\n this.div.className = this.className;\n this.div.setAttribute('style', \"cursor: pointer; position: absolute; top: \".concat(pos !== null ? \"\".concat(pos.y, \"px\") : '0', \"; left: \").concat(pos !== null ? \"\".concat(pos.x, \"px\") : '0', \"; width: \").concat(this.width, \"px; height: \").concat(this.height, \"px; \"));\n var img = document.createElement('img');\n img.alt = divTitle;\n img.src = this.url;\n img.width = this.width;\n img.height = this.height;\n img.setAttribute('style', \"position: absolute; top: \".concat(spriteV, \"px; left: \").concat(spriteH, \"px\"));\n if (!this.cluster.getClusterer().enableRetinaIcons) {\n img.style.clip = \"rect(-\".concat(spriteV, \"px, -\").concat(spriteH + this.width, \"px, -\").concat(spriteV + this.height, \", -\").concat(spriteH, \")\");\n }\n var textElm = document.createElement('div');\n textElm.setAttribute('style', \"position: absolute; top: \".concat(this.anchorText[0], \"px; left: \").concat(this.anchorText[1], \"px; color: \").concat(this.textColor, \"; font-size: \").concat(this.textSize, \"px; font-family: \").concat(this.fontFamily, \"; font-weight: \").concat(this.fontWeight, \"; fontStyle: \").concat(this.fontStyle, \"; text-decoration: \").concat(this.textDecoration, \"; text-align: center; width: \").concat(this.width, \"px; line-height: \").concat(this.height, \"px\"));\n if ((_c = this.sums) === null || _c === void 0 ? void 0 : _c.text) textElm.innerText = \"\".concat((_d = this.sums) === null || _d === void 0 ? void 0 : _d.text);\n if ((_e = this.sums) === null || _e === void 0 ? void 0 : _e.html) textElm.innerHTML = \"\".concat((_f = this.sums) === null || _f === void 0 ? void 0 : _f.html);\n this.div.innerHTML = '';\n this.div.appendChild(img);\n this.div.appendChild(textElm);\n this.div.title = divTitle;\n this.div.style.display = '';\n }\n this.visible = true;\n };\n ClusterIcon.prototype.useStyle = function (sums) {\n this.sums = sums;\n var styles = this.cluster.getClusterer().getStyles();\n var style = styles[Math.min(styles.length - 1, Math.max(0, sums.index - 1))];\n if (style) {\n this.url = style.url;\n this.height = style.height;\n this.width = style.width;\n if (style.className) {\n this.className = \"\".concat(this.clusterClassName, \" \").concat(style.className);\n }\n this.anchorText = style.anchorText || [0, 0];\n this.anchorIcon = style.anchorIcon || [this.height / 2, this.width / 2];\n this.textColor = style.textColor || 'black';\n this.textSize = style.textSize || 11;\n this.textDecoration = style.textDecoration || 'none';\n this.fontWeight = style.fontWeight || 'bold';\n this.fontStyle = style.fontStyle || 'normal';\n this.fontFamily = style.fontFamily || 'Arial,sans-serif';\n this.backgroundPosition = style.backgroundPosition || '0 0';\n }\n };\n ClusterIcon.prototype.setCenter = function (center) {\n this.center = center;\n };\n ClusterIcon.prototype.getPosFromLatLng = function (latlng) {\n var pos = this.getProjection().fromLatLngToDivPixel(latlng);\n if (pos !== null) {\n pos.x -= this.anchorIcon[1];\n pos.y -= this.anchorIcon[0];\n }\n return pos;\n };\n return ClusterIcon;\n}();\n\n/* global google */\nvar Cluster$1 = /** @class */function () {\n function Cluster(markerClusterer) {\n this.markerClusterer = markerClusterer;\n this.map = this.markerClusterer.getMap();\n this.gridSize = this.markerClusterer.getGridSize();\n this.minClusterSize = this.markerClusterer.getMinimumClusterSize();\n this.averageCenter = this.markerClusterer.getAverageCenter();\n this.markers = [];\n this.center = undefined;\n this.bounds = null;\n this.clusterIcon = new ClusterIcon(this, this.markerClusterer.getStyles());\n this.getSize = this.getSize.bind(this);\n this.getMarkers = this.getMarkers.bind(this);\n this.getCenter = this.getCenter.bind(this);\n this.getMap = this.getMap.bind(this);\n this.getClusterer = this.getClusterer.bind(this);\n this.getBounds = this.getBounds.bind(this);\n this.remove = this.remove.bind(this);\n this.addMarker = this.addMarker.bind(this);\n this.isMarkerInClusterBounds = this.isMarkerInClusterBounds.bind(this);\n this.calculateBounds = this.calculateBounds.bind(this);\n this.updateIcon = this.updateIcon.bind(this);\n this.isMarkerAlreadyAdded = this.isMarkerAlreadyAdded.bind(this);\n }\n Cluster.prototype.getSize = function () {\n return this.markers.length;\n };\n Cluster.prototype.getMarkers = function () {\n return this.markers;\n };\n Cluster.prototype.getCenter = function () {\n return this.center;\n };\n Cluster.prototype.getMap = function () {\n return this.map;\n };\n Cluster.prototype.getClusterer = function () {\n return this.markerClusterer;\n };\n Cluster.prototype.getBounds = function () {\n var bounds = new google.maps.LatLngBounds(this.center, this.center);\n var markers = this.getMarkers();\n for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {\n var marker = markers_1[_i];\n var position = marker.getPosition();\n if (position) {\n bounds.extend(position);\n }\n }\n return bounds;\n };\n Cluster.prototype.remove = function () {\n this.clusterIcon.setMap(null);\n this.markers = [];\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n delete this.markers;\n };\n Cluster.prototype.addMarker = function (marker) {\n var _a;\n if (this.isMarkerAlreadyAdded(marker)) {\n return false;\n }\n if (!this.center) {\n var position = marker.getPosition();\n if (position) {\n this.center = position;\n this.calculateBounds();\n }\n } else {\n if (this.averageCenter) {\n var position = marker.getPosition();\n if (position) {\n var length_1 = this.markers.length + 1;\n this.center = new google.maps.LatLng((this.center.lat() * (length_1 - 1) + position.lat()) / length_1, (this.center.lng() * (length_1 - 1) + position.lng()) / length_1);\n this.calculateBounds();\n }\n }\n }\n marker.isAdded = true;\n this.markers.push(marker);\n var mCount = this.markers.length;\n var maxZoom = this.markerClusterer.getMaxZoom();\n var zoom = (_a = this.map) === null || _a === void 0 ? void 0 : _a.getZoom();\n if (maxZoom !== null && typeof zoom !== 'undefined' && zoom > maxZoom) {\n // Zoomed in past max zoom, so show the marker.\n if (marker.getMap() !== this.map) {\n marker.setMap(this.map);\n }\n } else if (mCount < this.minClusterSize) {\n // Min cluster size not reached so show the marker.\n if (marker.getMap() !== this.map) {\n marker.setMap(this.map);\n }\n } else if (mCount === this.minClusterSize) {\n // Hide the markers that were showing.\n for (var _i = 0, _b = this.markers; _i < _b.length; _i++) {\n var markerElement = _b[_i];\n markerElement.setMap(null);\n }\n } else {\n marker.setMap(null);\n }\n return true;\n };\n Cluster.prototype.isMarkerInClusterBounds = function (marker) {\n if (this.bounds !== null) {\n var position = marker.getPosition();\n if (position) {\n return this.bounds.contains(position);\n }\n }\n return false;\n };\n Cluster.prototype.calculateBounds = function () {\n this.bounds = this.markerClusterer.getExtendedBounds(new google.maps.LatLngBounds(this.center, this.center));\n };\n Cluster.prototype.updateIcon = function () {\n var _a;\n var mCount = this.markers.length;\n var maxZoom = this.markerClusterer.getMaxZoom();\n var zoom = (_a = this.map) === null || _a === void 0 ? void 0 : _a.getZoom();\n if (maxZoom !== null && typeof zoom !== 'undefined' && zoom > maxZoom) {\n this.clusterIcon.hide();\n return;\n }\n if (mCount < this.minClusterSize) {\n // Min cluster size not yet reached.\n this.clusterIcon.hide();\n return;\n }\n if (this.center) {\n this.clusterIcon.setCenter(this.center);\n }\n this.clusterIcon.useStyle(this.markerClusterer.getCalculator()(this.markers, this.markerClusterer.getStyles().length));\n this.clusterIcon.show();\n };\n Cluster.prototype.isMarkerAlreadyAdded = function (marker) {\n if (this.markers.includes) {\n return this.markers.includes(marker);\n }\n for (var i = 0; i < this.markers.length; i++) {\n if (marker === this.markers[i]) {\n return true;\n }\n }\n return false;\n };\n return Cluster;\n}();\n\n/* global google */\n/* eslint-disable filenames/match-regex */\n/**\n * Supports up to 9007199254740991 (Number.MAX_SAFE_INTEGER) markers\n * which is not a problem as max array length is 4294967296 (2**32)\n */\nfunction CALCULATOR(markers, numStyles) {\n var count = markers.length;\n var numberOfDigits = count.toString().length;\n var index = Math.min(numberOfDigits, numStyles);\n return {\n text: count.toString(),\n index: index,\n title: ''\n };\n}\nvar BATCH_SIZE = 2000;\nvar BATCH_SIZE_IE = 500;\nvar IMAGE_PATH = 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m';\nvar IMAGE_EXTENSION = 'png';\nvar IMAGE_SIZES = [53, 56, 66, 78, 90];\nvar CLUSTERER_CLASS = 'cluster';\nvar Clusterer = /** @class */function () {\n function Clusterer(map, optMarkers, optOptions) {\n if (optMarkers === void 0) {\n optMarkers = [];\n }\n if (optOptions === void 0) {\n optOptions = {};\n }\n this.getMinimumClusterSize = this.getMinimumClusterSize.bind(this);\n this.setMinimumClusterSize = this.setMinimumClusterSize.bind(this);\n this.getEnableRetinaIcons = this.getEnableRetinaIcons.bind(this);\n this.setEnableRetinaIcons = this.setEnableRetinaIcons.bind(this);\n this.addToClosestCluster = this.addToClosestCluster.bind(this);\n this.getImageExtension = this.getImageExtension.bind(this);\n this.setImageExtension = this.setImageExtension.bind(this);\n this.getExtendedBounds = this.getExtendedBounds.bind(this);\n this.getAverageCenter = this.getAverageCenter.bind(this);\n this.setAverageCenter = this.setAverageCenter.bind(this);\n this.getTotalClusters = this.getTotalClusters.bind(this);\n this.fitMapToMarkers = this.fitMapToMarkers.bind(this);\n this.getIgnoreHidden = this.getIgnoreHidden.bind(this);\n this.setIgnoreHidden = this.setIgnoreHidden.bind(this);\n this.getClusterClass = this.getClusterClass.bind(this);\n this.setClusterClass = this.setClusterClass.bind(this);\n this.getTotalMarkers = this.getTotalMarkers.bind(this);\n this.getZoomOnClick = this.getZoomOnClick.bind(this);\n this.setZoomOnClick = this.setZoomOnClick.bind(this);\n this.getBatchSizeIE = this.getBatchSizeIE.bind(this);\n this.setBatchSizeIE = this.setBatchSizeIE.bind(this);\n this.createClusters = this.createClusters.bind(this);\n this.onZoomChanged = this.onZoomChanged.bind(this);\n this.getImageSizes = this.getImageSizes.bind(this);\n this.setImageSizes = this.setImageSizes.bind(this);\n this.getCalculator = this.getCalculator.bind(this);\n this.setCalculator = this.setCalculator.bind(this);\n this.removeMarkers = this.removeMarkers.bind(this);\n this.resetViewport = this.resetViewport.bind(this);\n this.getImagePath = this.getImagePath.bind(this);\n this.setImagePath = this.setImagePath.bind(this);\n this.pushMarkerTo = this.pushMarkerTo.bind(this);\n this.removeMarker = this.removeMarker.bind(this);\n this.clearMarkers = this.clearMarkers.bind(this);\n this.setupStyles = this.setupStyles.bind(this);\n this.getGridSize = this.getGridSize.bind(this);\n this.setGridSize = this.setGridSize.bind(this);\n this.getClusters = this.getClusters.bind(this);\n this.getMaxZoom = this.getMaxZoom.bind(this);\n this.setMaxZoom = this.setMaxZoom.bind(this);\n this.getMarkers = this.getMarkers.bind(this);\n this.addMarkers = this.addMarkers.bind(this);\n this.getStyles = this.getStyles.bind(this);\n this.setStyles = this.setStyles.bind(this);\n this.addMarker = this.addMarker.bind(this);\n this.onRemove = this.onRemove.bind(this);\n this.getTitle = this.getTitle.bind(this);\n this.setTitle = this.setTitle.bind(this);\n this.repaint = this.repaint.bind(this);\n this.onIdle = this.onIdle.bind(this);\n this.redraw = this.redraw.bind(this);\n this.onAdd = this.onAdd.bind(this);\n this.draw = this.draw.bind(this);\n this.extend = this.extend.bind(this);\n this.extend(Clusterer, google.maps.OverlayView);\n this.markers = [];\n this.clusters = [];\n this.listeners = [];\n this.activeMap = null;\n this.ready = false;\n this.gridSize = optOptions.gridSize || 60;\n this.minClusterSize = optOptions.minimumClusterSize || 2;\n this.maxZoom = optOptions.maxZoom || null;\n this.styles = optOptions.styles || [];\n this.title = optOptions.title || '';\n this.zoomOnClick = true;\n if (optOptions.zoomOnClick !== undefined) {\n this.zoomOnClick = optOptions.zoomOnClick;\n }\n this.averageCenter = false;\n if (optOptions.averageCenter !== undefined) {\n this.averageCenter = optOptions.averageCenter;\n }\n this.ignoreHidden = false;\n if (optOptions.ignoreHidden !== undefined) {\n this.ignoreHidden = optOptions.ignoreHidden;\n }\n this.enableRetinaIcons = false;\n if (optOptions.enableRetinaIcons !== undefined) {\n this.enableRetinaIcons = optOptions.enableRetinaIcons;\n }\n this.imagePath = optOptions.imagePath || IMAGE_PATH;\n this.imageExtension = optOptions.imageExtension || IMAGE_EXTENSION;\n this.imageSizes = optOptions.imageSizes || IMAGE_SIZES;\n this.calculator = optOptions.calculator || CALCULATOR;\n this.batchSize = optOptions.batchSize || BATCH_SIZE;\n this.batchSizeIE = optOptions.batchSizeIE || BATCH_SIZE_IE;\n this.clusterClass = optOptions.clusterClass || CLUSTERER_CLASS;\n if (navigator.userAgent.toLowerCase().indexOf('msie') !== -1) {\n // Try to avoid IE timeout when processing a huge number of markers:\n this.batchSize = this.batchSizeIE;\n }\n this.timerRefStatic = null;\n this.setupStyles();\n this.addMarkers(optMarkers, true);\n this.setMap(map); // Note: this causes onAdd to be called\n }\n Clusterer.prototype.onZoomChanged = function () {\n var _a, _b;\n this.resetViewport(false);\n // Workaround for this Google bug: when map is at level 0 and \"-\" of\n // zoom slider is clicked, a \"zoom_changed\" event is fired even though\n // the map doesn't zoom out any further. In this situation, no \"idle\"\n // event is triggered so the cluster markers that have been removed\n // do not get redrawn. Same goes for a zoom in at maxZoom.\n if (((_a = this.getMap()) === null || _a === void 0 ? void 0 : _a.getZoom()) === (this.get('minZoom') || 0) || ((_b = this.getMap()) === null || _b === void 0 ? void 0 : _b.getZoom()) === this.get('maxZoom')) {\n google.maps.event.trigger(this, 'idle');\n }\n };\n Clusterer.prototype.onIdle = function () {\n this.redraw();\n };\n Clusterer.prototype.onAdd = function () {\n var map = this.getMap();\n this.activeMap = map;\n this.ready = true;\n this.repaint();\n if (map !== null) {\n // Add the map event listeners\n this.listeners = [google.maps.event.addListener(map, 'zoom_changed', this.onZoomChanged), google.maps.event.addListener(map, 'idle', this.onIdle)];\n }\n };\n Clusterer.prototype.onRemove = function () {\n // Put all the managed markers back on the map:\n for (var _i = 0, _a = this.markers; _i < _a.length; _i++) {\n var marker = _a[_i];\n if (marker.getMap() !== this.activeMap) {\n marker.setMap(this.activeMap);\n }\n }\n // Remove all clusters:\n for (var _b = 0, _c = this.clusters; _b < _c.length; _b++) {\n var cluster = _c[_b];\n cluster.remove();\n }\n this.clusters = [];\n // Remove map event listeners:\n for (var _d = 0, _e = this.listeners; _d < _e.length; _d++) {\n var listener = _e[_d];\n google.maps.event.removeListener(listener);\n }\n this.listeners = [];\n this.activeMap = null;\n this.ready = false;\n };\n Clusterer.prototype.draw = function () {\n return;\n };\n Clusterer.prototype.getMap = function () {\n return null;\n };\n Clusterer.prototype.getPanes = function () {\n return null;\n };\n Clusterer.prototype.getProjection = function () {\n return {\n fromContainerPixelToLatLng: function fromContainerPixelToLatLng() {\n return null;\n },\n fromDivPixelToLatLng: function fromDivPixelToLatLng() {\n return null;\n },\n fromLatLngToContainerPixel: function fromLatLngToContainerPixel() {\n return null;\n },\n fromLatLngToDivPixel: function fromLatLngToDivPixel() {\n return null;\n },\n getVisibleRegion: function getVisibleRegion() {\n return null;\n },\n getWorldWidth: function getWorldWidth() {\n return 0;\n }\n };\n };\n Clusterer.prototype.setMap = function () {\n return;\n };\n Clusterer.prototype.addListener = function () {\n return {\n remove: function remove() {\n return;\n }\n };\n };\n Clusterer.prototype.bindTo = function () {\n return;\n };\n Clusterer.prototype.get = function () {\n return;\n };\n Clusterer.prototype.notify = function () {\n return;\n };\n Clusterer.prototype.set = function () {\n return;\n };\n Clusterer.prototype.setValues = function () {\n return;\n };\n Clusterer.prototype.unbind = function () {\n return;\n };\n Clusterer.prototype.unbindAll = function () {\n return;\n };\n Clusterer.prototype.setupStyles = function () {\n if (this.styles.length > 0) {\n return;\n }\n for (var i = 0; i < this.imageSizes.length; i++) {\n this.styles.push({\n url: \"\".concat(this.imagePath + (i + 1), \".\").concat(this.imageExtension),\n height: this.imageSizes[i] || 0,\n width: this.imageSizes[i] || 0\n });\n }\n };\n Clusterer.prototype.fitMapToMarkers = function () {\n var markers = this.getMarkers();\n var bounds = new google.maps.LatLngBounds();\n for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {\n var marker = markers_1[_i];\n var position = marker.getPosition();\n if (position) {\n bounds.extend(position);\n }\n }\n var map = this.getMap();\n if (map !== null && 'fitBounds' in map) {\n map.fitBounds(bounds);\n }\n };\n Clusterer.prototype.getGridSize = function () {\n return this.gridSize;\n };\n Clusterer.prototype.setGridSize = function (gridSize) {\n this.gridSize = gridSize;\n };\n Clusterer.prototype.getMinimumClusterSize = function () {\n return this.minClusterSize;\n };\n Clusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {\n this.minClusterSize = minimumClusterSize;\n };\n Clusterer.prototype.getMaxZoom = function () {\n return this.maxZoom;\n };\n Clusterer.prototype.setMaxZoom = function (maxZoom) {\n this.maxZoom = maxZoom;\n };\n Clusterer.prototype.getStyles = function () {\n return this.styles;\n };\n Clusterer.prototype.setStyles = function (styles) {\n this.styles = styles;\n };\n Clusterer.prototype.getTitle = function () {\n return this.title;\n };\n Clusterer.prototype.setTitle = function (title) {\n this.title = title;\n };\n Clusterer.prototype.getZoomOnClick = function () {\n return this.zoomOnClick;\n };\n Clusterer.prototype.setZoomOnClick = function (zoomOnClick) {\n this.zoomOnClick = zoomOnClick;\n };\n Clusterer.prototype.getAverageCenter = function () {\n return this.averageCenter;\n };\n Clusterer.prototype.setAverageCenter = function (averageCenter) {\n this.averageCenter = averageCenter;\n };\n Clusterer.prototype.getIgnoreHidden = function () {\n return this.ignoreHidden;\n };\n Clusterer.prototype.setIgnoreHidden = function (ignoreHidden) {\n this.ignoreHidden = ignoreHidden;\n };\n Clusterer.prototype.getEnableRetinaIcons = function () {\n return this.enableRetinaIcons;\n };\n Clusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {\n this.enableRetinaIcons = enableRetinaIcons;\n };\n Clusterer.prototype.getImageExtension = function () {\n return this.imageExtension;\n };\n Clusterer.prototype.setImageExtension = function (imageExtension) {\n this.imageExtension = imageExtension;\n };\n Clusterer.prototype.getImagePath = function () {\n return this.imagePath;\n };\n Clusterer.prototype.setImagePath = function (imagePath) {\n this.imagePath = imagePath;\n };\n Clusterer.prototype.getImageSizes = function () {\n return this.imageSizes;\n };\n Clusterer.prototype.setImageSizes = function (imageSizes) {\n this.imageSizes = imageSizes;\n };\n Clusterer.prototype.getCalculator = function () {\n return this.calculator;\n };\n Clusterer.prototype.setCalculator = function (calculator) {\n this.calculator = calculator;\n };\n Clusterer.prototype.getBatchSizeIE = function () {\n return this.batchSizeIE;\n };\n Clusterer.prototype.setBatchSizeIE = function (batchSizeIE) {\n this.batchSizeIE = batchSizeIE;\n };\n Clusterer.prototype.getClusterClass = function () {\n return this.clusterClass;\n };\n Clusterer.prototype.setClusterClass = function (clusterClass) {\n this.clusterClass = clusterClass;\n };\n Clusterer.prototype.getMarkers = function () {\n return this.markers;\n };\n Clusterer.prototype.getTotalMarkers = function () {\n return this.markers.length;\n };\n Clusterer.prototype.getClusters = function () {\n return this.clusters;\n };\n Clusterer.prototype.getTotalClusters = function () {\n return this.clusters.length;\n };\n Clusterer.prototype.addMarker = function (marker, optNoDraw) {\n this.pushMarkerTo(marker);\n if (!optNoDraw) {\n this.redraw();\n }\n };\n Clusterer.prototype.addMarkers = function (markers, optNoDraw) {\n for (var key in markers) {\n if (Object.prototype.hasOwnProperty.call(markers, key)) {\n var marker = markers[key];\n if (marker) {\n this.pushMarkerTo(marker);\n }\n }\n }\n if (!optNoDraw) {\n this.redraw();\n }\n };\n Clusterer.prototype.pushMarkerTo = function (marker) {\n var _this = this;\n // If the marker is draggable add a listener so we can update the clusters on the dragend:\n if (marker.getDraggable()) {\n google.maps.event.addListener(marker, 'dragend', function () {\n if (_this.ready) {\n marker.isAdded = false;\n _this.repaint();\n }\n });\n }\n marker.isAdded = false;\n this.markers.push(marker);\n };\n Clusterer.prototype.removeMarker_ = function (marker) {\n var index = -1;\n if (this.markers.indexOf) {\n index = this.markers.indexOf(marker);\n } else {\n for (var i = 0; i < this.markers.length; i++) {\n if (marker === this.markers[i]) {\n index = i;\n break;\n }\n }\n }\n if (index === -1) {\n // Marker is not in our list of markers, so do nothing:\n return false;\n }\n marker.setMap(null);\n this.markers.splice(index, 1); // Remove the marker from the list of managed markers\n return true;\n };\n Clusterer.prototype.removeMarker = function (marker, optNoDraw) {\n var removed = this.removeMarker_(marker);\n if (!optNoDraw && removed) {\n this.repaint();\n }\n return removed;\n };\n Clusterer.prototype.removeMarkers = function (markers, optNoDraw) {\n var removed = false;\n for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {\n var marker = markers_2[_i];\n removed = removed || this.removeMarker_(marker);\n }\n if (!optNoDraw && removed) {\n this.repaint();\n }\n return removed;\n };\n Clusterer.prototype.clearMarkers = function () {\n this.resetViewport(true);\n this.markers = [];\n };\n Clusterer.prototype.repaint = function () {\n var oldClusters = this.clusters.slice();\n this.clusters = [];\n this.resetViewport(false);\n this.redraw();\n // Remove the old clusters.\n // Do it in a timeout to prevent blinking effect.\n setTimeout(function timeout() {\n for (var _i = 0, oldClusters_1 = oldClusters; _i < oldClusters_1.length; _i++) {\n var oldCluster = oldClusters_1[_i];\n oldCluster.remove();\n }\n }, 0);\n };\n Clusterer.prototype.getExtendedBounds = function (bounds) {\n var projection = this.getProjection();\n // Convert the points to pixels and the extend out by the grid size.\n var trPix = projection.fromLatLngToDivPixel(\n // Turn the bounds into latlng.\n new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()));\n if (trPix !== null) {\n trPix.x += this.gridSize;\n trPix.y -= this.gridSize;\n }\n var blPix = projection.fromLatLngToDivPixel(\n // Turn the bounds into latlng.\n new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()));\n if (blPix !== null) {\n blPix.x -= this.gridSize;\n blPix.y += this.gridSize;\n }\n // Extend the bounds to contain the new bounds.\n if (trPix !== null) {\n // Convert the pixel points back to LatLng nw\n var point1 = projection.fromDivPixelToLatLng(trPix);\n if (point1 !== null) {\n bounds.extend(point1);\n }\n }\n if (blPix !== null) {\n // Convert the pixel points back to LatLng sw\n var point2 = projection.fromDivPixelToLatLng(blPix);\n if (point2 !== null) {\n bounds.extend(point2);\n }\n }\n return bounds;\n };\n Clusterer.prototype.redraw = function () {\n // Redraws all the clusters.\n this.createClusters(0);\n };\n Clusterer.prototype.resetViewport = function (optHide) {\n // Remove all the clusters\n for (var _i = 0, _a = this.clusters; _i < _a.length; _i++) {\n var cluster = _a[_i];\n cluster.remove();\n }\n this.clusters = [];\n // Reset the markers to not be added and to be removed from the map.\n for (var _b = 0, _c = this.markers; _b < _c.length; _b++) {\n var marker = _c[_b];\n marker.isAdded = false;\n if (optHide) {\n marker.setMap(null);\n }\n }\n };\n Clusterer.prototype.distanceBetweenPoints = function (p1, p2) {\n var R = 6371; // Radius of the Earth in km\n var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;\n var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;\n var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n return R * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));\n };\n Clusterer.prototype.isMarkerInBounds = function (marker, bounds) {\n var position = marker.getPosition();\n if (position) {\n return bounds.contains(position);\n }\n return false;\n };\n Clusterer.prototype.addToClosestCluster = function (marker) {\n var cluster;\n var distance = 40000; // Some large number\n var clusterToAddTo = null;\n for (var _i = 0, _a = this.clusters; _i < _a.length; _i++) {\n var clusterElement = _a[_i];\n cluster = clusterElement;\n var center = cluster.getCenter();\n var position = marker.getPosition();\n if (center && position) {\n var d = this.distanceBetweenPoints(center, position);\n if (d < distance) {\n distance = d;\n clusterToAddTo = cluster;\n }\n }\n }\n if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {\n clusterToAddTo.addMarker(marker);\n } else {\n cluster = new Cluster$1(this);\n cluster.addMarker(marker);\n this.clusters.push(cluster);\n }\n };\n Clusterer.prototype.createClusters = function (iFirst) {\n var _this = this;\n if (!this.ready) {\n return;\n }\n // Cancel previous batch processing if we're working on the first batch:\n if (iFirst === 0) {\n /**\n * This event is fired when the Clusterer begins\n * clustering markers.\n * @name Clusterer#clusteringbegin\n * @param {Clusterer} mc The Clusterer whose markers are being clustered.\n * @event\n */\n google.maps.event.trigger(this, 'clusteringbegin', this);\n if (this.timerRefStatic !== null) {\n window.clearTimeout(this.timerRefStatic);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n delete this.timerRefStatic;\n }\n }\n var map = this.getMap();\n var bounds = map !== null && 'getBounds' in map ? map.getBounds() : null;\n var zoom = (map === null || map === void 0 ? void 0 : map.getZoom()) || 0;\n // Get our current map view bounds.\n // Create a new bounds object so we don't affect the map.\n //\n // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:\n var mapBounds = zoom > 3 ? new google.maps.LatLngBounds(bounds === null || bounds === void 0 ? void 0 : bounds.getSouthWest(), bounds === null || bounds === void 0 ? void 0 : bounds.getNorthEast()) : new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));\n var extendedMapBounds = this.getExtendedBounds(mapBounds);\n var iLast = Math.min(iFirst + this.batchSize, this.markers.length);\n for (var i = iFirst; i < iLast; i++) {\n var marker = this.markers[i];\n if (marker && !marker.isAdded && this.isMarkerInBounds(marker, extendedMapBounds) && (!this.ignoreHidden || this.ignoreHidden && marker.getVisible())) {\n this.addToClosestCluster(marker);\n }\n }\n if (iLast < this.markers.length) {\n this.timerRefStatic = window.setTimeout(function () {\n _this.createClusters(iLast);\n }, 0);\n } else {\n this.timerRefStatic = null;\n /**\n * This event is fired when the Clusterer stops\n * clustering markers.\n * @name Clusterer#clusteringend\n * @param {Clusterer} mc The Clusterer whose markers are being clustered.\n * @event\n */\n google.maps.event.trigger(this, 'clusteringend', this);\n for (var _i = 0, _a = this.clusters; _i < _a.length; _i++) {\n var cluster = _a[_i];\n cluster.updateIcon();\n }\n }\n };\n Clusterer.prototype.extend = function (obj1, obj2) {\n return function applyExtend(object) {\n for (var property in object.prototype) {\n // eslint-disable-next-line @typescript-eslint/ban-types\n var prop = property;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.prototype[prop] = object.prototype[prop];\n }\n return this;\n }.apply(obj1, [obj2]);\n };\n return Clusterer;\n}();\n\nfunction ownKeys$c(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$c(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$c(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$c(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$e = {\n onClick: 'click',\n onClusteringBegin: 'clusteringbegin',\n onClusteringEnd: 'clusteringend',\n onMouseOut: 'mouseout',\n onMouseOver: 'mouseover'\n};\nvar updaterMap$e = {\n averageCenter(instance, averageCenter) {\n instance.setAverageCenter(averageCenter);\n },\n batchSizeIE(instance, batchSizeIE) {\n instance.setBatchSizeIE(batchSizeIE);\n },\n calculator(instance, calculator) {\n instance.setCalculator(calculator);\n },\n clusterClass(instance, clusterClass) {\n instance.setClusterClass(clusterClass);\n },\n enableRetinaIcons(instance, enableRetinaIcons) {\n instance.setEnableRetinaIcons(enableRetinaIcons);\n },\n gridSize(instance, gridSize) {\n instance.setGridSize(gridSize);\n },\n ignoreHidden(instance, ignoreHidden) {\n instance.setIgnoreHidden(ignoreHidden);\n },\n imageExtension(instance, imageExtension) {\n instance.setImageExtension(imageExtension);\n },\n imagePath(instance, imagePath) {\n instance.setImagePath(imagePath);\n },\n imageSizes(instance, imageSizes) {\n instance.setImageSizes(imageSizes);\n },\n maxZoom(instance, maxZoom) {\n instance.setMaxZoom(maxZoom);\n },\n minimumClusterSize(instance, minimumClusterSize) {\n instance.setMinimumClusterSize(minimumClusterSize);\n },\n styles(instance, styles) {\n instance.setStyles(styles);\n },\n title(instance, title) {\n instance.setTitle(title);\n },\n zoomOnClick(instance, zoomOnClick) {\n instance.setZoomOnClick(zoomOnClick);\n }\n};\nvar defaultOptions$4 = {};\nfunction MarkerClustererFunctional(props) {\n var {\n children,\n options,\n averageCenter,\n batchSizeIE,\n calculator,\n clusterClass,\n enableRetinaIcons,\n gridSize,\n ignoreHidden,\n imageExtension,\n imagePath,\n imageSizes,\n maxZoom,\n minimumClusterSize,\n styles,\n title,\n zoomOnClick,\n onClick,\n onClusteringBegin,\n onClusteringEnd,\n onMouseOver,\n onMouseOut,\n onLoad,\n onUnmount\n } = props;\n var [instance, setInstance] = useState(null);\n var map = useContext(MapContext);\n var [clickListener, setClickListener] = useState(null);\n var [clusteringBeginListener, setClusteringBeginListener] = useState(null);\n var [clusteringEndListener, setClusteringEndListener] = useState(null);\n var [mouseoutListener, setMouseoutListener] = useState(null);\n var [mouseoverListener, setMouseoverListener] = useState(null);\n useEffect(() => {\n if (instance && onMouseOut) {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n setMouseoutListener(google.maps.event.addListener(instance, eventMap$e.onMouseOut, onMouseOut));\n }\n }, [onMouseOut]);\n useEffect(() => {\n if (instance && onMouseOver) {\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n setMouseoverListener(google.maps.event.addListener(instance, eventMap$e.onMouseOver, onMouseOver));\n }\n }, [onMouseOver]);\n useEffect(() => {\n if (instance && onClick) {\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n setClickListener(google.maps.event.addListener(instance, eventMap$e.onClick, onClick));\n }\n }, [onClick]);\n useEffect(() => {\n if (instance && onClusteringBegin) {\n if (clusteringBeginListener !== null) {\n google.maps.event.removeListener(clusteringBeginListener);\n }\n setClusteringBeginListener(google.maps.event.addListener(instance, eventMap$e.onClusteringBegin, onClusteringBegin));\n }\n }, [onClusteringBegin]);\n useEffect(() => {\n if (instance && onClusteringEnd) {\n if (clusteringEndListener !== null) {\n google.maps.event.removeListener(clusteringEndListener);\n }\n setClusteringBeginListener(google.maps.event.addListener(instance, eventMap$e.onClusteringEnd, onClusteringEnd));\n }\n }, [onClusteringEnd]);\n useEffect(() => {\n if (typeof averageCenter !== 'undefined' && instance !== null) {\n updaterMap$e.averageCenter(instance, averageCenter);\n }\n }, [instance, averageCenter]);\n useEffect(() => {\n if (typeof batchSizeIE !== 'undefined' && instance !== null) {\n updaterMap$e.batchSizeIE(instance, batchSizeIE);\n }\n }, [instance, batchSizeIE]);\n useEffect(() => {\n if (typeof calculator !== 'undefined' && instance !== null) {\n updaterMap$e.calculator(instance, calculator);\n }\n }, [instance, calculator]);\n useEffect(() => {\n if (typeof clusterClass !== 'undefined' && instance !== null) {\n updaterMap$e.clusterClass(instance, clusterClass);\n }\n }, [instance, clusterClass]);\n useEffect(() => {\n if (typeof enableRetinaIcons !== 'undefined' && instance !== null) {\n updaterMap$e.enableRetinaIcons(instance, enableRetinaIcons);\n }\n }, [instance, enableRetinaIcons]);\n useEffect(() => {\n if (typeof gridSize !== 'undefined' && instance !== null) {\n updaterMap$e.gridSize(instance, gridSize);\n }\n }, [instance, gridSize]);\n useEffect(() => {\n if (typeof ignoreHidden !== 'undefined' && instance !== null) {\n updaterMap$e.ignoreHidden(instance, ignoreHidden);\n }\n }, [instance, ignoreHidden]);\n useEffect(() => {\n if (typeof imageExtension !== 'undefined' && instance !== null) {\n updaterMap$e.imageExtension(instance, imageExtension);\n }\n }, [instance, imageExtension]);\n useEffect(() => {\n if (typeof imagePath !== 'undefined' && instance !== null) {\n updaterMap$e.imagePath(instance, imagePath);\n }\n }, [instance, imagePath]);\n useEffect(() => {\n if (typeof imageSizes !== 'undefined' && instance !== null) {\n updaterMap$e.imageSizes(instance, imageSizes);\n }\n }, [instance, imageSizes]);\n useEffect(() => {\n if (typeof maxZoom !== 'undefined' && instance !== null) {\n updaterMap$e.maxZoom(instance, maxZoom);\n }\n }, [instance, maxZoom]);\n useEffect(() => {\n if (typeof minimumClusterSize !== 'undefined' && instance !== null) {\n updaterMap$e.minimumClusterSize(instance, minimumClusterSize);\n }\n }, [instance, minimumClusterSize]);\n useEffect(() => {\n if (typeof styles !== 'undefined' && instance !== null) {\n updaterMap$e.styles(instance, styles);\n }\n }, [instance, styles]);\n useEffect(() => {\n if (typeof title !== 'undefined' && instance !== null) {\n updaterMap$e.title(instance, title);\n }\n }, [instance, title]);\n useEffect(() => {\n if (typeof zoomOnClick !== 'undefined' && instance !== null) {\n updaterMap$e.zoomOnClick(instance, zoomOnClick);\n }\n }, [instance, zoomOnClick]);\n useEffect(() => {\n if (!map) return;\n var clustererOptions = _objectSpread$c({}, options || defaultOptions$4);\n var clusterer = new Clusterer(map, [], clustererOptions);\n if (averageCenter) {\n updaterMap$e.averageCenter(clusterer, averageCenter);\n }\n if (batchSizeIE) {\n updaterMap$e.batchSizeIE(clusterer, batchSizeIE);\n }\n if (calculator) {\n updaterMap$e.calculator(clusterer, calculator);\n }\n if (clusterClass) {\n updaterMap$e.clusterClass(clusterer, clusterClass);\n }\n if (enableRetinaIcons) {\n updaterMap$e.enableRetinaIcons(clusterer, enableRetinaIcons);\n }\n if (gridSize) {\n updaterMap$e.gridSize(clusterer, gridSize);\n }\n if (ignoreHidden) {\n updaterMap$e.ignoreHidden(clusterer, ignoreHidden);\n }\n if (imageExtension) {\n updaterMap$e.imageExtension(clusterer, imageExtension);\n }\n if (imagePath) {\n updaterMap$e.imagePath(clusterer, imagePath);\n }\n if (imageSizes) {\n updaterMap$e.imageSizes(clusterer, imageSizes);\n }\n if (maxZoom) {\n updaterMap$e.maxZoom(clusterer, maxZoom);\n }\n if (minimumClusterSize) {\n updaterMap$e.minimumClusterSize(clusterer, minimumClusterSize);\n }\n if (styles) {\n updaterMap$e.styles(clusterer, styles);\n }\n if (title) {\n updaterMap$e.title(clusterer, title);\n }\n if (zoomOnClick) {\n updaterMap$e.zoomOnClick(clusterer, zoomOnClick);\n }\n if (onMouseOut) {\n setMouseoutListener(google.maps.event.addListener(clusterer, eventMap$e.onMouseOut, onMouseOut));\n }\n if (onMouseOver) {\n setMouseoverListener(google.maps.event.addListener(clusterer, eventMap$e.onMouseOver, onMouseOver));\n }\n if (onClick) {\n setClickListener(google.maps.event.addListener(clusterer, eventMap$e.onClick, onClick));\n }\n if (onClusteringBegin) {\n setClusteringBeginListener(google.maps.event.addListener(clusterer, eventMap$e.onClusteringBegin, onClusteringBegin));\n }\n if (onClusteringEnd) {\n setClusteringEndListener(google.maps.event.addListener(clusterer, eventMap$e.onClusteringEnd, onClusteringEnd));\n }\n setInstance(clusterer);\n if (onLoad) {\n onLoad(clusterer);\n }\n return () => {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n if (clusteringBeginListener !== null) {\n google.maps.event.removeListener(clusteringBeginListener);\n }\n if (clusteringEndListener !== null) {\n google.maps.event.removeListener(clusteringEndListener);\n }\n if (onUnmount) {\n onUnmount(clusterer);\n }\n };\n }, []);\n return instance !== null ? children(instance) || null : null;\n}\nvar MarkerClustererF = memo(MarkerClustererFunctional);\nclass ClustererComponent extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n markerClusterer: null\n });\n _defineProperty(this, \"setClustererCallback\", () => {\n if (this.state.markerClusterer !== null && this.props.onLoad) {\n this.props.onLoad(this.state.markerClusterer);\n }\n });\n }\n componentDidMount() {\n if (this.context) {\n var markerClusterer = new Clusterer(this.context, [], this.props.options);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$e,\n eventMap: eventMap$e,\n prevProps: {},\n nextProps: this.props,\n instance: markerClusterer\n });\n this.setState(() => {\n return {\n markerClusterer\n };\n }, this.setClustererCallback);\n }\n }\n componentDidUpdate(prevProps) {\n if (this.state.markerClusterer) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$e,\n eventMap: eventMap$e,\n prevProps,\n nextProps: this.props,\n instance: this.state.markerClusterer\n });\n }\n }\n componentWillUnmount() {\n if (this.state.markerClusterer !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.markerClusterer);\n }\n unregisterEvents(this.registeredEvents);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.state.markerClusterer.setMap(null);\n }\n }\n render() {\n return this.state.markerClusterer !== null ? this.props.children(this.state.markerClusterer) : null;\n }\n}\n_defineProperty(ClustererComponent, \"contextType\", MapContext);\n\n// This handler prevents an event in the InfoBox from being passed on to the map.\nfunction cancelHandler(event) {\n event.cancelBubble = true;\n if (event.stopPropagation) {\n event.stopPropagation();\n }\n}\nvar InfoBox = /** @class */function () {\n function InfoBox(options) {\n if (options === void 0) {\n options = {};\n }\n this.getCloseClickHandler = this.getCloseClickHandler.bind(this);\n this.closeClickHandler = this.closeClickHandler.bind(this);\n this.createInfoBoxDiv = this.createInfoBoxDiv.bind(this);\n this.addClickHandler = this.addClickHandler.bind(this);\n this.getCloseBoxImg = this.getCloseBoxImg.bind(this);\n this.getBoxWidths = this.getBoxWidths.bind(this);\n this.setBoxStyle = this.setBoxStyle.bind(this);\n this.setPosition = this.setPosition.bind(this);\n this.getPosition = this.getPosition.bind(this);\n this.setOptions = this.setOptions.bind(this);\n this.setContent = this.setContent.bind(this);\n this.setVisible = this.setVisible.bind(this);\n this.getContent = this.getContent.bind(this);\n this.getVisible = this.getVisible.bind(this);\n this.setZIndex = this.setZIndex.bind(this);\n this.getZIndex = this.getZIndex.bind(this);\n this.onRemove = this.onRemove.bind(this);\n this.panBox = this.panBox.bind(this);\n this.extend = this.extend.bind(this);\n this.close = this.close.bind(this);\n this.draw = this.draw.bind(this);\n this.show = this.show.bind(this);\n this.hide = this.hide.bind(this);\n this.open = this.open.bind(this);\n this.extend(InfoBox, google.maps.OverlayView);\n // Standard options (in common with google.maps.InfoWindow):\n this.content = options.content || '';\n this.disableAutoPan = options.disableAutoPan || false;\n this.maxWidth = options.maxWidth || 0;\n this.pixelOffset = options.pixelOffset || new google.maps.Size(0, 0);\n this.position = options.position || new google.maps.LatLng(0, 0);\n this.zIndex = options.zIndex || null;\n // Additional options (unique to InfoBox):\n this.boxClass = options.boxClass || 'infoBox';\n this.boxStyle = options.boxStyle || {};\n this.closeBoxMargin = options.closeBoxMargin || '2px';\n this.closeBoxURL = options.closeBoxURL || 'http://www.google.com/intl/en_us/mapfiles/close.gif';\n if (options.closeBoxURL === '') {\n this.closeBoxURL = '';\n }\n this.infoBoxClearance = options.infoBoxClearance || new google.maps.Size(1, 1);\n if (typeof options.visible === 'undefined') {\n if (typeof options.isHidden === 'undefined') {\n options.visible = true;\n } else {\n options.visible = !options.isHidden;\n }\n }\n this.isHidden = !options.visible;\n this.alignBottom = options.alignBottom || false;\n this.pane = options.pane || 'floatPane';\n this.enableEventPropagation = options.enableEventPropagation || false;\n this.div = null;\n this.closeListener = null;\n this.moveListener = null;\n this.mapListener = null;\n this.contextListener = null;\n this.eventListeners = null;\n this.fixedWidthSet = null;\n }\n InfoBox.prototype.createInfoBoxDiv = function () {\n var _this = this;\n // This handler ignores the current event in the InfoBox and conditionally prevents\n // the event from being passed on to the map. It is used for the contextmenu event.\n var ignoreHandler = function ignoreHandler(event) {\n event.returnValue = false;\n if (event.preventDefault) {\n event.preventDefault();\n }\n if (!_this.enableEventPropagation) {\n cancelHandler(event);\n }\n };\n if (!this.div) {\n this.div = document.createElement('div');\n this.setBoxStyle();\n if (typeof this.content === 'string') {\n this.div.innerHTML = this.getCloseBoxImg() + this.content;\n } else {\n this.div.innerHTML = this.getCloseBoxImg();\n this.div.appendChild(this.content);\n }\n var panes = this.getPanes();\n if (panes !== null) {\n panes[this.pane].appendChild(this.div); // Add the InfoBox div to the DOM\n }\n this.addClickHandler();\n if (this.div.style.width) {\n this.fixedWidthSet = true;\n } else {\n if (this.maxWidth !== 0 && this.div.offsetWidth > this.maxWidth) {\n this.div.style.width = this.maxWidth + 'px';\n this.fixedWidthSet = true;\n } else {\n // The following code is needed to overcome problems with MSIE\n var bw = this.getBoxWidths();\n this.div.style.width = this.div.offsetWidth - bw.left - bw.right + 'px';\n this.fixedWidthSet = false;\n }\n }\n this.panBox(this.disableAutoPan);\n if (!this.enableEventPropagation) {\n this.eventListeners = [];\n // Cancel event propagation.\n // Note: mousemove not included (to resolve Issue 152)\n var events = ['mousedown', 'mouseover', 'mouseout', 'mouseup', 'click', 'dblclick', 'touchstart', 'touchend', 'touchmove'];\n for (var _i = 0, events_1 = events; _i < events_1.length; _i++) {\n var event_1 = events_1[_i];\n this.eventListeners.push(google.maps.event.addListener(this.div, event_1, cancelHandler));\n }\n // Workaround for Google bug that causes the cursor to change to a pointer\n // when the mouse moves over a marker underneath InfoBox.\n this.eventListeners.push(google.maps.event.addListener(this.div, 'mouseover', function () {\n if (_this.div) {\n _this.div.style.cursor = 'default';\n }\n }));\n }\n this.contextListener = google.maps.event.addListener(this.div, 'contextmenu', ignoreHandler);\n /**\n * This event is fired when the DIV containing the InfoBox's content is attached to the DOM.\n * @name InfoBox#domready\n * @event\n */\n google.maps.event.trigger(this, 'domready');\n }\n };\n InfoBox.prototype.getCloseBoxImg = function () {\n var img = '';\n if (this.closeBoxURL !== '') {\n img = '\"\"';\n\";\n }\n return img;\n };\n InfoBox.prototype.addClickHandler = function () {\n this.closeListener = this.div && this.div.firstChild && this.closeBoxURL !== '' ? google.maps.event.addListener(this.div.firstChild, 'click', this.getCloseClickHandler()) : null;\n };\n InfoBox.prototype.closeClickHandler = function (event) {\n // 1.0.3 fix: Always prevent propagation of a close box click to the map:\n event.cancelBubble = true;\n if (event.stopPropagation) {\n event.stopPropagation();\n }\n /**\n * This event is fired when the InfoBox's close box is clicked.\n * @name InfoBox#closeclick\n * @event\n */\n google.maps.event.trigger(this, 'closeclick');\n this.close();\n };\n InfoBox.prototype.getCloseClickHandler = function () {\n return this.closeClickHandler;\n };\n InfoBox.prototype.panBox = function (disablePan) {\n if (this.div && !disablePan) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n var map = this.getMap();\n // Only pan if attached to map, not panorama\n if (map instanceof google.maps.Map) {\n var xOffset = 0;\n var yOffset = 0;\n var bounds = map.getBounds();\n if (bounds && !bounds.contains(this.position)) {\n // Marker not in visible area of map, so set center\n // of map to the marker position first.\n map.setCenter(this.position);\n }\n var mapDiv = map.getDiv();\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n var mapWidth = mapDiv.offsetWidth;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n var mapHeight = mapDiv.offsetHeight;\n var iwOffsetX = this.pixelOffset.width;\n var iwOffsetY = this.pixelOffset.height;\n var iwWidth = this.div.offsetWidth;\n var iwHeight = this.div.offsetHeight;\n var padX = this.infoBoxClearance.width;\n var padY = this.infoBoxClearance.height;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n var projection = this.getProjection();\n var pixPosition = projection.fromLatLngToContainerPixel(this.position);\n if (pixPosition !== null) {\n if (pixPosition.x < -iwOffsetX + padX) {\n xOffset = pixPosition.x + iwOffsetX - padX;\n } else if (pixPosition.x + iwWidth + iwOffsetX + padX > mapWidth) {\n xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth;\n }\n if (this.alignBottom) {\n if (pixPosition.y < -iwOffsetY + padY + iwHeight) {\n yOffset = pixPosition.y + iwOffsetY - padY - iwHeight;\n } else if (pixPosition.y + iwOffsetY + padY > mapHeight) {\n yOffset = pixPosition.y + iwOffsetY + padY - mapHeight;\n }\n } else {\n if (pixPosition.y < -iwOffsetY + padY) {\n yOffset = pixPosition.y + iwOffsetY - padY;\n } else if (pixPosition.y + iwHeight + iwOffsetY + padY > mapHeight) {\n yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight;\n }\n }\n }\n if (!(xOffset === 0 && yOffset === 0)) {\n // Move the map to the shifted center.\n map.panBy(xOffset, yOffset);\n }\n }\n }\n };\n InfoBox.prototype.setBoxStyle = function () {\n if (this.div) {\n // Apply style values from the style sheet defined in the boxClass parameter:\n this.div.className = this.boxClass;\n // Clear existing inline style values:\n this.div.style.cssText = '';\n // Apply style values defined in the boxStyle parameter:\n var boxStyle = this.boxStyle;\n for (var i in boxStyle) {\n if (Object.prototype.hasOwnProperty.call(boxStyle, i)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.div.style[i] = boxStyle[i];\n }\n }\n // Fix for iOS disappearing InfoBox problem\n // See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad\n this.div.style.webkitTransform = 'translateZ(0)';\n // Fix up opacity style for benefit of MSIE\n if (typeof this.div.style.opacity !== 'undefined' && this.div.style.opacity !== '') {\n // See http://www.quirksmode.org/css/opacity.html\n var opacity = parseFloat(this.div.style.opacity || '');\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.div.style.msFilter = '\"progid:DXImageTransform.Microsoft.Alpha(Opacity=' + opacity * 100 + ')\"';\n this.div.style.filter = 'alpha(opacity=' + opacity * 100 + ')';\n }\n // Apply required styles\n this.div.style.position = 'absolute';\n this.div.style.visibility = 'hidden';\n if (this.zIndex !== null) {\n this.div.style.zIndex = this.zIndex + '';\n }\n if (!this.div.style.overflow) {\n this.div.style.overflow = 'auto';\n }\n }\n };\n InfoBox.prototype.getBoxWidths = function () {\n var bw = {\n top: 0,\n bottom: 0,\n left: 0,\n right: 0\n };\n if (!this.div) {\n return bw;\n }\n if (document.defaultView) {\n var ownerDocument = this.div.ownerDocument;\n var computedStyle = ownerDocument && ownerDocument.defaultView ? ownerDocument.defaultView.getComputedStyle(this.div, '') : null;\n if (computedStyle) {\n // The computed styles are always in pixel units (good!)\n bw.top = parseInt(computedStyle.borderTopWidth || '', 10) || 0;\n bw.bottom = parseInt(computedStyle.borderBottomWidth || '', 10) || 0;\n bw.left = parseInt(computedStyle.borderLeftWidth || '', 10) || 0;\n bw.right = parseInt(computedStyle.borderRightWidth || '', 10) || 0;\n }\n } else if (\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n document.documentElement.currentStyle // MSIE\n ) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n var currentStyle = this.div.currentStyle;\n if (currentStyle) {\n // The current styles may not be in pixel units, but assume they are (bad!)\n bw.top = parseInt(currentStyle.borderTopWidth || '', 10) || 0;\n bw.bottom = parseInt(currentStyle.borderBottomWidth || '', 10) || 0;\n bw.left = parseInt(currentStyle.borderLeftWidth || '', 10) || 0;\n bw.right = parseInt(currentStyle.borderRightWidth || '', 10) || 0;\n }\n }\n return bw;\n };\n InfoBox.prototype.onRemove = function () {\n if (this.div && this.div.parentNode) {\n this.div.parentNode.removeChild(this.div);\n this.div = null;\n }\n };\n InfoBox.prototype.draw = function () {\n this.createInfoBoxDiv();\n if (this.div) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n var projection = this.getProjection();\n var pixPosition = projection.fromLatLngToDivPixel(this.position);\n if (pixPosition !== null) {\n this.div.style.left = pixPosition.x + this.pixelOffset.width + 'px';\n if (this.alignBottom) {\n this.div.style.bottom = -(pixPosition.y + this.pixelOffset.height) + 'px';\n } else {\n this.div.style.top = pixPosition.y + this.pixelOffset.height + 'px';\n }\n }\n if (this.isHidden) {\n this.div.style.visibility = 'hidden';\n } else {\n this.div.style.visibility = 'visible';\n }\n }\n };\n InfoBox.prototype.setOptions = function (options) {\n if (options === void 0) {\n options = {};\n }\n if (typeof options.boxClass !== 'undefined') {\n // Must be first\n this.boxClass = options.boxClass;\n this.setBoxStyle();\n }\n if (typeof options.boxStyle !== 'undefined') {\n // Must be second\n this.boxStyle = options.boxStyle;\n this.setBoxStyle();\n }\n if (typeof options.content !== 'undefined') {\n this.setContent(options.content);\n }\n if (typeof options.disableAutoPan !== 'undefined') {\n this.disableAutoPan = options.disableAutoPan;\n }\n if (typeof options.maxWidth !== 'undefined') {\n this.maxWidth = options.maxWidth;\n }\n if (typeof options.pixelOffset !== 'undefined') {\n this.pixelOffset = options.pixelOffset;\n }\n if (typeof options.alignBottom !== 'undefined') {\n this.alignBottom = options.alignBottom;\n }\n if (typeof options.position !== 'undefined') {\n this.setPosition(options.position);\n }\n if (typeof options.zIndex !== 'undefined') {\n this.setZIndex(options.zIndex);\n }\n if (typeof options.closeBoxMargin !== 'undefined') {\n this.closeBoxMargin = options.closeBoxMargin;\n }\n if (typeof options.closeBoxURL !== 'undefined') {\n this.closeBoxURL = options.closeBoxURL;\n }\n if (typeof options.infoBoxClearance !== 'undefined') {\n this.infoBoxClearance = options.infoBoxClearance;\n }\n if (typeof options.isHidden !== 'undefined') {\n this.isHidden = options.isHidden;\n }\n if (typeof options.visible !== 'undefined') {\n this.isHidden = !options.visible;\n }\n if (typeof options.enableEventPropagation !== 'undefined') {\n this.enableEventPropagation = options.enableEventPropagation;\n }\n if (this.div) {\n this.draw();\n }\n };\n InfoBox.prototype.setContent = function (content) {\n this.content = content;\n if (this.div) {\n if (this.closeListener) {\n google.maps.event.removeListener(this.closeListener);\n this.closeListener = null;\n }\n // Odd code required to make things work with MSIE.\n if (!this.fixedWidthSet) {\n this.div.style.width = '';\n }\n if (typeof content === 'string') {\n this.div.innerHTML = this.getCloseBoxImg() + content;\n } else {\n this.div.innerHTML = this.getCloseBoxImg();\n this.div.appendChild(content);\n }\n // Perverse code required to make things work with MSIE.\n // (Ensures the close box does, in fact, float to the right.)\n if (!this.fixedWidthSet) {\n this.div.style.width = this.div.offsetWidth + 'px';\n if (typeof content === 'string') {\n this.div.innerHTML = this.getCloseBoxImg() + content;\n } else {\n this.div.innerHTML = this.getCloseBoxImg();\n this.div.appendChild(content);\n }\n }\n this.addClickHandler();\n }\n /**\n * This event is fired when the content of the InfoBox changes.\n * @name InfoBox#content_changed\n * @event\n */\n google.maps.event.trigger(this, 'content_changed');\n };\n InfoBox.prototype.setPosition = function (latLng) {\n this.position = latLng;\n if (this.div) {\n this.draw();\n }\n /**\n * This event is fired when the position of the InfoBox changes.\n * @name InfoBox#position_changed\n * @event\n */\n google.maps.event.trigger(this, 'position_changed');\n };\n InfoBox.prototype.setVisible = function (isVisible) {\n this.isHidden = !isVisible;\n if (this.div) {\n this.div.style.visibility = this.isHidden ? 'hidden' : 'visible';\n }\n };\n InfoBox.prototype.setZIndex = function (index) {\n this.zIndex = index;\n if (this.div) {\n this.div.style.zIndex = index + '';\n }\n /**\n * This event is fired when the zIndex of the InfoBox changes.\n * @name InfoBox#zindex_changed\n * @event\n */\n google.maps.event.trigger(this, 'zindex_changed');\n };\n InfoBox.prototype.getContent = function () {\n return this.content;\n };\n InfoBox.prototype.getPosition = function () {\n return this.position;\n };\n InfoBox.prototype.getZIndex = function () {\n return this.zIndex;\n };\n InfoBox.prototype.getVisible = function () {\n var map = this.getMap();\n return typeof map === 'undefined' || map === null ? false : !this.isHidden;\n };\n InfoBox.prototype.show = function () {\n this.isHidden = false;\n if (this.div) {\n this.div.style.visibility = 'visible';\n }\n };\n InfoBox.prototype.hide = function () {\n this.isHidden = true;\n if (this.div) {\n this.div.style.visibility = 'hidden';\n }\n };\n InfoBox.prototype.open = function (map, anchor) {\n var _this = this;\n if (anchor) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.position = anchor.getPosition();\n this.moveListener = google.maps.event.addListener(anchor, 'position_changed', function () {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n var position = anchor.getPosition();\n _this.setPosition(position);\n });\n this.mapListener = google.maps.event.addListener(anchor, 'map_changed', function () {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n _this.setMap(anchor.map);\n });\n }\n this.setMap(map);\n if (this.div) {\n this.panBox();\n }\n };\n InfoBox.prototype.close = function () {\n if (this.closeListener) {\n google.maps.event.removeListener(this.closeListener);\n this.closeListener = null;\n }\n if (this.eventListeners) {\n for (var _i = 0, _a = this.eventListeners; _i < _a.length; _i++) {\n var eventListener = _a[_i];\n google.maps.event.removeListener(eventListener);\n }\n this.eventListeners = null;\n }\n if (this.moveListener) {\n google.maps.event.removeListener(this.moveListener);\n this.moveListener = null;\n }\n if (this.mapListener) {\n google.maps.event.removeListener(this.mapListener);\n this.mapListener = null;\n }\n if (this.contextListener) {\n google.maps.event.removeListener(this.contextListener);\n this.contextListener = null;\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.setMap(null);\n };\n InfoBox.prototype.extend = function (obj1, obj2) {\n return function applyExtend(object) {\n for (var property in object.prototype) {\n if (!Object.prototype.hasOwnProperty.call(this, property)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.prototype[property] = object.prototype[property];\n }\n }\n return this;\n }.apply(obj1, [obj2]);\n };\n return InfoBox;\n}();\n\nvar _excluded = [\"position\"],\n _excluded2 = [\"position\"];\nfunction ownKeys$b(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$b(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$b(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$b(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$d = {\n onCloseClick: 'closeclick',\n onContentChanged: 'content_changed',\n onDomReady: 'domready',\n onPositionChanged: 'position_changed',\n onZindexChanged: 'zindex_changed'\n};\nvar updaterMap$d = {\n options(instance, options) {\n instance.setOptions(options);\n },\n position(instance, position) {\n if (position instanceof google.maps.LatLng) {\n instance.setPosition(position);\n } else {\n instance.setPosition(new google.maps.LatLng(position.lat, position.lng));\n }\n },\n visible(instance, visible) {\n instance.setVisible(visible);\n },\n zIndex(instance, zIndex) {\n instance.setZIndex(zIndex);\n }\n};\nvar defaultOptions$3 = {};\nfunction InfoBoxFunctional(_ref) {\n var {\n children,\n anchor,\n options,\n position,\n zIndex,\n onCloseClick,\n onDomReady,\n onContentChanged,\n onPositionChanged,\n onZindexChanged,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [closeClickListener, setCloseClickListener] = useState(null);\n var [domReadyClickListener, setDomReadyClickListener] = useState(null);\n var [contentChangedClickListener, setContentChangedClickListener] = useState(null);\n var [positionChangedClickListener, setPositionChangedClickListener] = useState(null);\n var [zIndexChangedClickListener, setZindexChangedClickListener] = useState(null);\n var containerElementRef = useRef(null);\n // Order does matter\n useEffect(() => {\n if (map && instance !== null) {\n instance.close();\n if (anchor) {\n instance.open(map, anchor);\n } else if (instance.getPosition()) {\n instance.open(map);\n }\n }\n }, [map, instance, anchor]);\n useEffect(() => {\n if (options && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n if (position && instance !== null) {\n var positionLatLng = position instanceof google.maps.LatLng ? position :\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n new google.maps.LatLng(position.lat, position.lng);\n instance.setPosition(positionLatLng);\n }\n }, [position]);\n useEffect(() => {\n if (typeof zIndex === 'number' && instance !== null) {\n instance.setZIndex(zIndex);\n }\n }, [zIndex]);\n useEffect(() => {\n if (instance && onCloseClick) {\n if (closeClickListener !== null) {\n google.maps.event.removeListener(closeClickListener);\n }\n setCloseClickListener(google.maps.event.addListener(instance, 'closeclick', onCloseClick));\n }\n }, [onCloseClick]);\n useEffect(() => {\n if (instance && onDomReady) {\n if (domReadyClickListener !== null) {\n google.maps.event.removeListener(domReadyClickListener);\n }\n setDomReadyClickListener(google.maps.event.addListener(instance, 'domready', onDomReady));\n }\n }, [onDomReady]);\n useEffect(() => {\n if (instance && onContentChanged) {\n if (contentChangedClickListener !== null) {\n google.maps.event.removeListener(contentChangedClickListener);\n }\n setContentChangedClickListener(google.maps.event.addListener(instance, 'content_changed', onContentChanged));\n }\n }, [onContentChanged]);\n useEffect(() => {\n if (instance && onPositionChanged) {\n if (positionChangedClickListener !== null) {\n google.maps.event.removeListener(positionChangedClickListener);\n }\n setPositionChangedClickListener(google.maps.event.addListener(instance, 'position_changed', onPositionChanged));\n }\n }, [onPositionChanged]);\n useEffect(() => {\n if (instance && onZindexChanged) {\n if (zIndexChangedClickListener !== null) {\n google.maps.event.removeListener(zIndexChangedClickListener);\n }\n setZindexChangedClickListener(google.maps.event.addListener(instance, 'zindex_changed', onZindexChanged));\n }\n }, [onZindexChanged]);\n useEffect(() => {\n if (map) {\n var _ref2 = options || defaultOptions$3,\n {\n position: _position\n } = _ref2,\n infoBoxOptions = _objectWithoutProperties(_ref2, _excluded);\n var positionLatLng;\n if (_position && !(_position instanceof google.maps.LatLng)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n positionLatLng = new google.maps.LatLng(_position.lat, _position.lng);\n }\n var infoBox = new InfoBox(_objectSpread$b(_objectSpread$b({}, infoBoxOptions), positionLatLng ? {\n position: positionLatLng\n } : {}));\n containerElementRef.current = document.createElement('div');\n setInstance(infoBox);\n if (onCloseClick) {\n setCloseClickListener(google.maps.event.addListener(infoBox, 'closeclick', onCloseClick));\n }\n if (onDomReady) {\n setDomReadyClickListener(google.maps.event.addListener(infoBox, 'domready', onDomReady));\n }\n if (onContentChanged) {\n setContentChangedClickListener(google.maps.event.addListener(infoBox, 'content_changed', onContentChanged));\n }\n if (onPositionChanged) {\n setPositionChangedClickListener(google.maps.event.addListener(infoBox, 'position_changed', onPositionChanged));\n }\n if (onZindexChanged) {\n setZindexChangedClickListener(google.maps.event.addListener(infoBox, 'zindex_changed', onZindexChanged));\n }\n infoBox.setContent(containerElementRef.current);\n if (anchor) {\n infoBox.open(map, anchor);\n } else if (infoBox.getPosition()) {\n infoBox.open(map);\n } else {\n invariant(false, 'You must provide either an anchor or a position prop for .');\n }\n if (onLoad) {\n onLoad(infoBox);\n }\n }\n return () => {\n if (instance !== null) {\n if (closeClickListener) {\n google.maps.event.removeListener(closeClickListener);\n }\n if (contentChangedClickListener) {\n google.maps.event.removeListener(contentChangedClickListener);\n }\n if (domReadyClickListener) {\n google.maps.event.removeListener(domReadyClickListener);\n }\n if (positionChangedClickListener) {\n google.maps.event.removeListener(positionChangedClickListener);\n }\n if (zIndexChangedClickListener) {\n google.maps.event.removeListener(zIndexChangedClickListener);\n }\n if (onUnmount) {\n onUnmount(instance);\n }\n instance.close();\n }\n };\n }, []);\n return containerElementRef.current ? createPortal(Children.only(children), containerElementRef.current) : null;\n}\nvar InfoBoxF = memo(InfoBoxFunctional);\nclass InfoBoxComponent extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"containerElement\", null);\n _defineProperty(this, \"state\", {\n infoBox: null\n });\n _defineProperty(this, \"open\", (infoBox, anchor) => {\n if (anchor) {\n if (this.context !== null) {\n infoBox.open(this.context, anchor);\n }\n } else if (infoBox.getPosition()) {\n if (this.context !== null) {\n infoBox.open(this.context);\n }\n } else {\n invariant(false, 'You must provide either an anchor or a position prop for .');\n }\n });\n _defineProperty(this, \"setInfoBoxCallback\", () => {\n if (this.state.infoBox !== null && this.containerElement !== null) {\n this.state.infoBox.setContent(this.containerElement);\n this.open(this.state.infoBox, this.props.anchor);\n if (this.props.onLoad) {\n this.props.onLoad(this.state.infoBox);\n }\n }\n });\n }\n componentDidMount() {\n var _ref3 = this.props.options || {},\n {\n position\n } = _ref3,\n infoBoxOptions = _objectWithoutProperties(_ref3, _excluded2);\n var positionLatLng;\n if (position && !(position instanceof google.maps.LatLng)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n positionLatLng = new google.maps.LatLng(position.lat, position.lng);\n }\n var infoBox = new InfoBox(_objectSpread$b(_objectSpread$b({}, infoBoxOptions), positionLatLng ? {\n position: positionLatLng\n } : {}));\n this.containerElement = document.createElement('div');\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$d,\n eventMap: eventMap$d,\n prevProps: {},\n nextProps: this.props,\n instance: infoBox\n });\n this.setState({\n infoBox\n }, this.setInfoBoxCallback);\n }\n componentDidUpdate(prevProps) {\n var {\n infoBox\n } = this.state;\n if (infoBox !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$d,\n eventMap: eventMap$d,\n prevProps,\n nextProps: this.props,\n instance: infoBox\n });\n }\n }\n componentWillUnmount() {\n var {\n onUnmount\n } = this.props;\n var {\n infoBox\n } = this.state;\n if (infoBox !== null) {\n if (onUnmount) {\n onUnmount(infoBox);\n }\n unregisterEvents(this.registeredEvents);\n infoBox.close();\n }\n }\n render() {\n return this.containerElement ? createPortal(Children.only(this.props.children), this.containerElement) : null;\n }\n}\n_defineProperty(InfoBoxComponent, \"contextType\", MapContext);\n\nvar fastDeepEqual;\nvar hasRequiredFastDeepEqual;\nfunction requireFastDeepEqual() {\n if (hasRequiredFastDeepEqual) return fastDeepEqual;\n hasRequiredFastDeepEqual = 1;\n\n // do not edit .js files directly - edit src/index.jst\n\n fastDeepEqual = function equal(a, b) {\n if (a === b) return true;\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;\n return true;\n }\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n if (!equal(a[key], b[key])) return false;\n }\n return true;\n }\n\n // true if both NaN, false otherwise\n return a !== a && b !== b;\n };\n return fastDeepEqual;\n}\n\nvar fastDeepEqualExports = requireFastDeepEqual();\nvar equal = /*@__PURE__*/getDefaultExportFromCjs$1(fastDeepEqualExports);\n\nvar ARRAY_TYPES = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];\n\n/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */\n\nvar VERSION = 1; // serialized format version\nvar HEADER_SIZE = 8;\nclass KDBush {\n /**\n * Creates an index from raw `ArrayBuffer` data.\n * @param {ArrayBuffer} data\n */\n static from(data) {\n if (!(data instanceof ArrayBuffer)) {\n throw new Error('Data must be an instance of ArrayBuffer.');\n }\n var [magic, versionAndType] = new Uint8Array(data, 0, 2);\n if (magic !== 0xdb) {\n throw new Error('Data does not appear to be in a KDBush format.');\n }\n var version = versionAndType >> 4;\n if (version !== VERSION) {\n throw new Error(\"Got v\".concat(version, \" data when expected v\").concat(VERSION, \".\"));\n }\n var ArrayType = ARRAY_TYPES[versionAndType & 0x0f];\n if (!ArrayType) {\n throw new Error('Unrecognized array type.');\n }\n var [nodeSize] = new Uint16Array(data, 2, 1);\n var [numItems] = new Uint32Array(data, 4, 1);\n return new KDBush(numItems, nodeSize, ArrayType, data);\n }\n\n /**\n * Creates an index that will hold a given number of items.\n * @param {number} numItems\n * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).\n * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).\n * @param {ArrayBuffer} [data] (For internal use only)\n */\n constructor(numItems) {\n var nodeSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 64;\n var ArrayType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Float64Array;\n var data = arguments.length > 3 ? arguments[3] : undefined;\n if (isNaN(numItems) || numItems < 0) throw new Error(\"Unpexpected numItems value: \".concat(numItems, \".\"));\n this.numItems = +numItems;\n this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);\n this.ArrayType = ArrayType;\n this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;\n var arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);\n var coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;\n var idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;\n var padCoords = (8 - idsByteSize % 8) % 8;\n if (arrayTypeIndex < 0) {\n throw new Error(\"Unexpected typed array class: \".concat(ArrayType, \".\"));\n }\n if (data && data instanceof ArrayBuffer) {\n // reconstruct an index from a buffer\n this.data = data;\n this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);\n this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = numItems * 2;\n this._finished = true;\n } else {\n // initialize a new index\n this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);\n this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);\n this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = 0;\n this._finished = false;\n\n // set header\n new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);\n new Uint16Array(this.data, 2, 1)[0] = nodeSize;\n new Uint32Array(this.data, 4, 1)[0] = numItems;\n }\n }\n\n /**\n * Add a point to the index.\n * @param {number} x\n * @param {number} y\n * @returns {number} An incremental index associated with the added item (starting from `0`).\n */\n add(x, y) {\n var index = this._pos >> 1;\n this.ids[index] = index;\n this.coords[this._pos++] = x;\n this.coords[this._pos++] = y;\n return index;\n }\n\n /**\n * Perform indexing of the added points.\n */\n finish() {\n var numAdded = this._pos >> 1;\n if (numAdded !== this.numItems) {\n throw new Error(\"Added \".concat(numAdded, \" items when expected \").concat(this.numItems, \".\"));\n }\n // kd-sort both arrays for efficient search\n sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);\n this._finished = true;\n return this;\n }\n\n /**\n * Search the index for items within a given bounding box.\n * @param {number} minX\n * @param {number} minY\n * @param {number} maxX\n * @param {number} maxY\n * @returns {number[]} An array of indices correponding to the found items.\n */\n range(minX, minY, maxX, maxY) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n var {\n ids,\n coords,\n nodeSize\n } = this;\n var stack = [0, ids.length - 1, 0];\n var result = [];\n\n // recursively search for items in range in the kd-sorted arrays\n while (stack.length) {\n var axis = stack.pop() || 0;\n var right = stack.pop() || 0;\n var left = stack.pop() || 0;\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (var i = left; i <= right; i++) {\n var _x = coords[2 * i];\n var _y = coords[2 * i + 1];\n if (_x >= minX && _x <= maxX && _y >= minY && _y <= maxY) result.push(ids[i]);\n }\n continue;\n }\n\n // otherwise find the middle index\n var m = left + right >> 1;\n\n // include the middle item if it's in range\n var x = coords[2 * m];\n var y = coords[2 * m + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\n // queue search in halves that intersect the query\n if (axis === 0 ? minX <= x : minY <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(1 - axis);\n }\n if (axis === 0 ? maxX >= x : maxY >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(1 - axis);\n }\n }\n return result;\n }\n\n /**\n * Search the index for items within a given radius.\n * @param {number} qx\n * @param {number} qy\n * @param {number} r Query radius.\n * @returns {number[]} An array of indices correponding to the found items.\n */\n within(qx, qy, r) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n var {\n ids,\n coords,\n nodeSize\n } = this;\n var stack = [0, ids.length - 1, 0];\n var result = [];\n var r2 = r * r;\n\n // recursively search for items within radius in the kd-sorted arrays\n while (stack.length) {\n var axis = stack.pop() || 0;\n var right = stack.pop() || 0;\n var left = stack.pop() || 0;\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (var i = left; i <= right; i++) {\n if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);\n }\n continue;\n }\n\n // otherwise find the middle index\n var m = left + right >> 1;\n\n // include the middle item if it's in range\n var x = coords[2 * m];\n var y = coords[2 * m + 1];\n if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);\n\n // queue search in halves that intersect the query\n if (axis === 0 ? qx - r <= x : qy - r <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(1 - axis);\n }\n if (axis === 0 ? qx + r >= x : qy + r >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(1 - axis);\n }\n }\n return result;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType} coords\n * @param {number} nodeSize\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction sort(ids, coords, nodeSize, left, right, axis) {\n if (right - left <= nodeSize) return;\n var m = left + right >> 1; // middle index\n\n // sort ids and coords around the middle index so that the halves lie\n // either left/right or top/bottom correspondingly (taking turns)\n select(ids, coords, m, left, right, axis);\n\n // recursively kd-sort first half and second half on the opposite axis\n sort(ids, coords, nodeSize, left, m - 1, 1 - axis);\n sort(ids, coords, nodeSize, m + 1, right, 1 - axis);\n}\n\n/**\n * Custom Floyd-Rivest selection algorithm: sort ids and coords so that\n * [left..k-1] items are smaller than k-th item (on either x or y axis)\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType} coords\n * @param {number} k\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction select(ids, coords, k, left, right, axis) {\n while (right > left) {\n if (right - left > 600) {\n var n = right - left + 1;\n var m = k - left + 1;\n var z = Math.log(n);\n var s = 0.5 * Math.exp(2 * z / 3);\n var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n select(ids, coords, k, newLeft, newRight, axis);\n }\n var t = coords[2 * k + axis];\n var i = left;\n var j = right;\n swapItem(ids, coords, left, k);\n if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);\n while (i < j) {\n swapItem(ids, coords, i, j);\n i++;\n j--;\n while (coords[2 * i + axis] < t) i++;\n while (coords[2 * j + axis] > t) j--;\n }\n if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);else {\n j++;\n swapItem(ids, coords, j, right);\n }\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType} coords\n * @param {number} i\n * @param {number} j\n */\nfunction swapItem(ids, coords, i, j) {\n swap(ids, i, j);\n swap(coords, 2 * i, 2 * j);\n swap(coords, 2 * i + 1, 2 * j + 1);\n}\n\n/**\n * @param {InstanceType} arr\n * @param {number} i\n * @param {number} j\n */\nfunction swap(arr, i, j) {\n var tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\n/**\n * @param {number} ax\n * @param {number} ay\n * @param {number} bx\n * @param {number} by\n */\nfunction sqDist(ax, ay, bx, by) {\n var dx = ax - bx;\n var dy = ay - by;\n return dx * dx + dy * dy;\n}\n\nvar defaultOptions$2 = {\n minZoom: 0,\n // min zoom to generate clusters on\n maxZoom: 16,\n // max zoom level to cluster the points on\n minPoints: 2,\n // minimum points to form a cluster\n radius: 40,\n // cluster radius in pixels\n extent: 512,\n // tile extent (radius is calculated relative to it)\n nodeSize: 64,\n // size of the KD-tree leaf node, affects performance\n log: false,\n // whether to log timing info\n\n // whether to generate numeric ids for input features (in vector tiles)\n generateId: false,\n // a reduce function for calculating custom cluster properties\n reduce: null,\n // (accumulated, props) => { accumulated.sum += props.sum; }\n\n // properties to use for individual points when running the reducer\n map: props => props // props => ({sum: props.my_value})\n};\nvar fround = Math.fround || (tmp => x => {\n tmp[0] = +x;\n return tmp[0];\n})(new Float32Array(1));\nvar OFFSET_ZOOM = 2;\nvar OFFSET_ID = 3;\nvar OFFSET_PARENT = 4;\nvar OFFSET_NUM = 5;\nvar OFFSET_PROP = 6;\nclass Supercluster {\n constructor(options) {\n this.options = Object.assign(Object.create(defaultOptions$2), options);\n this.trees = new Array(this.options.maxZoom + 1);\n this.stride = this.options.reduce ? 7 : 6;\n this.clusterProps = [];\n }\n load(points) {\n var {\n log,\n minZoom,\n maxZoom\n } = this.options;\n if (log) console.time('total time');\n var timerId = \"prepare \".concat(points.length, \" points\");\n if (log) console.time(timerId);\n this.points = points;\n\n // generate a cluster object for each point and index input points into a KD-tree\n var data = [];\n for (var i = 0; i < points.length; i++) {\n var p = points[i];\n if (!p.geometry) continue;\n var [lng, lat] = p.geometry.coordinates;\n var x = fround(lngX(lng));\n var y = fround(latY(lat));\n // store internal point/cluster data in flat numeric arrays for performance\n data.push(x, y,\n // projected point coordinates\n Infinity,\n // the last zoom the point was processed at\n i,\n // index of the source feature in the original input array\n -1,\n // parent cluster id\n 1 // number of points in a cluster\n );\n if (this.options.reduce) data.push(0); // noop\n }\n var tree = this.trees[maxZoom + 1] = this._createTree(data);\n if (log) console.timeEnd(timerId);\n\n // cluster points on max zoom, then cluster the results on previous zoom, etc.;\n // results in a cluster hierarchy across zoom levels\n for (var z = maxZoom; z >= minZoom; z--) {\n var now = +Date.now();\n\n // create a new set of clusters for the zoom and index them with a KD-tree\n tree = this.trees[z] = this._createTree(this._cluster(tree, z));\n if (log) console.log('z%d: %d clusters in %dms', z, tree.numItems, +Date.now() - now);\n }\n if (log) console.timeEnd('total time');\n return this;\n }\n getClusters(bbox, zoom) {\n var minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;\n var minLat = Math.max(-90, Math.min(90, bbox[1]));\n var maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;\n var maxLat = Math.max(-90, Math.min(90, bbox[3]));\n if (bbox[2] - bbox[0] >= 360) {\n minLng = -180;\n maxLng = 180;\n } else if (minLng > maxLng) {\n var easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom);\n var westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom);\n return easternHem.concat(westernHem);\n }\n var tree = this.trees[this._limitZoom(zoom)];\n var ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat));\n var data = tree.data;\n var clusters = [];\n for (var id of ids) {\n var k = this.stride * id;\n clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);\n }\n return clusters;\n }\n getChildren(clusterId) {\n var originId = this._getOriginId(clusterId);\n var originZoom = this._getOriginZoom(clusterId);\n var errorMsg = 'No cluster with the specified id.';\n var tree = this.trees[originZoom];\n if (!tree) throw new Error(errorMsg);\n var data = tree.data;\n if (originId * this.stride >= data.length) throw new Error(errorMsg);\n var r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));\n var x = data[originId * this.stride];\n var y = data[originId * this.stride + 1];\n var ids = tree.within(x, y, r);\n var children = [];\n for (var id of ids) {\n var k = id * this.stride;\n if (data[k + OFFSET_PARENT] === clusterId) {\n children.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);\n }\n }\n if (children.length === 0) throw new Error(errorMsg);\n return children;\n }\n getLeaves(clusterId, limit, offset) {\n limit = limit || 10;\n offset = offset || 0;\n var leaves = [];\n this._appendLeaves(leaves, clusterId, limit, offset, 0);\n return leaves;\n }\n getTile(z, x, y) {\n var tree = this.trees[this._limitZoom(z)];\n var z2 = Math.pow(2, z);\n var {\n extent,\n radius\n } = this.options;\n var p = radius / extent;\n var top = (y - p) / z2;\n var bottom = (y + 1 + p) / z2;\n var tile = {\n features: []\n };\n this._addTileFeatures(tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), tree.data, x, y, z2, tile);\n if (x === 0) {\n this._addTileFeatures(tree.range(1 - p / z2, top, 1, bottom), tree.data, z2, y, z2, tile);\n }\n if (x === z2 - 1) {\n this._addTileFeatures(tree.range(0, top, p / z2, bottom), tree.data, -1, y, z2, tile);\n }\n return tile.features.length ? tile : null;\n }\n getClusterExpansionZoom(clusterId) {\n var expansionZoom = this._getOriginZoom(clusterId) - 1;\n while (expansionZoom <= this.options.maxZoom) {\n var children = this.getChildren(clusterId);\n expansionZoom++;\n if (children.length !== 1) break;\n clusterId = children[0].properties.cluster_id;\n }\n return expansionZoom;\n }\n _appendLeaves(result, clusterId, limit, offset, skipped) {\n var children = this.getChildren(clusterId);\n for (var child of children) {\n var props = child.properties;\n if (props && props.cluster) {\n if (skipped + props.point_count <= offset) {\n // skip the whole cluster\n skipped += props.point_count;\n } else {\n // enter the cluster\n skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped);\n // exit the cluster\n }\n } else if (skipped < offset) {\n // skip a single point\n skipped++;\n } else {\n // add a single point\n result.push(child);\n }\n if (result.length === limit) break;\n }\n return skipped;\n }\n _createTree(data) {\n var tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array);\n for (var i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]);\n tree.finish();\n tree.data = data;\n return tree;\n }\n _addTileFeatures(ids, data, x, y, z2, tile) {\n for (var i of ids) {\n var k = i * this.stride;\n var isCluster = data[k + OFFSET_NUM] > 1;\n var tags = void 0,\n px = void 0,\n py = void 0;\n if (isCluster) {\n tags = getClusterProperties(data, k, this.clusterProps);\n px = data[k];\n py = data[k + 1];\n } else {\n var p = this.points[data[k + OFFSET_ID]];\n tags = p.properties;\n var [lng, lat] = p.geometry.coordinates;\n px = lngX(lng);\n py = latY(lat);\n }\n var f = {\n type: 1,\n geometry: [[Math.round(this.options.extent * (px * z2 - x)), Math.round(this.options.extent * (py * z2 - y))]],\n tags\n };\n\n // assign id\n var id = void 0;\n if (isCluster || this.options.generateId) {\n // optionally generate id for points\n id = data[k + OFFSET_ID];\n } else {\n // keep id if already assigned\n id = this.points[data[k + OFFSET_ID]].id;\n }\n if (id !== undefined) f.id = id;\n tile.features.push(f);\n }\n }\n _limitZoom(z) {\n return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));\n }\n _cluster(tree, zoom) {\n var {\n radius,\n extent,\n reduce,\n minPoints\n } = this.options;\n var r = radius / (extent * Math.pow(2, zoom));\n var data = tree.data;\n var nextData = [];\n var stride = this.stride;\n\n // loop through each point\n for (var i = 0; i < data.length; i += stride) {\n // if we've already visited the point at this zoom level, skip it\n if (data[i + OFFSET_ZOOM] <= zoom) continue;\n data[i + OFFSET_ZOOM] = zoom;\n\n // find all nearby points\n var x = data[i];\n var y = data[i + 1];\n var neighborIds = tree.within(data[i], data[i + 1], r);\n var numPointsOrigin = data[i + OFFSET_NUM];\n var numPoints = numPointsOrigin;\n\n // count the number of points in a potential cluster\n for (var neighborId of neighborIds) {\n var k = neighborId * stride;\n // filter out neighbors that are already processed\n if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM];\n }\n\n // if there were neighbors to merge, and there are enough points to form a cluster\n if (numPoints > numPointsOrigin && numPoints >= minPoints) {\n var wx = x * numPointsOrigin;\n var wy = y * numPointsOrigin;\n var clusterProperties = void 0;\n var clusterPropIndex = -1;\n\n // encode both zoom and point index on which the cluster originated -- offset by total length of features\n var id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length;\n for (var _neighborId of neighborIds) {\n var _k = _neighborId * stride;\n if (data[_k + OFFSET_ZOOM] <= zoom) continue;\n data[_k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice)\n\n var numPoints2 = data[_k + OFFSET_NUM];\n wx += data[_k] * numPoints2; // accumulate coordinates for calculating weighted center\n wy += data[_k + 1] * numPoints2;\n data[_k + OFFSET_PARENT] = id;\n if (reduce) {\n if (!clusterProperties) {\n clusterProperties = this._map(data, i, true);\n clusterPropIndex = this.clusterProps.length;\n this.clusterProps.push(clusterProperties);\n }\n reduce(clusterProperties, this._map(data, _k));\n }\n }\n data[i + OFFSET_PARENT] = id;\n nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints);\n if (reduce) nextData.push(clusterPropIndex);\n } else {\n // left points as unclustered\n for (var j = 0; j < stride; j++) nextData.push(data[i + j]);\n if (numPoints > 1) {\n for (var _neighborId2 of neighborIds) {\n var _k2 = _neighborId2 * stride;\n if (data[_k2 + OFFSET_ZOOM] <= zoom) continue;\n data[_k2 + OFFSET_ZOOM] = zoom;\n for (var _j = 0; _j < stride; _j++) nextData.push(data[_k2 + _j]);\n }\n }\n }\n }\n return nextData;\n }\n\n // get index of the point from which the cluster originated\n _getOriginId(clusterId) {\n return clusterId - this.points.length >> 5;\n }\n\n // get zoom of the point from which the cluster originated\n _getOriginZoom(clusterId) {\n return (clusterId - this.points.length) % 32;\n }\n _map(data, i, clone) {\n if (data[i + OFFSET_NUM] > 1) {\n var props = this.clusterProps[data[i + OFFSET_PROP]];\n return clone ? Object.assign({}, props) : props;\n }\n var original = this.points[data[i + OFFSET_ID]].properties;\n var result = this.options.map(original);\n return clone && result === original ? Object.assign({}, result) : result;\n }\n}\nfunction getClusterJSON(data, i, clusterProps) {\n return {\n type: 'Feature',\n id: data[i + OFFSET_ID],\n properties: getClusterProperties(data, i, clusterProps),\n geometry: {\n type: 'Point',\n coordinates: [xLng(data[i]), yLat(data[i + 1])]\n }\n };\n}\nfunction getClusterProperties(data, i, clusterProps) {\n var count = data[i + OFFSET_NUM];\n var abbrev = count >= 10000 ? \"\".concat(Math.round(count / 1000), \"k\") : count >= 1000 ? \"\".concat(Math.round(count / 100) / 10, \"k\") : count;\n var propIndex = data[i + OFFSET_PROP];\n var properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);\n return Object.assign(properties, {\n cluster: true,\n cluster_id: data[i + OFFSET_ID],\n point_count: count,\n point_count_abbreviated: abbrev\n });\n}\n\n// longitude/latitude to spherical mercator in [0..1] range\nfunction lngX(lng) {\n return lng / 360 + 0.5;\n}\nfunction latY(lat) {\n var sin = Math.sin(lat * Math.PI / 180);\n var y = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;\n return y < 0 ? 0 : y > 1 ? 1 : y;\n}\n\n// spherical mercator to longitude/latitude\nfunction xLng(x) {\n return (x - 0.5) * 360;\n}\nfunction yLat(y) {\n var y2 = (180 - y * 360) * Math.PI / 180;\n return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;\n}\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\n\nfunction __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];\n }\n return t;\n}\n\n/**\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * util class that creates a common set of convenience functions to wrap\n * shared behavior of Advanced Markers and Markers.\n */\nclass MarkerUtils {\n static isAdvancedMarkerAvailable(map) {\n return google.maps.marker && map.getMapCapabilities().isAdvancedMarkersAvailable === true;\n }\n static isAdvancedMarker(marker) {\n return google.maps.marker && marker instanceof google.maps.marker.AdvancedMarkerElement;\n }\n static setMap(marker, map) {\n if (this.isAdvancedMarker(marker)) {\n marker.map = map;\n } else {\n marker.setMap(map);\n }\n }\n static getPosition(marker) {\n // SuperClusterAlgorithm.calculate expects a LatLng instance so we fake it for Adv Markers\n if (this.isAdvancedMarker(marker)) {\n if (marker.position) {\n if (marker.position instanceof google.maps.LatLng) {\n return marker.position;\n }\n // since we can't cast to LatLngLiteral for reasons =(\n if (marker.position.lat && marker.position.lng) {\n return new google.maps.LatLng(marker.position.lat, marker.position.lng);\n }\n }\n return new google.maps.LatLng(null);\n }\n return marker.getPosition();\n }\n static getVisible(marker) {\n if (this.isAdvancedMarker(marker)) {\n /**\n * Always return true for Advanced Markers because the clusterer\n * uses getVisible as a way to count legacy markers not as an actual\n * indicator of visibility for some reason. Even when markers are hidden\n * Marker.getVisible returns `true` and this is used to set the marker count\n * on the cluster. See the behavior of Cluster.count\n */\n return true;\n }\n return marker.getVisible();\n }\n}\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Cluster {\n constructor(_ref) {\n var {\n markers,\n position\n } = _ref;\n this.markers = markers;\n if (position) {\n if (position instanceof google.maps.LatLng) {\n this._position = position;\n } else {\n this._position = new google.maps.LatLng(position);\n }\n }\n }\n get bounds() {\n if (this.markers.length === 0 && !this._position) {\n return;\n }\n var bounds = new google.maps.LatLngBounds(this._position, this._position);\n for (var marker of this.markers) {\n bounds.extend(MarkerUtils.getPosition(marker));\n }\n return bounds;\n }\n get position() {\n return this._position || this.bounds.getCenter();\n }\n /**\n * Get the count of **visible** markers.\n */\n get count() {\n return this.markers.filter(m => MarkerUtils.getVisible(m)).length;\n }\n /**\n * Add a marker to the cluster.\n */\n push(marker) {\n this.markers.push(marker);\n }\n /**\n * Cleanup references and remove marker from map.\n */\n delete() {\n if (this.marker) {\n MarkerUtils.setMap(this.marker, null);\n this.marker = undefined;\n }\n this.markers.length = 0;\n }\n}\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns the markers visible in a padded map viewport\n *\n * @param map\n * @param mapCanvasProjection\n * @param markers The list of marker to filter\n * @param viewportPaddingPixels The padding in pixel\n * @returns The list of markers in the padded viewport\n */\nvar filterMarkersToPaddedViewport = (map, mapCanvasProjection, markers, viewportPaddingPixels) => {\n var extendedMapBounds = extendBoundsToPaddedViewport(map.getBounds(), mapCanvasProjection, viewportPaddingPixels);\n return markers.filter(marker => extendedMapBounds.contains(MarkerUtils.getPosition(marker)));\n};\n/**\n * Extends a bounds by a number of pixels in each direction\n */\nvar extendBoundsToPaddedViewport = (bounds, projection, numPixels) => {\n var {\n northEast,\n southWest\n } = latLngBoundsToPixelBounds(bounds, projection);\n var extendedPixelBounds = extendPixelBounds({\n northEast,\n southWest\n }, numPixels);\n return pixelBoundsToLatLngBounds(extendedPixelBounds, projection);\n};\n/**\n * Gets the extended bounds as a bbox [westLng, southLat, eastLng, northLat]\n */\nvar getPaddedViewport = (bounds, projection, pixels) => {\n var extended = extendBoundsToPaddedViewport(bounds, projection, pixels);\n var ne = extended.getNorthEast();\n var sw = extended.getSouthWest();\n return [sw.lng(), sw.lat(), ne.lng(), ne.lat()];\n};\n/**\n * Returns the distance between 2 positions.\n *\n * @hidden\n */\nvar distanceBetweenPoints = (p1, p2) => {\n var R = 6371; // Radius of the Earth in km\n var dLat = (p2.lat - p1.lat) * Math.PI / 180;\n var dLon = (p2.lng - p1.lng) * Math.PI / 180;\n var sinDLat = Math.sin(dLat / 2);\n var sinDLon = Math.sin(dLon / 2);\n var a = sinDLat * sinDLat + Math.cos(p1.lat * Math.PI / 180) * Math.cos(p2.lat * Math.PI / 180) * sinDLon * sinDLon;\n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n return R * c;\n};\n/**\n * Converts a LatLng bound to pixels.\n *\n * @hidden\n */\nvar latLngBoundsToPixelBounds = (bounds, projection) => {\n return {\n northEast: projection.fromLatLngToDivPixel(bounds.getNorthEast()),\n southWest: projection.fromLatLngToDivPixel(bounds.getSouthWest())\n };\n};\n/**\n * Extends a pixel bounds by numPixels in all directions.\n *\n * @hidden\n */\nvar extendPixelBounds = (_ref2, numPixels) => {\n var {\n northEast,\n southWest\n } = _ref2;\n northEast.x += numPixels;\n northEast.y -= numPixels;\n southWest.x -= numPixels;\n southWest.y += numPixels;\n return {\n northEast,\n southWest\n };\n};\n/**\n * @hidden\n */\nvar pixelBoundsToLatLngBounds = (_ref3, projection) => {\n var {\n northEast,\n southWest\n } = _ref3;\n var sw = projection.fromDivPixelToLatLng(southWest);\n var ne = projection.fromDivPixelToLatLng(northEast);\n return new google.maps.LatLngBounds(sw, ne);\n};\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @hidden\n */\nclass AbstractAlgorithm {\n constructor(_ref4) {\n var {\n maxZoom = 16\n } = _ref4;\n this.maxZoom = maxZoom;\n }\n /**\n * Helper function to bypass clustering based upon some map state such as\n * zoom, number of markers, etc.\n *\n * ```typescript\n * cluster({markers, map}: AlgorithmInput): Cluster[] {\n * if (shouldBypassClustering(map)) {\n * return this.noop({markers})\n * }\n * }\n * ```\n */\n noop(_ref5) {\n var {\n markers\n } = _ref5;\n return noop$1(markers);\n }\n}\n/**\n * Abstract viewport algorithm proves a class to filter markers by a padded\n * viewport. This is a common optimization.\n *\n * @hidden\n */\nclass AbstractViewportAlgorithm extends AbstractAlgorithm {\n constructor(_a) {\n var {\n viewportPadding = 60\n } = _a,\n options = __rest(_a, [\"viewportPadding\"]);\n super(options);\n this.viewportPadding = 60;\n this.viewportPadding = viewportPadding;\n }\n calculate(_ref6) {\n var {\n markers,\n map,\n mapCanvasProjection\n } = _ref6;\n if (map.getZoom() >= this.maxZoom) {\n return {\n clusters: this.noop({\n markers\n }),\n changed: false\n };\n }\n return {\n clusters: this.cluster({\n markers: filterMarkersToPaddedViewport(map, mapCanvasProjection, markers, this.viewportPadding),\n map,\n mapCanvasProjection\n })\n };\n }\n}\n/**\n * @hidden\n */\nvar noop$1 = markers => {\n var clusters = markers.map(marker => new Cluster({\n position: MarkerUtils.getPosition(marker),\n markers: [marker]\n }));\n return clusters;\n};\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The default Grid algorithm historically used in Google Maps marker\n * clustering.\n *\n * The Grid algorithm does not implement caching and markers may flash as the\n * viewport changes. Instead use {@link SuperClusterAlgorithm}.\n */\nclass GridAlgorithm extends AbstractViewportAlgorithm {\n constructor(_a) {\n var {\n maxDistance = 40000,\n gridSize = 40\n } = _a,\n options = __rest(_a, [\"maxDistance\", \"gridSize\"]);\n super(options);\n this.clusters = [];\n this.state = {\n zoom: -1\n };\n this.maxDistance = maxDistance;\n this.gridSize = gridSize;\n }\n calculate(_ref7) {\n var {\n markers,\n map,\n mapCanvasProjection\n } = _ref7;\n var state = {\n zoom: map.getZoom()\n };\n var changed = false;\n if (this.state.zoom >= this.maxZoom && state.zoom >= this.maxZoom) ;else {\n changed = !equal(this.state, state);\n }\n this.state = state;\n if (map.getZoom() >= this.maxZoom) {\n return {\n clusters: this.noop({\n markers\n }),\n changed\n };\n }\n return {\n clusters: this.cluster({\n markers: filterMarkersToPaddedViewport(map, mapCanvasProjection, markers, this.viewportPadding),\n map,\n mapCanvasProjection\n })\n };\n }\n cluster(_ref8) {\n var {\n markers,\n map,\n mapCanvasProjection\n } = _ref8;\n this.clusters = [];\n markers.forEach(marker => {\n this.addToClosestCluster(marker, map, mapCanvasProjection);\n });\n return this.clusters;\n }\n addToClosestCluster(marker, map, projection) {\n var maxDistance = this.maxDistance; // Some large number\n var cluster = null;\n for (var i = 0; i < this.clusters.length; i++) {\n var candidate = this.clusters[i];\n var distance = distanceBetweenPoints(candidate.bounds.getCenter().toJSON(), MarkerUtils.getPosition(marker).toJSON());\n if (distance < maxDistance) {\n maxDistance = distance;\n cluster = candidate;\n }\n }\n if (cluster && extendBoundsToPaddedViewport(cluster.bounds, projection, this.gridSize).contains(MarkerUtils.getPosition(marker))) {\n cluster.push(marker);\n } else {\n var _cluster = new Cluster({\n markers: [marker]\n });\n this.clusters.push(_cluster);\n }\n }\n}\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Noop algorithm does not generate any clusters or filter markers by the an extended viewport.\n */\nclass NoopAlgorithm extends AbstractAlgorithm {\n constructor(_a) {\n var options = __rest(_a, []);\n super(options);\n }\n calculate(_ref9) {\n var {\n markers,\n map,\n mapCanvasProjection\n } = _ref9;\n return {\n clusters: this.cluster({\n markers,\n map,\n mapCanvasProjection\n }),\n changed: false\n };\n }\n cluster(input) {\n return this.noop(input);\n }\n}\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A very fast JavaScript algorithm for geospatial point clustering using KD trees.\n *\n * @see https://www.npmjs.com/package/supercluster for more information on options.\n */\nclass SuperClusterAlgorithm extends AbstractAlgorithm {\n constructor(_a) {\n var {\n maxZoom,\n radius = 60\n } = _a,\n options = __rest(_a, [\"maxZoom\", \"radius\"]);\n super({\n maxZoom\n });\n this.state = {\n zoom: -1\n };\n this.superCluster = new Supercluster(Object.assign({\n maxZoom: this.maxZoom,\n radius\n }, options));\n }\n calculate(input) {\n var changed = false;\n var state = {\n zoom: input.map.getZoom()\n };\n if (!equal(input.markers, this.markers)) {\n changed = true;\n // TODO use proxy to avoid copy?\n this.markers = [...input.markers];\n var points = this.markers.map(marker => {\n var position = MarkerUtils.getPosition(marker);\n var coordinates = [position.lng(), position.lat()];\n return {\n type: \"Feature\",\n geometry: {\n type: \"Point\",\n coordinates\n },\n properties: {\n marker\n }\n };\n });\n this.superCluster.load(points);\n }\n if (!changed) {\n if (this.state.zoom <= this.maxZoom || state.zoom <= this.maxZoom) {\n changed = !equal(this.state, state);\n }\n }\n this.state = state;\n if (changed) {\n this.clusters = this.cluster(input);\n }\n return {\n clusters: this.clusters,\n changed\n };\n }\n cluster(_ref10) {\n var {\n map\n } = _ref10;\n return this.superCluster.getClusters([-180, -90, 180, 90], Math.round(map.getZoom())).map(feature => this.transformCluster(feature));\n }\n transformCluster(_ref11) {\n var {\n geometry: {\n coordinates: [lng, lat]\n },\n properties\n } = _ref11;\n if (properties.cluster) {\n return new Cluster({\n markers: this.superCluster.getLeaves(properties.cluster_id, Infinity).map(leaf => leaf.properties.marker),\n position: {\n lat,\n lng\n }\n });\n }\n var marker = properties.marker;\n return new Cluster({\n markers: [marker],\n position: MarkerUtils.getPosition(marker)\n });\n }\n}\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A very fast JavaScript algorithm for geospatial point clustering using KD trees.\n *\n * @see https://www.npmjs.com/package/supercluster for more information on options.\n */\nclass SuperClusterViewportAlgorithm extends AbstractViewportAlgorithm {\n constructor(_a) {\n var {\n maxZoom,\n radius = 60,\n viewportPadding = 60\n } = _a,\n options = __rest(_a, [\"maxZoom\", \"radius\", \"viewportPadding\"]);\n super({\n maxZoom,\n viewportPadding\n });\n this.superCluster = new Supercluster(Object.assign({\n maxZoom: this.maxZoom,\n radius\n }, options));\n this.state = {\n zoom: -1,\n view: [0, 0, 0, 0]\n };\n }\n calculate(input) {\n var state = {\n zoom: Math.round(input.map.getZoom()),\n view: getPaddedViewport(input.map.getBounds(), input.mapCanvasProjection, this.viewportPadding)\n };\n var changed = !equal(this.state, state);\n if (!equal(input.markers, this.markers)) {\n changed = true;\n // TODO use proxy to avoid copy?\n this.markers = [...input.markers];\n var points = this.markers.map(marker => {\n var position = MarkerUtils.getPosition(marker);\n var coordinates = [position.lng(), position.lat()];\n return {\n type: \"Feature\",\n geometry: {\n type: \"Point\",\n coordinates\n },\n properties: {\n marker\n }\n };\n });\n this.superCluster.load(points);\n }\n if (changed) {\n this.clusters = this.cluster(input);\n this.state = state;\n }\n return {\n clusters: this.clusters,\n changed\n };\n }\n cluster(_ref12) {\n var {\n map,\n mapCanvasProjection\n } = _ref12;\n /* recalculate new state because we can't use the cached version. */\n var state = {\n zoom: Math.round(map.getZoom()),\n view: getPaddedViewport(map.getBounds(), mapCanvasProjection, this.viewportPadding)\n };\n return this.superCluster.getClusters(state.view, state.zoom).map(feature => this.transformCluster(feature));\n }\n transformCluster(_ref13) {\n var {\n geometry: {\n coordinates: [lng, lat]\n },\n properties\n } = _ref13;\n if (properties.cluster) {\n return new Cluster({\n markers: this.superCluster.getLeaves(properties.cluster_id, Infinity).map(leaf => leaf.properties.marker),\n position: {\n lat,\n lng\n }\n });\n }\n var marker = properties.marker;\n return new Cluster({\n markers: [marker],\n position: MarkerUtils.getPosition(marker)\n });\n }\n}\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides statistics on all clusters in the current render cycle for use in {@link Renderer.render}.\n */\nclass ClusterStats {\n constructor(markers, clusters) {\n this.markers = {\n sum: markers.length\n };\n var clusterMarkerCounts = clusters.map(a => a.count);\n var clusterMarkerSum = clusterMarkerCounts.reduce((a, b) => a + b, 0);\n this.clusters = {\n count: clusters.length,\n markers: {\n mean: clusterMarkerSum / clusters.length,\n sum: clusterMarkerSum,\n min: Math.min(...clusterMarkerCounts),\n max: Math.max(...clusterMarkerCounts)\n }\n };\n }\n}\nclass DefaultRenderer {\n /**\n * The default render function for the library used by {@link MarkerClusterer}.\n *\n * Currently set to use the following:\n *\n * ```typescript\n * // change color if this cluster has more markers than the mean cluster\n * const color =\n * count > Math.max(10, stats.clusters.markers.mean)\n * ? \"#ff0000\"\n * : \"#0000ff\";\n *\n * // create svg url with fill color\n * const svg = window.btoa(`\n * \n * \n * \n * \n * \n * `);\n *\n * // create marker using svg icon\n * return new google.maps.Marker({\n * position,\n * icon: {\n * url: `data:image/svg+xml;base64,${svg}`,\n * scaledSize: new google.maps.Size(45, 45),\n * },\n * label: {\n * text: String(count),\n * color: \"rgba(255,255,255,0.9)\",\n * fontSize: \"12px\",\n * },\n * // adjust zIndex to be above other markers\n * zIndex: 1000 + count,\n * });\n * ```\n */\n render(_ref14, stats, map) {\n var {\n count,\n position\n } = _ref14;\n // change color if this cluster has more markers than the mean cluster\n var color = count > Math.max(10, stats.clusters.markers.mean) ? \"#ff0000\" : \"#0000ff\";\n // create svg literal with fill color\n var svg = \"\\n\\n\\n\\n\").concat(count, \"\\n\");\n var title = \"Cluster of \".concat(count, \" markers\"),\n // adjust zIndex to be above other markers\n zIndex = Number(google.maps.Marker.MAX_ZINDEX) + count;\n if (MarkerUtils.isAdvancedMarkerAvailable(map)) {\n // create cluster SVG element\n var parser = new DOMParser();\n var svgEl = parser.parseFromString(svg, \"image/svg+xml\").documentElement;\n svgEl.setAttribute(\"transform\", \"translate(0 25)\");\n var _clusterOptions = {\n map,\n position,\n zIndex,\n title,\n content: svgEl\n };\n return new google.maps.marker.AdvancedMarkerElement(_clusterOptions);\n }\n var clusterOptions = {\n position,\n zIndex,\n title,\n icon: {\n url: \"data:image/svg+xml;base64,\".concat(btoa(svg)),\n anchor: new google.maps.Point(25, 25)\n }\n };\n return new google.maps.Marker(clusterOptions);\n }\n}\n\n/**\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Extends an object's prototype by another's.\n *\n * @param type1 The Type to be extended.\n * @param type2 The Type to extend with.\n * @ignore\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extend(type1, type2) {\n /* istanbul ignore next */\n // eslint-disable-next-line prefer-const\n for (var property in type2.prototype) {\n type1.prototype[property] = type2.prototype[property];\n }\n}\n/**\n * @ignore\n */\nclass OverlayViewSafe {\n constructor() {\n // MarkerClusterer implements google.maps.OverlayView interface. We use the\n // extend function to extend MarkerClusterer with google.maps.OverlayView\n // because it might not always be available when the code is defined so we\n // look for it at the last possible moment. If it doesn't exist now then\n // there is no point going ahead :)\n extend(OverlayViewSafe, google.maps.OverlayView);\n }\n}\n\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar MarkerClustererEvents;\n(function (MarkerClustererEvents) {\n MarkerClustererEvents[\"CLUSTERING_BEGIN\"] = \"clusteringbegin\";\n MarkerClustererEvents[\"CLUSTERING_END\"] = \"clusteringend\";\n MarkerClustererEvents[\"CLUSTER_CLICK\"] = \"click\";\n})(MarkerClustererEvents || (MarkerClustererEvents = {}));\nvar defaultOnClusterClickHandler = (_, cluster, map) => {\n map.fitBounds(cluster.bounds);\n};\n/**\n * MarkerClusterer creates and manages per-zoom-level clusters for large amounts\n * of markers. See {@link MarkerClustererOptions} for more details.\n *\n */\nclass MarkerClusterer extends OverlayViewSafe {\n constructor(_ref15) {\n var {\n map,\n markers = [],\n algorithmOptions = {},\n algorithm = new SuperClusterAlgorithm(algorithmOptions),\n renderer = new DefaultRenderer(),\n onClusterClick = defaultOnClusterClickHandler\n } = _ref15;\n super();\n this.markers = [...markers];\n this.clusters = [];\n this.algorithm = algorithm;\n this.renderer = renderer;\n this.onClusterClick = onClusterClick;\n if (map) {\n this.setMap(map);\n }\n }\n addMarker(marker, noDraw) {\n if (this.markers.includes(marker)) {\n return;\n }\n this.markers.push(marker);\n if (!noDraw) {\n this.render();\n }\n }\n addMarkers(markers, noDraw) {\n markers.forEach(marker => {\n this.addMarker(marker, true);\n });\n if (!noDraw) {\n this.render();\n }\n }\n removeMarker(marker, noDraw) {\n var index = this.markers.indexOf(marker);\n if (index === -1) {\n // Marker is not in our list of markers, so do nothing:\n return false;\n }\n MarkerUtils.setMap(marker, null);\n this.markers.splice(index, 1); // Remove the marker from the list of managed markers\n if (!noDraw) {\n this.render();\n }\n return true;\n }\n removeMarkers(markers, noDraw) {\n var removed = false;\n markers.forEach(marker => {\n removed = this.removeMarker(marker, true) || removed;\n });\n if (removed && !noDraw) {\n this.render();\n }\n return removed;\n }\n clearMarkers(noDraw) {\n this.markers.length = 0;\n if (!noDraw) {\n this.render();\n }\n }\n /**\n * Recalculates and draws all the marker clusters.\n */\n render() {\n var map = this.getMap();\n if (map instanceof google.maps.Map && map.getProjection()) {\n google.maps.event.trigger(this, MarkerClustererEvents.CLUSTERING_BEGIN, this);\n var {\n clusters,\n changed\n } = this.algorithm.calculate({\n markers: this.markers,\n map,\n mapCanvasProjection: this.getProjection()\n });\n // Allow algorithms to return flag on whether the clusters/markers have changed.\n if (changed || changed == undefined) {\n // Accumulate the markers of the clusters composed of a single marker.\n // Those clusters directly use the marker.\n // Clusters with more than one markers use a group marker generated by a renderer.\n var singleMarker = new Set();\n for (var cluster of clusters) {\n if (cluster.markers.length == 1) {\n singleMarker.add(cluster.markers[0]);\n }\n }\n var groupMarkers = [];\n // Iterate the clusters that are currently rendered.\n for (var _cluster2 of this.clusters) {\n if (_cluster2.marker == null) {\n continue;\n }\n if (_cluster2.markers.length == 1) {\n if (!singleMarker.has(_cluster2.marker)) {\n // The marker:\n // - was previously rendered because it is from a cluster with 1 marker,\n // - should no more be rendered as it is not in singleMarker.\n MarkerUtils.setMap(_cluster2.marker, null);\n }\n } else {\n // Delay the removal of old group markers to avoid flickering.\n groupMarkers.push(_cluster2.marker);\n }\n }\n this.clusters = clusters;\n this.renderClusters();\n // Delayed removal of the markers of the former groups.\n requestAnimationFrame(() => groupMarkers.forEach(marker => MarkerUtils.setMap(marker, null)));\n }\n google.maps.event.trigger(this, MarkerClustererEvents.CLUSTERING_END, this);\n }\n }\n onAdd() {\n this.idleListener = this.getMap().addListener(\"idle\", this.render.bind(this));\n this.render();\n }\n onRemove() {\n google.maps.event.removeListener(this.idleListener);\n this.reset();\n }\n reset() {\n this.markers.forEach(marker => MarkerUtils.setMap(marker, null));\n this.clusters.forEach(cluster => cluster.delete());\n this.clusters = [];\n }\n renderClusters() {\n // Generate stats to pass to renderers.\n var stats = new ClusterStats(this.markers, this.clusters);\n var map = this.getMap();\n this.clusters.forEach(cluster => {\n if (cluster.markers.length === 1) {\n cluster.marker = cluster.markers[0];\n } else {\n // Generate the marker to represent the group.\n cluster.marker = this.renderer.render(cluster, stats, map);\n // Make sure all individual markers are removed from the map.\n cluster.markers.forEach(marker => MarkerUtils.setMap(marker, null));\n if (this.onClusterClick) {\n cluster.marker.addListener(\"click\", /* istanbul ignore next */\n event => {\n google.maps.event.trigger(this, MarkerClustererEvents.CLUSTER_CLICK, cluster);\n this.onClusterClick(event, cluster, map);\n });\n }\n }\n MarkerUtils.setMap(cluster.marker, map);\n });\n }\n}\n\nvar index_esm = /*#__PURE__*/Object.freeze({\n __proto__: null,\n AbstractAlgorithm: AbstractAlgorithm,\n AbstractViewportAlgorithm: AbstractViewportAlgorithm,\n Cluster: Cluster,\n ClusterStats: ClusterStats,\n DefaultRenderer: DefaultRenderer,\n GridAlgorithm: GridAlgorithm,\n MarkerClusterer: MarkerClusterer,\n get MarkerClustererEvents () { return MarkerClustererEvents; },\n MarkerUtils: MarkerUtils,\n NoopAlgorithm: NoopAlgorithm,\n SuperClusterAlgorithm: SuperClusterAlgorithm,\n SuperClusterViewportAlgorithm: SuperClusterViewportAlgorithm,\n defaultOnClusterClickHandler: defaultOnClusterClickHandler,\n distanceBetweenPoints: distanceBetweenPoints,\n extendBoundsToPaddedViewport: extendBoundsToPaddedViewport,\n extendPixelBounds: extendPixelBounds,\n filterMarkersToPaddedViewport: filterMarkersToPaddedViewport,\n getPaddedViewport: getPaddedViewport,\n noop: noop$1,\n pixelBoundsToLatLngBounds: pixelBoundsToLatLngBounds\n});\n\nfunction ownKeys$a(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$a(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$a(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$a(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction useGoogleMarkerClusterer(options) {\n var map = useGoogleMap();\n var [markerClusterer, setMarkerClusterer] = useState(null);\n useEffect(() => {\n if (map && markerClusterer === null) {\n var markerCluster = new MarkerClusterer(_objectSpread$a(_objectSpread$a({}, options), {}, {\n map\n }));\n setMarkerClusterer(markerCluster);\n }\n }, [map]);\n return markerClusterer;\n}\n/** Wrapper around [@googlemaps/markerclusterer](https://github.com/googlemaps/js-markerclusterer)\n *\n * Accepts {@link MarkerClustererOptionsSubset} which is a subset of {@link MarkerClustererOptions}\n */\nfunction GoogleMarkerClusterer(_ref) {\n var {\n children,\n options\n } = _ref;\n var markerClusterer = useGoogleMarkerClusterer(options);\n return markerClusterer !== null ? children(markerClusterer) : null;\n}\nvar GoogleMarkerClusterer$1 = memo(GoogleMarkerClusterer);\n\nvar eventMap$c = {\n onCloseClick: 'closeclick',\n onContentChanged: 'content_changed',\n onDomReady: 'domready',\n onPositionChanged: 'position_changed',\n onZindexChanged: 'zindex_changed'\n};\nvar updaterMap$c = {\n options(instance, options) {\n instance.setOptions(options);\n },\n position(instance, position) {\n instance.setPosition(position);\n },\n zIndex(instance, zIndex) {\n instance.setZIndex(zIndex);\n }\n};\nfunction InfoWindowFunctional(_ref) {\n var {\n children,\n anchor,\n options,\n position,\n zIndex,\n onCloseClick,\n onDomReady,\n onContentChanged,\n onPositionChanged,\n onZindexChanged,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [closeclickListener, setCloseClickListener] = useState(null);\n var [domreadyclickListener, setDomReadyClickListener] = useState(null);\n var [contentchangedclickListener, setContentChangedClickListener] = useState(null);\n var [positionchangedclickListener, setPositionChangedClickListener] = useState(null);\n var [zindexchangedclickListener, setZindexChangedClickListener] = useState(null);\n var containerElementRef = useRef(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.close();\n if (anchor) {\n instance.open(map, anchor);\n } else if (instance.getPosition()) {\n instance.open(map);\n }\n }\n }, [map, instance, anchor]);\n useEffect(() => {\n if (options && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n if (position && instance !== null) {\n instance.setPosition(position);\n }\n }, [position]);\n useEffect(() => {\n if (typeof zIndex === 'number' && instance !== null) {\n instance.setZIndex(zIndex);\n }\n }, [zIndex]);\n useEffect(() => {\n if (instance && onCloseClick) {\n if (closeclickListener !== null) {\n google.maps.event.removeListener(closeclickListener);\n }\n setCloseClickListener(google.maps.event.addListener(instance, 'closeclick', onCloseClick));\n }\n }, [onCloseClick]);\n useEffect(() => {\n if (instance && onDomReady) {\n if (domreadyclickListener !== null) {\n google.maps.event.removeListener(domreadyclickListener);\n }\n setDomReadyClickListener(google.maps.event.addListener(instance, 'domready', onDomReady));\n }\n }, [onDomReady]);\n useEffect(() => {\n if (instance && onContentChanged) {\n if (contentchangedclickListener !== null) {\n google.maps.event.removeListener(contentchangedclickListener);\n }\n setContentChangedClickListener(google.maps.event.addListener(instance, 'content_changed', onContentChanged));\n }\n }, [onContentChanged]);\n useEffect(() => {\n if (instance && onPositionChanged) {\n if (positionchangedclickListener !== null) {\n google.maps.event.removeListener(positionchangedclickListener);\n }\n setPositionChangedClickListener(google.maps.event.addListener(instance, 'position_changed', onPositionChanged));\n }\n }, [onPositionChanged]);\n useEffect(() => {\n if (instance && onZindexChanged) {\n if (zindexchangedclickListener !== null) {\n google.maps.event.removeListener(zindexchangedclickListener);\n }\n setZindexChangedClickListener(google.maps.event.addListener(instance, 'zindex_changed', onZindexChanged));\n }\n }, [onZindexChanged]);\n useEffect(() => {\n var infoWindow = new google.maps.InfoWindow(options);\n setInstance(infoWindow);\n containerElementRef.current = document.createElement('div');\n if (onCloseClick) {\n setCloseClickListener(google.maps.event.addListener(infoWindow, 'closeclick', onCloseClick));\n }\n if (onDomReady) {\n setDomReadyClickListener(google.maps.event.addListener(infoWindow, 'domready', onDomReady));\n }\n if (onContentChanged) {\n setContentChangedClickListener(google.maps.event.addListener(infoWindow, 'content_changed', onContentChanged));\n }\n if (onPositionChanged) {\n setPositionChangedClickListener(google.maps.event.addListener(infoWindow, 'position_changed', onPositionChanged));\n }\n if (onZindexChanged) {\n setZindexChangedClickListener(google.maps.event.addListener(infoWindow, 'zindex_changed', onZindexChanged));\n }\n infoWindow.setContent(containerElementRef.current);\n if (position) {\n infoWindow.setPosition(position);\n }\n if (zIndex) {\n infoWindow.setZIndex(zIndex);\n }\n if (anchor) {\n infoWindow.open(map, anchor);\n } else if (infoWindow.getPosition()) {\n infoWindow.open(map);\n } else {\n invariant(false, \"You must provide either an anchor (typically render it inside a ) or a position props for .\");\n }\n if (onLoad) {\n onLoad(infoWindow);\n }\n return () => {\n if (closeclickListener) {\n google.maps.event.removeListener(closeclickListener);\n }\n if (contentchangedclickListener) {\n google.maps.event.removeListener(contentchangedclickListener);\n }\n if (domreadyclickListener) {\n google.maps.event.removeListener(domreadyclickListener);\n }\n if (positionchangedclickListener) {\n google.maps.event.removeListener(positionchangedclickListener);\n }\n if (zindexchangedclickListener) {\n google.maps.event.removeListener(zindexchangedclickListener);\n }\n if (onUnmount) {\n onUnmount(infoWindow);\n }\n infoWindow.close();\n };\n }, []);\n return containerElementRef.current ? createPortal(Children.only(children), containerElementRef.current) : null;\n}\nvar InfoWindowF = memo(InfoWindowFunctional);\nclass InfoWindow extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"containerElement\", null);\n _defineProperty(this, \"state\", {\n infoWindow: null\n });\n _defineProperty(this, \"open\", (infoWindow, anchor) => {\n if (anchor) {\n infoWindow.open(this.context, anchor);\n } else if (infoWindow.getPosition()) {\n infoWindow.open(this.context);\n } else {\n invariant(false, \"You must provide either an anchor (typically render it inside a ) or a position props for .\");\n }\n });\n _defineProperty(this, \"setInfoWindowCallback\", () => {\n if (this.state.infoWindow !== null && this.containerElement !== null) {\n this.state.infoWindow.setContent(this.containerElement);\n this.open(this.state.infoWindow, this.props.anchor);\n if (this.props.onLoad) {\n this.props.onLoad(this.state.infoWindow);\n }\n }\n });\n }\n componentDidMount() {\n var infoWindow = new google.maps.InfoWindow(this.props.options);\n this.containerElement = document.createElement('div');\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$c,\n eventMap: eventMap$c,\n prevProps: {},\n nextProps: this.props,\n instance: infoWindow\n });\n this.setState(() => {\n return {\n infoWindow\n };\n }, this.setInfoWindowCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.infoWindow !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$c,\n eventMap: eventMap$c,\n prevProps,\n nextProps: this.props,\n instance: this.state.infoWindow\n });\n }\n }\n componentWillUnmount() {\n if (this.state.infoWindow !== null) {\n unregisterEvents(this.registeredEvents);\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.infoWindow);\n }\n this.state.infoWindow.close();\n }\n }\n render() {\n return this.containerElement ? createPortal(Children.only(this.props.children), this.containerElement) : null;\n }\n}\n_defineProperty(InfoWindow, \"contextType\", MapContext);\n\nfunction ownKeys$9(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$9(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$9(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$9(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$b = {\n onClick: 'click',\n onDblClick: 'dblclick',\n onDrag: 'drag',\n onDragEnd: 'dragend',\n onDragStart: 'dragstart',\n onMouseDown: 'mousedown',\n onMouseMove: 'mousemove',\n onMouseOut: 'mouseout',\n onMouseOver: 'mouseover',\n onMouseUp: 'mouseup',\n onRightClick: 'rightclick'\n};\nvar updaterMap$b = {\n draggable(instance, draggable) {\n instance.setDraggable(draggable);\n },\n editable(instance, editable) {\n instance.setEditable(editable);\n },\n map(instance, map) {\n instance.setMap(map);\n },\n options(instance, options) {\n instance.setOptions(options);\n },\n path(instance, path) {\n instance.setPath(path);\n },\n visible(instance, visible) {\n instance.setVisible(visible);\n }\n};\nvar defaultOptions$1 = {};\nfunction PolylineFunctional(_ref) {\n var {\n options,\n draggable,\n editable,\n visible,\n path,\n onDblClick,\n onDragEnd,\n onDragStart,\n onMouseDown,\n onMouseMove,\n onMouseOut,\n onMouseOver,\n onMouseUp,\n onRightClick,\n onClick,\n onDrag,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [dblclickListener, setDblclickListener] = useState(null);\n var [dragendListener, setDragendListener] = useState(null);\n var [dragstartListener, setDragstartListener] = useState(null);\n var [mousedownListener, setMousedownListener] = useState(null);\n var [mousemoveListener, setMousemoveListener] = useState(null);\n var [mouseoutListener, setMouseoutListener] = useState(null);\n var [mouseoverListener, setMouseoverListener] = useState(null);\n var [mouseupListener, setMouseupListener] = useState(null);\n var [rightclickListener, setRightclickListener] = useState(null);\n var [clickListener, setClickListener] = useState(null);\n var [dragListener, setDragListener] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (typeof options !== 'undefined' && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n if (typeof draggable !== 'undefined' && instance !== null) {\n instance.setDraggable(draggable);\n }\n }, [instance, draggable]);\n useEffect(() => {\n if (typeof editable !== 'undefined' && instance !== null) {\n instance.setEditable(editable);\n }\n }, [instance, editable]);\n useEffect(() => {\n if (typeof visible !== 'undefined' && instance !== null) {\n instance.setVisible(visible);\n }\n }, [instance, visible]);\n useEffect(() => {\n if (typeof path !== 'undefined' && instance !== null) {\n instance.setPath(path);\n }\n }, [instance, path]);\n useEffect(() => {\n if (instance && onDblClick) {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n setDblclickListener(google.maps.event.addListener(instance, 'dblclick', onDblClick));\n }\n }, [onDblClick]);\n useEffect(() => {\n if (instance && onDragEnd) {\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n setDragendListener(google.maps.event.addListener(instance, 'dragend', onDragEnd));\n }\n }, [onDragEnd]);\n useEffect(() => {\n if (instance && onDragStart) {\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n setDragstartListener(google.maps.event.addListener(instance, 'dragstart', onDragStart));\n }\n }, [onDragStart]);\n useEffect(() => {\n if (instance && onMouseDown) {\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n setMousedownListener(google.maps.event.addListener(instance, 'mousedown', onMouseDown));\n }\n }, [onMouseDown]);\n useEffect(() => {\n if (instance && onMouseMove) {\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n setMousemoveListener(google.maps.event.addListener(instance, 'mousemove', onMouseMove));\n }\n }, [onMouseMove]);\n useEffect(() => {\n if (instance && onMouseOut) {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n setMouseoutListener(google.maps.event.addListener(instance, 'mouseout', onMouseOut));\n }\n }, [onMouseOut]);\n useEffect(() => {\n if (instance && onMouseOver) {\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n setMouseoverListener(google.maps.event.addListener(instance, 'mouseover', onMouseOver));\n }\n }, [onMouseOver]);\n useEffect(() => {\n if (instance && onMouseUp) {\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n setMouseupListener(google.maps.event.addListener(instance, 'mouseup', onMouseUp));\n }\n }, [onMouseUp]);\n useEffect(() => {\n if (instance && onRightClick) {\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n setRightclickListener(google.maps.event.addListener(instance, 'rightclick', onRightClick));\n }\n }, [onRightClick]);\n useEffect(() => {\n if (instance && onClick) {\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n setClickListener(google.maps.event.addListener(instance, 'click', onClick));\n }\n }, [onClick]);\n useEffect(() => {\n if (instance && onDrag) {\n if (dragListener !== null) {\n google.maps.event.removeListener(dragListener);\n }\n setDragListener(google.maps.event.addListener(instance, 'drag', onDrag));\n }\n }, [onDrag]);\n useEffect(() => {\n var polyline = new google.maps.Polyline(_objectSpread$9(_objectSpread$9({}, options || defaultOptions$1), {}, {\n map\n }));\n if (path) {\n polyline.setPath(path);\n }\n if (typeof visible !== 'undefined') {\n polyline.setVisible(visible);\n }\n if (typeof editable !== 'undefined') {\n polyline.setEditable(editable);\n }\n if (typeof draggable !== 'undefined') {\n polyline.setDraggable(draggable);\n }\n if (onDblClick) {\n setDblclickListener(google.maps.event.addListener(polyline, 'dblclick', onDblClick));\n }\n if (onDragEnd) {\n setDragendListener(google.maps.event.addListener(polyline, 'dragend', onDragEnd));\n }\n if (onDragStart) {\n setDragstartListener(google.maps.event.addListener(polyline, 'dragstart', onDragStart));\n }\n if (onMouseDown) {\n setMousedownListener(google.maps.event.addListener(polyline, 'mousedown', onMouseDown));\n }\n if (onMouseMove) {\n setMousemoveListener(google.maps.event.addListener(polyline, 'mousemove', onMouseMove));\n }\n if (onMouseOut) {\n setMouseoutListener(google.maps.event.addListener(polyline, 'mouseout', onMouseOut));\n }\n if (onMouseOver) {\n setMouseoverListener(google.maps.event.addListener(polyline, 'mouseover', onMouseOver));\n }\n if (onMouseUp) {\n setMouseupListener(google.maps.event.addListener(polyline, 'mouseup', onMouseUp));\n }\n if (onRightClick) {\n setRightclickListener(google.maps.event.addListener(polyline, 'rightclick', onRightClick));\n }\n if (onClick) {\n setClickListener(google.maps.event.addListener(polyline, 'click', onClick));\n }\n if (onDrag) {\n setDragListener(google.maps.event.addListener(polyline, 'drag', onDrag));\n }\n setInstance(polyline);\n if (onLoad) {\n onLoad(polyline);\n }\n return () => {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n if (onUnmount) {\n onUnmount(polyline);\n }\n polyline.setMap(null);\n };\n }, []);\n return null;\n}\nvar PolylineF = memo(PolylineFunctional);\nclass Polyline extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n polyline: null\n });\n _defineProperty(this, \"setPolylineCallback\", () => {\n if (this.state.polyline !== null && this.props.onLoad) {\n this.props.onLoad(this.state.polyline);\n }\n });\n }\n componentDidMount() {\n var polyline = new google.maps.Polyline(_objectSpread$9(_objectSpread$9({}, this.props.options), {}, {\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$b,\n eventMap: eventMap$b,\n prevProps: {},\n nextProps: this.props,\n instance: polyline\n });\n this.setState(function setPolyline() {\n return {\n polyline\n };\n }, this.setPolylineCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.polyline !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$b,\n eventMap: eventMap$b,\n prevProps,\n nextProps: this.props,\n instance: this.state.polyline\n });\n }\n }\n componentWillUnmount() {\n if (this.state.polyline === null) {\n return;\n }\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.polyline);\n }\n unregisterEvents(this.registeredEvents);\n this.state.polyline.setMap(null);\n }\n render() {\n return null;\n }\n}\n_defineProperty(Polyline, \"contextType\", MapContext);\n\nfunction ownKeys$8(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$8(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$8(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$8(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$a = {\n onClick: 'click',\n onDblClick: 'dblclick',\n onDrag: 'drag',\n onDragEnd: 'dragend',\n onDragStart: 'dragstart',\n onMouseDown: 'mousedown',\n onMouseMove: 'mousemove',\n onMouseOut: 'mouseout',\n onMouseOver: 'mouseover',\n onMouseUp: 'mouseup',\n onRightClick: 'rightclick'\n};\nvar updaterMap$a = {\n draggable(instance, draggable) {\n instance.setDraggable(draggable);\n },\n editable(instance, editable) {\n instance.setEditable(editable);\n },\n map(instance, map) {\n instance.setMap(map);\n },\n options(instance, options) {\n instance.setOptions(options);\n },\n path(instance, path) {\n instance.setPath(path);\n },\n paths(instance, paths) {\n instance.setPaths(paths);\n },\n visible(instance, visible) {\n instance.setVisible(visible);\n }\n};\nfunction PolygonFunctional(_ref) {\n var {\n options,\n draggable,\n editable,\n visible,\n path,\n paths,\n onDblClick,\n onDragEnd,\n onDragStart,\n onMouseDown,\n onMouseMove,\n onMouseOut,\n onMouseOver,\n onMouseUp,\n onRightClick,\n onClick,\n onDrag,\n onLoad,\n onUnmount,\n onEdit\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [dblclickListener, setDblclickListener] = useState(null);\n var [dragendListener, setDragendListener] = useState(null);\n var [dragstartListener, setDragstartListener] = useState(null);\n var [mousedownListener, setMousedownListener] = useState(null);\n var [mousemoveListener, setMousemoveListener] = useState(null);\n var [mouseoutListener, setMouseoutListener] = useState(null);\n var [mouseoverListener, setMouseoverListener] = useState(null);\n var [mouseupListener, setMouseupListener] = useState(null);\n var [rightclickListener, setRightclickListener] = useState(null);\n var [clickListener, setClickListener] = useState(null);\n var [dragListener, setDragListener] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (typeof options !== 'undefined' && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n if (typeof draggable !== 'undefined' && instance !== null) {\n instance.setDraggable(draggable);\n }\n }, [instance, draggable]);\n useEffect(() => {\n if (typeof editable !== 'undefined' && instance !== null) {\n instance.setEditable(editable);\n }\n }, [instance, editable]);\n useEffect(() => {\n if (typeof visible !== 'undefined' && instance !== null) {\n instance.setVisible(visible);\n }\n }, [instance, visible]);\n useEffect(() => {\n if (typeof path !== 'undefined' && instance !== null) {\n instance.setPath(path);\n }\n }, [instance, path]);\n useEffect(() => {\n if (typeof paths !== 'undefined' && instance !== null) {\n instance.setPaths(paths);\n }\n }, [instance, paths]);\n useEffect(() => {\n if (instance && typeof onDblClick === 'function') {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n setDblclickListener(google.maps.event.addListener(instance, 'dblclick', onDblClick));\n }\n }, [onDblClick]);\n useEffect(() => {\n if (!instance) {\n return;\n }\n google.maps.event.addListener(instance.getPath(), 'insert_at', () => {\n onEdit === null || onEdit === void 0 || onEdit(instance);\n });\n google.maps.event.addListener(instance.getPath(), 'set_at', () => {\n onEdit === null || onEdit === void 0 || onEdit(instance);\n });\n google.maps.event.addListener(instance.getPath(), 'remove_at', () => {\n onEdit === null || onEdit === void 0 || onEdit(instance);\n });\n }, [instance, onEdit]);\n useEffect(() => {\n if (instance && typeof onDragEnd === 'function') {\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n setDragendListener(google.maps.event.addListener(instance, 'dragend', onDragEnd));\n }\n }, [onDragEnd]);\n useEffect(() => {\n if (instance && typeof onDragStart === 'function') {\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n setDragstartListener(google.maps.event.addListener(instance, 'dragstart', onDragStart));\n }\n }, [onDragStart]);\n useEffect(() => {\n if (instance && typeof onMouseDown === 'function') {\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n setMousedownListener(google.maps.event.addListener(instance, 'mousedown', onMouseDown));\n }\n }, [onMouseDown]);\n useEffect(() => {\n if (instance && typeof onMouseMove === 'function') {\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n setMousemoveListener(google.maps.event.addListener(instance, 'mousemove', onMouseMove));\n }\n }, [onMouseMove]);\n useEffect(() => {\n if (instance && typeof onMouseOut === 'function') {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n setMouseoutListener(google.maps.event.addListener(instance, 'mouseout', onMouseOut));\n }\n }, [onMouseOut]);\n useEffect(() => {\n if (instance && typeof onMouseOver === 'function') {\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n setMouseoverListener(google.maps.event.addListener(instance, 'mouseover', onMouseOver));\n }\n }, [onMouseOver]);\n useEffect(() => {\n if (instance && typeof onMouseUp === 'function') {\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n setMouseupListener(google.maps.event.addListener(instance, 'mouseup', onMouseUp));\n }\n }, [onMouseUp]);\n useEffect(() => {\n if (instance && typeof onRightClick === 'function') {\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n setRightclickListener(google.maps.event.addListener(instance, 'rightclick', onRightClick));\n }\n }, [onRightClick]);\n useEffect(() => {\n if (instance && typeof onClick === 'function') {\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n setClickListener(google.maps.event.addListener(instance, 'click', onClick));\n }\n }, [onClick]);\n useEffect(() => {\n if (instance && typeof onDrag === 'function') {\n if (dragListener !== null) {\n google.maps.event.removeListener(dragListener);\n }\n setDragListener(google.maps.event.addListener(instance, 'drag', onDrag));\n }\n }, [onDrag]);\n useEffect(() => {\n var polygon = new google.maps.Polygon(_objectSpread$8(_objectSpread$8({}, options), {}, {\n map\n }));\n if (path) {\n polygon.setPath(path);\n }\n if (paths) {\n polygon.setPaths(paths);\n }\n if (typeof visible !== 'undefined') {\n polygon.setVisible(visible);\n }\n if (typeof editable !== 'undefined') {\n polygon.setEditable(editable);\n }\n if (typeof draggable !== 'undefined') {\n polygon.setDraggable(draggable);\n }\n if (onDblClick) {\n setDblclickListener(google.maps.event.addListener(polygon, 'dblclick', onDblClick));\n }\n if (onDragEnd) {\n setDragendListener(google.maps.event.addListener(polygon, 'dragend', onDragEnd));\n }\n if (onDragStart) {\n setDragstartListener(google.maps.event.addListener(polygon, 'dragstart', onDragStart));\n }\n if (onMouseDown) {\n setMousedownListener(google.maps.event.addListener(polygon, 'mousedown', onMouseDown));\n }\n if (onMouseMove) {\n setMousemoveListener(google.maps.event.addListener(polygon, 'mousemove', onMouseMove));\n }\n if (onMouseOut) {\n setMouseoutListener(google.maps.event.addListener(polygon, 'mouseout', onMouseOut));\n }\n if (onMouseOver) {\n setMouseoverListener(google.maps.event.addListener(polygon, 'mouseover', onMouseOver));\n }\n if (onMouseUp) {\n setMouseupListener(google.maps.event.addListener(polygon, 'mouseup', onMouseUp));\n }\n if (onRightClick) {\n setRightclickListener(google.maps.event.addListener(polygon, 'rightclick', onRightClick));\n }\n if (onClick) {\n setClickListener(google.maps.event.addListener(polygon, 'click', onClick));\n }\n if (onDrag) {\n setDragListener(google.maps.event.addListener(polygon, 'drag', onDrag));\n }\n setInstance(polygon);\n if (onLoad) {\n onLoad(polygon);\n }\n return () => {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n if (onUnmount) {\n onUnmount(polygon);\n }\n polygon.setMap(null);\n };\n }, []);\n return null;\n}\nvar PolygonF = memo(PolygonFunctional);\nclass Polygon extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n }\n componentDidMount() {\n var polygonOptions = this.props.options || {};\n this.polygon = new google.maps.Polygon(polygonOptions);\n this.polygon.setMap(this.context);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$a,\n eventMap: eventMap$a,\n prevProps: {},\n nextProps: this.props,\n instance: this.polygon\n });\n if (this.props.onLoad) {\n this.props.onLoad(this.polygon);\n }\n }\n componentDidUpdate(prevProps) {\n if (this.polygon) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$a,\n eventMap: eventMap$a,\n prevProps,\n nextProps: this.props,\n instance: this.polygon\n });\n }\n }\n componentWillUnmount() {\n if (this.polygon) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.polygon);\n }\n unregisterEvents(this.registeredEvents);\n if (this.polygon) {\n this.polygon.setMap(null);\n }\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(Polygon, \"contextType\", MapContext);\n\nfunction ownKeys$7(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$7(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$7(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$9 = {\n onBoundsChanged: 'bounds_changed',\n onClick: 'click',\n onDblClick: 'dblclick',\n onDrag: 'drag',\n onDragEnd: 'dragend',\n onDragStart: 'dragstart',\n onMouseDown: 'mousedown',\n onMouseMove: 'mousemove',\n onMouseOut: 'mouseout',\n onMouseOver: 'mouseover',\n onMouseUp: 'mouseup',\n onRightClick: 'rightclick'\n};\nvar updaterMap$9 = {\n bounds(instance, bounds) {\n instance.setBounds(bounds);\n },\n draggable(instance, draggable) {\n instance.setDraggable(draggable);\n },\n editable(instance, editable) {\n instance.setEditable(editable);\n },\n map(instance, map) {\n instance.setMap(map);\n },\n options(instance, options) {\n instance.setOptions(options);\n },\n visible(instance, visible) {\n instance.setVisible(visible);\n }\n};\nfunction RectangleFunctional(_ref) {\n var {\n options,\n bounds,\n draggable,\n editable,\n visible,\n onDblClick,\n onDragEnd,\n onDragStart,\n onMouseDown,\n onMouseMove,\n onMouseOut,\n onMouseOver,\n onMouseUp,\n onRightClick,\n onClick,\n onDrag,\n onBoundsChanged,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [dblclickListener, setDblclickListener] = useState(null);\n var [dragendListener, setDragendListener] = useState(null);\n var [dragstartListener, setDragstartListener] = useState(null);\n var [mousedownListener, setMousedownListener] = useState(null);\n var [mousemoveListener, setMousemoveListener] = useState(null);\n var [mouseoutListener, setMouseoutListener] = useState(null);\n var [mouseoverListener, setMouseoverListener] = useState(null);\n var [mouseupListener, setMouseupListener] = useState(null);\n var [rightClickListener, setRightClickListener] = useState(null);\n var [clickListener, setClickListener] = useState(null);\n var [dragListener, setDragListener] = useState(null);\n var [boundsChangedListener, setBoundsChangedListener] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (typeof options !== 'undefined' && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n if (typeof draggable !== 'undefined' && instance !== null) {\n instance.setDraggable(draggable);\n }\n }, [instance, draggable]);\n useEffect(() => {\n if (typeof editable !== 'undefined' && instance !== null) {\n instance.setEditable(editable);\n }\n }, [instance, editable]);\n useEffect(() => {\n if (typeof visible !== 'undefined' && instance !== null) {\n instance.setVisible(visible);\n }\n }, [instance, visible]);\n useEffect(() => {\n if (typeof bounds !== 'undefined' && instance !== null) {\n instance.setBounds(bounds);\n }\n }, [instance, bounds]);\n useEffect(() => {\n if (instance && onDblClick) {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n setDblclickListener(google.maps.event.addListener(instance, 'dblclick', onDblClick));\n }\n }, [onDblClick]);\n useEffect(() => {\n if (instance && onDragEnd) {\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n setDragendListener(google.maps.event.addListener(instance, 'dragend', onDragEnd));\n }\n }, [onDragEnd]);\n useEffect(() => {\n if (instance && onDragStart) {\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n setDragstartListener(google.maps.event.addListener(instance, 'dragstart', onDragStart));\n }\n }, [onDragStart]);\n useEffect(() => {\n if (instance && onMouseDown) {\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n setMousedownListener(google.maps.event.addListener(instance, 'mousedown', onMouseDown));\n }\n }, [onMouseDown]);\n useEffect(() => {\n if (instance && onMouseMove) {\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n setMousemoveListener(google.maps.event.addListener(instance, 'mousemove', onMouseMove));\n }\n }, [onMouseMove]);\n useEffect(() => {\n if (instance && onMouseOut) {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n setMouseoutListener(google.maps.event.addListener(instance, 'mouseout', onMouseOut));\n }\n }, [onMouseOut]);\n useEffect(() => {\n if (instance && onMouseOver) {\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n setMouseoverListener(google.maps.event.addListener(instance, 'mouseover', onMouseOver));\n }\n }, [onMouseOver]);\n useEffect(() => {\n if (instance && onMouseUp) {\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n setMouseupListener(google.maps.event.addListener(instance, 'mouseup', onMouseUp));\n }\n }, [onMouseUp]);\n useEffect(() => {\n if (instance && onRightClick) {\n if (rightClickListener !== null) {\n google.maps.event.removeListener(rightClickListener);\n }\n setRightClickListener(google.maps.event.addListener(instance, 'rightclick', onRightClick));\n }\n }, [onRightClick]);\n useEffect(() => {\n if (instance && onClick) {\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n setClickListener(google.maps.event.addListener(instance, 'click', onClick));\n }\n }, [onClick]);\n useEffect(() => {\n if (instance && onDrag) {\n if (dragListener !== null) {\n google.maps.event.removeListener(dragListener);\n }\n setDragListener(google.maps.event.addListener(instance, 'drag', onDrag));\n }\n }, [onDrag]);\n useEffect(() => {\n if (instance && onBoundsChanged) {\n if (boundsChangedListener !== null) {\n google.maps.event.removeListener(boundsChangedListener);\n }\n setBoundsChangedListener(google.maps.event.addListener(instance, 'bounds_changed', onBoundsChanged));\n }\n }, [onBoundsChanged]);\n useEffect(() => {\n var rectangle = new google.maps.Rectangle(_objectSpread$7(_objectSpread$7({}, options), {}, {\n map\n }));\n if (typeof visible !== 'undefined') {\n rectangle.setVisible(visible);\n }\n if (typeof editable !== 'undefined') {\n rectangle.setEditable(editable);\n }\n if (typeof draggable !== 'undefined') {\n rectangle.setDraggable(draggable);\n }\n if (typeof bounds !== 'undefined') {\n rectangle.setBounds(bounds);\n }\n if (onDblClick) {\n setDblclickListener(google.maps.event.addListener(rectangle, 'dblclick', onDblClick));\n }\n if (onDragEnd) {\n setDragendListener(google.maps.event.addListener(rectangle, 'dragend', onDragEnd));\n }\n if (onDragStart) {\n setDragstartListener(google.maps.event.addListener(rectangle, 'dragstart', onDragStart));\n }\n if (onMouseDown) {\n setMousedownListener(google.maps.event.addListener(rectangle, 'mousedown', onMouseDown));\n }\n if (onMouseMove) {\n setMousemoveListener(google.maps.event.addListener(rectangle, 'mousemove', onMouseMove));\n }\n if (onMouseOut) {\n setMouseoutListener(google.maps.event.addListener(rectangle, 'mouseout', onMouseOut));\n }\n if (onMouseOver) {\n setMouseoverListener(google.maps.event.addListener(rectangle, 'mouseover', onMouseOver));\n }\n if (onMouseUp) {\n setMouseupListener(google.maps.event.addListener(rectangle, 'mouseup', onMouseUp));\n }\n if (onRightClick) {\n setRightClickListener(google.maps.event.addListener(rectangle, 'rightclick', onRightClick));\n }\n if (onClick) {\n setClickListener(google.maps.event.addListener(rectangle, 'click', onClick));\n }\n if (onDrag) {\n setDragListener(google.maps.event.addListener(rectangle, 'drag', onDrag));\n }\n if (onBoundsChanged) {\n setBoundsChangedListener(google.maps.event.addListener(rectangle, 'bounds_changed', onBoundsChanged));\n }\n setInstance(rectangle);\n if (onLoad) {\n onLoad(rectangle);\n }\n return () => {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n if (rightClickListener !== null) {\n google.maps.event.removeListener(rightClickListener);\n }\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n if (dragListener !== null) {\n google.maps.event.removeListener(dragListener);\n }\n if (boundsChangedListener !== null) {\n google.maps.event.removeListener(boundsChangedListener);\n }\n if (onUnmount) {\n onUnmount(rectangle);\n }\n rectangle.setMap(null);\n };\n }, []);\n return null;\n}\nvar RectangleF = memo(RectangleFunctional);\nclass Rectangle extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n rectangle: null\n });\n _defineProperty(this, \"setRectangleCallback\", () => {\n if (this.state.rectangle !== null && this.props.onLoad) {\n this.props.onLoad(this.state.rectangle);\n }\n });\n }\n componentDidMount() {\n var rectangle = new google.maps.Rectangle(_objectSpread$7(_objectSpread$7({}, this.props.options), {}, {\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$9,\n eventMap: eventMap$9,\n prevProps: {},\n nextProps: this.props,\n instance: rectangle\n });\n this.setState(function setRectangle() {\n return {\n rectangle\n };\n }, this.setRectangleCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.rectangle !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$9,\n eventMap: eventMap$9,\n prevProps,\n nextProps: this.props,\n instance: this.state.rectangle\n });\n }\n }\n componentWillUnmount() {\n if (this.state.rectangle !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.rectangle);\n }\n unregisterEvents(this.registeredEvents);\n this.state.rectangle.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(Rectangle, \"contextType\", MapContext);\n\nfunction ownKeys$6(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$6(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$6(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$8 = {\n onCenterChanged: 'center_changed',\n onRadiusChanged: 'radius_changed',\n onClick: 'click',\n onDblClick: 'dblclick',\n onDrag: 'drag',\n onDragEnd: 'dragend',\n onDragStart: 'dragstart',\n onMouseDown: 'mousedown',\n onMouseMove: 'mousemove',\n onMouseOut: 'mouseout',\n onMouseOver: 'mouseover',\n onMouseUp: 'mouseup',\n onRightClick: 'rightclick'\n};\nvar updaterMap$8 = {\n center(instance, center) {\n instance.setCenter(center);\n },\n draggable(instance, draggable) {\n instance.setDraggable(draggable);\n },\n editable(instance, editable) {\n instance.setEditable(editable);\n },\n map(instance, map) {\n instance.setMap(map);\n },\n options(instance, options) {\n instance.setOptions(options);\n },\n radius(instance, radius) {\n instance.setRadius(radius);\n },\n visible(instance, visible) {\n instance.setVisible(visible);\n }\n};\nvar defaultOptions = {};\nfunction CircleFunctional(_ref) {\n var {\n options,\n center,\n radius,\n draggable,\n editable,\n visible,\n onDblClick,\n onDragEnd,\n onDragStart,\n onMouseDown,\n onMouseMove,\n onMouseOut,\n onMouseOver,\n onMouseUp,\n onRightClick,\n onClick,\n onDrag,\n onCenterChanged,\n onRadiusChanged,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [dblclickListener, setDblclickListener] = useState(null);\n var [dragendListener, setDragendListener] = useState(null);\n var [dragstartListener, setDragstartListener] = useState(null);\n var [mousedownListener, setMousedownListener] = useState(null);\n var [mousemoveListener, setMousemoveListener] = useState(null);\n var [mouseoutListener, setMouseoutListener] = useState(null);\n var [mouseoverListener, setMouseoverListener] = useState(null);\n var [mouseupListener, setMouseupListener] = useState(null);\n var [rightclickListener, setRightclickListener] = useState(null);\n var [clickListener, setClickListener] = useState(null);\n var [dragListener, setDragListener] = useState(null);\n var [centerChangedListener, setCenterChangedListener] = useState(null);\n var [radiusChangedListener, setRadiusChangedListener] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (typeof options !== 'undefined' && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n if (typeof draggable !== 'undefined' && instance !== null) {\n instance.setDraggable(draggable);\n }\n }, [instance, draggable]);\n useEffect(() => {\n if (typeof editable !== 'undefined' && instance !== null) {\n instance.setEditable(editable);\n }\n }, [instance, editable]);\n useEffect(() => {\n if (typeof visible !== 'undefined' && instance !== null) {\n instance.setVisible(visible);\n }\n }, [instance, visible]);\n useEffect(() => {\n if (typeof radius === 'number' && instance !== null) {\n instance.setRadius(radius);\n }\n }, [instance, radius]);\n useEffect(() => {\n if (typeof center !== 'undefined' && instance !== null) {\n instance.setCenter(center);\n }\n }, [instance, center]);\n useEffect(() => {\n if (instance && onDblClick) {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n setDblclickListener(google.maps.event.addListener(instance, 'dblclick', onDblClick));\n }\n }, [onDblClick]);\n useEffect(() => {\n if (instance && onDragEnd) {\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n setDragendListener(google.maps.event.addListener(instance, 'dragend', onDragEnd));\n }\n }, [onDragEnd]);\n useEffect(() => {\n if (instance && onDragStart) {\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n setDragstartListener(google.maps.event.addListener(instance, 'dragstart', onDragStart));\n }\n }, [onDragStart]);\n useEffect(() => {\n if (instance && onMouseDown) {\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n setMousedownListener(google.maps.event.addListener(instance, 'mousedown', onMouseDown));\n }\n }, [onMouseDown]);\n useEffect(() => {\n if (instance && onMouseMove) {\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n setMousemoveListener(google.maps.event.addListener(instance, 'mousemove', onMouseMove));\n }\n }, [onMouseMove]);\n useEffect(() => {\n if (instance && onMouseOut) {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n setMouseoutListener(google.maps.event.addListener(instance, 'mouseout', onMouseOut));\n }\n }, [onMouseOut]);\n useEffect(() => {\n if (instance && onMouseOver) {\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n setMouseoverListener(google.maps.event.addListener(instance, 'mouseover', onMouseOver));\n }\n }, [onMouseOver]);\n useEffect(() => {\n if (instance && onMouseUp) {\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n setMouseupListener(google.maps.event.addListener(instance, 'mouseup', onMouseUp));\n }\n }, [onMouseUp]);\n useEffect(() => {\n if (instance && onRightClick) {\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n setRightclickListener(google.maps.event.addListener(instance, 'rightclick', onRightClick));\n }\n }, [onRightClick]);\n useEffect(() => {\n if (instance && onClick) {\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n setClickListener(google.maps.event.addListener(instance, 'click', onClick));\n }\n }, [onClick]);\n useEffect(() => {\n if (instance && onDrag) {\n if (dragListener !== null) {\n google.maps.event.removeListener(dragListener);\n }\n setDragListener(google.maps.event.addListener(instance, 'drag', onDrag));\n }\n }, [onDrag]);\n useEffect(() => {\n if (instance && onCenterChanged) {\n if (centerChangedListener !== null) {\n google.maps.event.removeListener(centerChangedListener);\n }\n setCenterChangedListener(google.maps.event.addListener(instance, 'center_changed', onCenterChanged));\n }\n }, [onClick]);\n useEffect(() => {\n if (instance && onRadiusChanged) {\n if (radiusChangedListener !== null) {\n google.maps.event.removeListener(radiusChangedListener);\n }\n setRadiusChangedListener(google.maps.event.addListener(instance, 'radius_changed', onRadiusChanged));\n }\n }, [onRadiusChanged]);\n useEffect(() => {\n var circle = new google.maps.Circle(_objectSpread$6(_objectSpread$6({}, options || defaultOptions), {}, {\n map\n }));\n if (typeof radius === 'number') {\n circle.setRadius(radius);\n }\n if (typeof center !== 'undefined') {\n circle.setCenter(center);\n }\n if (typeof radius === 'number') {\n circle.setRadius(radius);\n }\n if (typeof visible !== 'undefined') {\n circle.setVisible(visible);\n }\n if (typeof editable !== 'undefined') {\n circle.setEditable(editable);\n }\n if (typeof draggable !== 'undefined') {\n circle.setDraggable(draggable);\n }\n if (onDblClick) {\n setDblclickListener(google.maps.event.addListener(circle, 'dblclick', onDblClick));\n }\n if (onDragEnd) {\n setDragendListener(google.maps.event.addListener(circle, 'dragend', onDragEnd));\n }\n if (onDragStart) {\n setDragstartListener(google.maps.event.addListener(circle, 'dragstart', onDragStart));\n }\n if (onMouseDown) {\n setMousedownListener(google.maps.event.addListener(circle, 'mousedown', onMouseDown));\n }\n if (onMouseMove) {\n setMousemoveListener(google.maps.event.addListener(circle, 'mousemove', onMouseMove));\n }\n if (onMouseOut) {\n setMouseoutListener(google.maps.event.addListener(circle, 'mouseout', onMouseOut));\n }\n if (onMouseOver) {\n setMouseoverListener(google.maps.event.addListener(circle, 'mouseover', onMouseOver));\n }\n if (onMouseUp) {\n setMouseupListener(google.maps.event.addListener(circle, 'mouseup', onMouseUp));\n }\n if (onRightClick) {\n setRightclickListener(google.maps.event.addListener(circle, 'rightclick', onRightClick));\n }\n if (onClick) {\n setClickListener(google.maps.event.addListener(circle, 'click', onClick));\n }\n if (onDrag) {\n setDragListener(google.maps.event.addListener(circle, 'drag', onDrag));\n }\n if (onCenterChanged) {\n setCenterChangedListener(google.maps.event.addListener(circle, 'center_changed', onCenterChanged));\n }\n if (onRadiusChanged) {\n setRadiusChangedListener(google.maps.event.addListener(circle, 'radius_changed', onRadiusChanged));\n }\n setInstance(circle);\n if (onLoad) {\n onLoad(circle);\n }\n return () => {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n if (dragendListener !== null) {\n google.maps.event.removeListener(dragendListener);\n }\n if (dragstartListener !== null) {\n google.maps.event.removeListener(dragstartListener);\n }\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n if (centerChangedListener !== null) {\n google.maps.event.removeListener(centerChangedListener);\n }\n if (radiusChangedListener !== null) {\n google.maps.event.removeListener(radiusChangedListener);\n }\n if (onUnmount) {\n onUnmount(circle);\n }\n circle.setMap(null);\n };\n }, []);\n return null;\n}\nvar CircleF = memo(CircleFunctional);\nclass Circle extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n circle: null\n });\n _defineProperty(this, \"setCircleCallback\", () => {\n if (this.state.circle !== null && this.props.onLoad) {\n this.props.onLoad(this.state.circle);\n }\n });\n }\n componentDidMount() {\n var circle = new google.maps.Circle(_objectSpread$6(_objectSpread$6({}, this.props.options), {}, {\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$8,\n eventMap: eventMap$8,\n prevProps: {},\n nextProps: this.props,\n instance: circle\n });\n this.setState(function setCircle() {\n return {\n circle\n };\n }, this.setCircleCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.circle !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$8,\n eventMap: eventMap$8,\n prevProps,\n nextProps: this.props,\n instance: this.state.circle\n });\n }\n }\n componentWillUnmount() {\n if (this.state.circle !== null) {\n var _this$state$circle;\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.circle);\n }\n unregisterEvents(this.registeredEvents);\n (_this$state$circle = this.state.circle) === null || _this$state$circle === void 0 || _this$state$circle.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(Circle, \"contextType\", MapContext);\n\nfunction ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$7 = {\n onClick: 'click',\n onDblClick: 'dblclick',\n onMouseDown: 'mousedown',\n onMouseOut: 'mouseout',\n onMouseOver: 'mouseover',\n onMouseUp: 'mouseup',\n onRightClick: 'rightclick',\n onAddFeature: 'addfeature',\n onRemoveFeature: 'removefeature',\n onRemoveProperty: 'removeproperty',\n onSetGeometry: 'setgeometry',\n onSetProperty: 'setproperty'\n};\nvar updaterMap$7 = {\n add(instance, feature) {\n instance.add(feature);\n },\n addgeojson(instance, geojson, options) {\n instance.addGeoJson(geojson, options);\n },\n contains(instance, feature) {\n instance.contains(feature);\n },\n foreach(instance, callback) {\n instance.forEach(callback);\n },\n loadgeojson(instance, url, options, callback) {\n instance.loadGeoJson(url, options, callback);\n },\n overridestyle(instance, feature, style) {\n instance.overrideStyle(feature, style);\n },\n remove(instance, feature) {\n instance.remove(feature);\n },\n revertstyle(instance, feature) {\n instance.revertStyle(feature);\n },\n controlposition(instance, controlPosition) {\n instance.setControlPosition(controlPosition);\n },\n controls(instance, controls) {\n instance.setControls(controls);\n },\n drawingmode(instance, mode) {\n instance.setDrawingMode(mode);\n },\n map(instance, map) {\n instance.setMap(map);\n },\n style(instance, style) {\n instance.setStyle(style);\n },\n togeojson(instance, callback) {\n instance.toGeoJson(callback);\n }\n};\nfunction DataFunctional(_ref) {\n var {\n options,\n onClick,\n onDblClick,\n onMouseDown,\n onMouseMove,\n onMouseOut,\n onMouseOver,\n onMouseUp,\n onRightClick,\n onAddFeature,\n onRemoveFeature,\n onRemoveProperty,\n onSetGeometry,\n onSetProperty,\n onLoad,\n onUnmount\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n var [dblclickListener, setDblclickListener] = useState(null);\n var [mousedownListener, setMousedownListener] = useState(null);\n var [mousemoveListener, setMousemoveListener] = useState(null);\n var [mouseoutListener, setMouseoutListener] = useState(null);\n var [mouseoverListener, setMouseoverListener] = useState(null);\n var [mouseupListener, setMouseupListener] = useState(null);\n var [rightclickListener, setRightclickListener] = useState(null);\n var [clickListener, setClickListener] = useState(null);\n var [addFeatureListener, setAddFeatureListener] = useState(null);\n var [removeFeatureListener, setRemoveFeatureListener] = useState(null);\n var [removePropertyListener, setRemovePropertyListener] = useState(null);\n var [setGeometryListener, setSetGeometryListener] = useState(null);\n var [setPropertyListener, setSetPropertyListener] = useState(null);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (instance && onDblClick) {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n setDblclickListener(google.maps.event.addListener(instance, 'dblclick', onDblClick));\n }\n }, [onDblClick]);\n useEffect(() => {\n if (instance && onMouseDown) {\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n setMousedownListener(google.maps.event.addListener(instance, 'mousedown', onMouseDown));\n }\n }, [onMouseDown]);\n useEffect(() => {\n if (instance && onMouseMove) {\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n setMousemoveListener(google.maps.event.addListener(instance, 'mousemove', onMouseMove));\n }\n }, [onMouseMove]);\n useEffect(() => {\n if (instance && onMouseOut) {\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n setMouseoutListener(google.maps.event.addListener(instance, 'mouseout', onMouseOut));\n }\n }, [onMouseOut]);\n useEffect(() => {\n if (instance && onMouseOver) {\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n setMouseoverListener(google.maps.event.addListener(instance, 'mouseover', onMouseOver));\n }\n }, [onMouseOver]);\n useEffect(() => {\n if (instance && onMouseUp) {\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n setMouseupListener(google.maps.event.addListener(instance, 'mouseup', onMouseUp));\n }\n }, [onMouseUp]);\n useEffect(() => {\n if (instance && onRightClick) {\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n setRightclickListener(google.maps.event.addListener(instance, 'rightclick', onRightClick));\n }\n }, [onRightClick]);\n useEffect(() => {\n if (instance && onClick) {\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n setClickListener(google.maps.event.addListener(instance, 'click', onClick));\n }\n }, [onClick]);\n useEffect(() => {\n if (instance && onAddFeature) {\n if (addFeatureListener !== null) {\n google.maps.event.removeListener(addFeatureListener);\n }\n setAddFeatureListener(google.maps.event.addListener(instance, 'addfeature', onAddFeature));\n }\n }, [onAddFeature]);\n useEffect(() => {\n if (instance && onRemoveFeature) {\n if (removeFeatureListener !== null) {\n google.maps.event.removeListener(removeFeatureListener);\n }\n setRemoveFeatureListener(google.maps.event.addListener(instance, 'removefeature', onRemoveFeature));\n }\n }, [onRemoveFeature]);\n useEffect(() => {\n if (instance && onRemoveProperty) {\n if (removePropertyListener !== null) {\n google.maps.event.removeListener(removePropertyListener);\n }\n setRemovePropertyListener(google.maps.event.addListener(instance, 'removeproperty', onRemoveProperty));\n }\n }, [onRemoveProperty]);\n useEffect(() => {\n if (instance && onSetGeometry) {\n if (setGeometryListener !== null) {\n google.maps.event.removeListener(setGeometryListener);\n }\n setSetGeometryListener(google.maps.event.addListener(instance, 'setgeometry', onSetGeometry));\n }\n }, [onSetGeometry]);\n useEffect(() => {\n if (instance && onSetProperty) {\n if (setPropertyListener !== null) {\n google.maps.event.removeListener(setPropertyListener);\n }\n setSetPropertyListener(google.maps.event.addListener(instance, 'setproperty', onSetProperty));\n }\n }, [onSetProperty]);\n useEffect(() => {\n if (map !== null) {\n var data = new google.maps.Data(_objectSpread$5(_objectSpread$5({}, options), {}, {\n map\n }));\n if (onDblClick) {\n setDblclickListener(google.maps.event.addListener(data, 'dblclick', onDblClick));\n }\n if (onMouseDown) {\n setMousedownListener(google.maps.event.addListener(data, 'mousedown', onMouseDown));\n }\n if (onMouseMove) {\n setMousemoveListener(google.maps.event.addListener(data, 'mousemove', onMouseMove));\n }\n if (onMouseOut) {\n setMouseoutListener(google.maps.event.addListener(data, 'mouseout', onMouseOut));\n }\n if (onMouseOver) {\n setMouseoverListener(google.maps.event.addListener(data, 'mouseover', onMouseOver));\n }\n if (onMouseUp) {\n setMouseupListener(google.maps.event.addListener(data, 'mouseup', onMouseUp));\n }\n if (onRightClick) {\n setRightclickListener(google.maps.event.addListener(data, 'rightclick', onRightClick));\n }\n if (onClick) {\n setClickListener(google.maps.event.addListener(data, 'click', onClick));\n }\n if (onAddFeature) {\n setAddFeatureListener(google.maps.event.addListener(data, 'addfeature', onAddFeature));\n }\n if (onRemoveFeature) {\n setRemoveFeatureListener(google.maps.event.addListener(data, 'removefeature', onRemoveFeature));\n }\n if (onRemoveProperty) {\n setRemovePropertyListener(google.maps.event.addListener(data, 'removeproperty', onRemoveProperty));\n }\n if (onSetGeometry) {\n setSetGeometryListener(google.maps.event.addListener(data, 'setgeometry', onSetGeometry));\n }\n if (onSetProperty) {\n setSetPropertyListener(google.maps.event.addListener(data, 'setproperty', onSetProperty));\n }\n setInstance(data);\n if (onLoad) {\n onLoad(data);\n }\n }\n return () => {\n if (instance) {\n if (dblclickListener !== null) {\n google.maps.event.removeListener(dblclickListener);\n }\n if (mousedownListener !== null) {\n google.maps.event.removeListener(mousedownListener);\n }\n if (mousemoveListener !== null) {\n google.maps.event.removeListener(mousemoveListener);\n }\n if (mouseoutListener !== null) {\n google.maps.event.removeListener(mouseoutListener);\n }\n if (mouseoverListener !== null) {\n google.maps.event.removeListener(mouseoverListener);\n }\n if (mouseupListener !== null) {\n google.maps.event.removeListener(mouseupListener);\n }\n if (rightclickListener !== null) {\n google.maps.event.removeListener(rightclickListener);\n }\n if (clickListener !== null) {\n google.maps.event.removeListener(clickListener);\n }\n if (addFeatureListener !== null) {\n google.maps.event.removeListener(addFeatureListener);\n }\n if (removeFeatureListener !== null) {\n google.maps.event.removeListener(removeFeatureListener);\n }\n if (removePropertyListener !== null) {\n google.maps.event.removeListener(removePropertyListener);\n }\n if (setGeometryListener !== null) {\n google.maps.event.removeListener(setGeometryListener);\n }\n if (setPropertyListener !== null) {\n google.maps.event.removeListener(setPropertyListener);\n }\n if (onUnmount) {\n onUnmount(instance);\n }\n instance.setMap(null);\n }\n };\n }, []);\n return null;\n}\nvar DataF = memo(DataFunctional);\nclass Data extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n data: null\n });\n _defineProperty(this, \"setDataCallback\", () => {\n if (this.state.data !== null && this.props.onLoad) {\n this.props.onLoad(this.state.data);\n }\n });\n }\n componentDidMount() {\n if (this.context !== null) {\n var data = new google.maps.Data(_objectSpread$5(_objectSpread$5({}, this.props.options), {}, {\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$7,\n eventMap: eventMap$7,\n prevProps: {},\n nextProps: this.props,\n instance: data\n });\n this.setState(() => {\n return {\n data\n };\n }, this.setDataCallback);\n }\n }\n componentDidUpdate(prevProps) {\n if (this.state.data !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$7,\n eventMap: eventMap$7,\n prevProps,\n nextProps: this.props,\n instance: this.state.data\n });\n }\n }\n componentWillUnmount() {\n if (this.state.data !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.data);\n }\n unregisterEvents(this.registeredEvents);\n if (this.state.data) {\n this.state.data.setMap(null);\n }\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(Data, \"contextType\", MapContext);\n\nfunction ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$6 = {\n onClick: 'click',\n onDefaultViewportChanged: 'defaultviewport_changed',\n onStatusChanged: 'status_changed'\n};\nvar updaterMap$6 = {\n options(instance, options) {\n instance.setOptions(options);\n },\n url(instance, url) {\n instance.setUrl(url);\n },\n zIndex(instance, zIndex) {\n instance.setZIndex(zIndex);\n }\n};\nclass KmlLayer extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n kmlLayer: null\n });\n _defineProperty(this, \"setKmlLayerCallback\", () => {\n if (this.state.kmlLayer !== null && this.props.onLoad) {\n this.props.onLoad(this.state.kmlLayer);\n }\n });\n }\n componentDidMount() {\n var kmlLayer = new google.maps.KmlLayer(_objectSpread$4(_objectSpread$4({}, this.props.options), {}, {\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$6,\n eventMap: eventMap$6,\n prevProps: {},\n nextProps: this.props,\n instance: kmlLayer\n });\n this.setState(function setLmlLayer() {\n return {\n kmlLayer\n };\n }, this.setKmlLayerCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.kmlLayer !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$6,\n eventMap: eventMap$6,\n prevProps,\n nextProps: this.props,\n instance: this.state.kmlLayer\n });\n }\n }\n componentWillUnmount() {\n if (this.state.kmlLayer !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.kmlLayer);\n }\n unregisterEvents(this.registeredEvents);\n this.state.kmlLayer.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(KmlLayer, \"contextType\", MapContext);\n\nfunction getOffsetOverride(containerElement, getPixelPositionOffset) {\n return typeof getPixelPositionOffset === 'function' ? getPixelPositionOffset(containerElement.offsetWidth, containerElement.offsetHeight) : {\n x: 0,\n y: 0\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction createLatLng(inst, Type) {\n return new Type(inst.lat, inst.lng);\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction createLatLngBounds(inst, Type) {\n return new Type(new google.maps.LatLng(inst.ne.lat, inst.ne.lng), new google.maps.LatLng(inst.sw.lat, inst.sw.lng));\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction ensureOfType(inst,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfactory\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n return inst instanceof type ? inst : factory(inst, type);\n}\nfunction ensureOfTypeBounds(inst,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype,\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfactory\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n return inst instanceof type ? inst : factory(inst, type);\n}\nfunction getLayoutStylesByBounds(mapCanvasProjection, offset, bounds) {\n var ne = mapCanvasProjection && mapCanvasProjection.fromLatLngToDivPixel(bounds.getNorthEast());\n var sw = mapCanvasProjection && mapCanvasProjection.fromLatLngToDivPixel(bounds.getSouthWest());\n if (ne && sw) {\n return {\n left: \"\".concat(sw.x + offset.x, \"px\"),\n top: \"\".concat(ne.y + offset.y, \"px\"),\n width: \"\".concat(ne.x - sw.x - offset.x, \"px\"),\n height: \"\".concat(sw.y - ne.y - offset.y, \"px\")\n };\n }\n return {\n left: '-9999px',\n top: '-9999px'\n };\n}\nfunction getLayoutStylesByPosition(mapCanvasProjection, offset, position) {\n var point = mapCanvasProjection && mapCanvasProjection.fromLatLngToDivPixel(position);\n if (point) {\n var {\n x,\n y\n } = point;\n return {\n left: \"\".concat(x + offset.x, \"px\"),\n top: \"\".concat(y + offset.y, \"px\")\n };\n }\n return {\n left: '-9999px',\n top: '-9999px'\n };\n}\nfunction getLayoutStyles(mapCanvasProjection, offset, bounds, position) {\n return bounds !== undefined ? getLayoutStylesByBounds(mapCanvasProjection, offset, ensureOfTypeBounds(bounds, google.maps.LatLngBounds, createLatLngBounds)) : getLayoutStylesByPosition(mapCanvasProjection, offset, ensureOfType(position, google.maps.LatLng, createLatLng));\n}\nfunction arePositionsEqual(currentPosition, previousPosition) {\n return currentPosition.left === previousPosition.left && currentPosition.top === previousPosition.top && currentPosition.width === previousPosition.height && currentPosition.height === previousPosition.height;\n}\n\nfunction ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction createOverlay(container, pane, position, bounds, getPixelPositionOffset) {\n class Overlay extends google.maps.OverlayView {\n constructor(container, pane, position, bounds) {\n super();\n this.container = container;\n this.pane = pane;\n this.position = position;\n this.bounds = bounds;\n }\n onAdd() {\n var _this$getPanes;\n var pane = (_this$getPanes = this.getPanes()) === null || _this$getPanes === void 0 ? void 0 : _this$getPanes[this.pane];\n pane === null || pane === void 0 || pane.appendChild(this.container);\n }\n draw() {\n var projection = this.getProjection();\n var offset = _objectSpread$3({}, this.container ? getOffsetOverride(this.container, getPixelPositionOffset) : {\n x: 0,\n y: 0\n });\n var layoutStyles = getLayoutStyles(projection, offset, this.bounds, this.position);\n for (var [key, value] of Object.entries(layoutStyles)) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.container.style[key] = value;\n }\n }\n onRemove() {\n if (this.container.parentNode !== null) {\n this.container.parentNode.removeChild(this.container);\n }\n }\n }\n return new Overlay(container, pane, position, bounds);\n}\n\nfunction ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction convertToLatLngString(latLngLike) {\n if (!latLngLike) {\n return '';\n }\n var latLng = latLngLike instanceof google.maps.LatLng ? latLngLike : new google.maps.LatLng(latLngLike.lat, latLngLike.lng);\n return latLng + '';\n}\nfunction convertToLatLngBoundsString(latLngBoundsLike) {\n if (!latLngBoundsLike) {\n return '';\n }\n var latLngBounds = latLngBoundsLike instanceof google.maps.LatLngBounds ? latLngBoundsLike : new google.maps.LatLngBounds(new google.maps.LatLng(latLngBoundsLike.south, latLngBoundsLike.east), new google.maps.LatLng(latLngBoundsLike.north, latLngBoundsLike.west));\n return latLngBounds + '';\n}\nvar FLOAT_PANE = \"floatPane\";\nvar MAP_PANE = \"mapPane\";\nvar MARKER_LAYER = \"markerLayer\";\nvar OVERLAY_LAYER = \"overlayLayer\";\nvar OVERLAY_MOUSE_TARGET = \"overlayMouseTarget\";\nfunction OverlayViewFunctional(_ref) {\n var {\n position,\n bounds,\n mapPaneName,\n zIndex,\n onLoad,\n onUnmount,\n getPixelPositionOffset,\n children\n } = _ref;\n var map = useContext(MapContext);\n var container = useMemo(() => {\n var div = document.createElement('div');\n div.style.position = 'absolute';\n return div;\n }, []);\n var overlay = useMemo(() => {\n return createOverlay(container, mapPaneName, position, bounds, getPixelPositionOffset);\n }, [container, mapPaneName, position, bounds]);\n useEffect(() => {\n onLoad === null || onLoad === void 0 || onLoad(overlay);\n overlay === null || overlay === void 0 || overlay.setMap(map);\n return () => {\n onUnmount === null || onUnmount === void 0 || onUnmount(overlay);\n overlay === null || overlay === void 0 || overlay.setMap(null);\n };\n }, [map, overlay]);\n // to move the container to the foreground and background\n useEffect(() => {\n container.style.zIndex = \"\".concat(zIndex);\n }, [zIndex, container]);\n return ReactDOM.createPortal(children, container);\n}\nvar OverlayViewF = memo(OverlayViewFunctional);\nclass OverlayView extends PureComponent {\n constructor(props) {\n super(props);\n _defineProperty(this, \"state\", {\n paneEl: null,\n containerStyle: {\n // set initial position\n position: 'absolute'\n }\n });\n _defineProperty(this, \"updatePane\", () => {\n var mapPaneName = this.props.mapPaneName;\n // https://developers.google.com/maps/documentation/javascript/3.exp/reference#MapPanes\n var mapPanes = this.overlayView.getPanes();\n invariant(!!mapPaneName, \"OverlayView requires props.mapPaneName but got %s\", mapPaneName);\n if (mapPanes) {\n this.setState({\n paneEl: mapPanes[mapPaneName]\n });\n } else {\n this.setState({\n paneEl: null\n });\n }\n });\n _defineProperty(this, \"onAdd\", () => {\n var _this$props$onLoad, _this$props;\n this.updatePane();\n (_this$props$onLoad = (_this$props = this.props).onLoad) === null || _this$props$onLoad === void 0 || _this$props$onLoad.call(_this$props, this.overlayView);\n });\n _defineProperty(this, \"onPositionElement\", () => {\n var mapCanvasProjection = this.overlayView.getProjection();\n var offset = _objectSpread$2({\n x: 0,\n y: 0\n }, this.containerRef.current ? getOffsetOverride(this.containerRef.current, this.props.getPixelPositionOffset) : {});\n var layoutStyles = getLayoutStyles(mapCanvasProjection, offset, this.props.bounds, this.props.position);\n if (!arePositionsEqual(layoutStyles, {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n left: this.state.containerStyle.left,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n top: this.state.containerStyle.top,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n width: this.state.containerStyle.width,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n height: this.state.containerStyle.height\n })) {\n var _layoutStyles$top, _layoutStyles$left, _layoutStyles$width, _layoutStyles$height;\n this.setState({\n containerStyle: {\n top: (_layoutStyles$top = layoutStyles.top) !== null && _layoutStyles$top !== void 0 ? _layoutStyles$top : 0,\n left: (_layoutStyles$left = layoutStyles.left) !== null && _layoutStyles$left !== void 0 ? _layoutStyles$left : 0,\n width: (_layoutStyles$width = layoutStyles.width) !== null && _layoutStyles$width !== void 0 ? _layoutStyles$width : 0,\n height: (_layoutStyles$height = layoutStyles.height) !== null && _layoutStyles$height !== void 0 ? _layoutStyles$height : 0,\n position: 'absolute'\n }\n });\n }\n });\n _defineProperty(this, \"draw\", () => {\n this.onPositionElement();\n });\n _defineProperty(this, \"onRemove\", () => {\n var _this$props$onUnmount, _this$props2;\n this.setState(() => ({\n paneEl: null\n }));\n (_this$props$onUnmount = (_this$props2 = this.props).onUnmount) === null || _this$props$onUnmount === void 0 || _this$props$onUnmount.call(_this$props2, this.overlayView);\n });\n this.containerRef = createRef();\n // You must implement three methods: onAdd(), draw(), and onRemove().\n var overlayView = new google.maps.OverlayView();\n overlayView.onAdd = this.onAdd;\n overlayView.draw = this.draw;\n overlayView.onRemove = this.onRemove;\n this.overlayView = overlayView;\n }\n componentDidMount() {\n this.overlayView.setMap(this.context);\n }\n componentDidUpdate(prevProps) {\n var prevPositionString = convertToLatLngString(prevProps.position);\n var positionString = convertToLatLngString(this.props.position);\n var prevBoundsString = convertToLatLngBoundsString(prevProps.bounds);\n var boundsString = convertToLatLngBoundsString(this.props.bounds);\n if (prevPositionString !== positionString || prevBoundsString !== boundsString) {\n this.overlayView.draw();\n }\n if (prevProps.mapPaneName !== this.props.mapPaneName) {\n this.updatePane();\n }\n }\n componentWillUnmount() {\n this.overlayView.setMap(null);\n }\n render() {\n var paneEl = this.state.paneEl;\n if (paneEl) {\n return ReactDOM.createPortal(jsx(\"div\", {\n ref: this.containerRef,\n style: this.state.containerStyle,\n children: Children.only(this.props.children)\n }), paneEl);\n } else {\n return null;\n }\n }\n}\n_defineProperty(OverlayView, \"FLOAT_PANE\", \"floatPane\");\n_defineProperty(OverlayView, \"MAP_PANE\", \"mapPane\");\n_defineProperty(OverlayView, \"MARKER_LAYER\", \"markerLayer\");\n_defineProperty(OverlayView, \"OVERLAY_LAYER\", \"overlayLayer\");\n_defineProperty(OverlayView, \"OVERLAY_MOUSE_TARGET\", \"overlayMouseTarget\");\n_defineProperty(OverlayView, \"contextType\", MapContext);\n\nfunction noop() {\n return;\n}\n\nfunction ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$5 = {\n onDblClick: 'dblclick',\n onClick: 'click'\n};\nvar updaterMap$5 = {\n opacity(instance, opacity) {\n instance.setOpacity(opacity);\n }\n};\nfunction GroundOverlayFunctional(_ref) {\n var {\n url,\n bounds,\n options,\n visible\n } = _ref;\n var map = useContext(MapContext);\n var imageBounds = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.south, bounds.west), new google.maps.LatLng(bounds.north, bounds.east));\n var groundOverlay = useMemo(() => {\n return new google.maps.GroundOverlay(url, imageBounds, options);\n }, []);\n useEffect(() => {\n if (groundOverlay !== null) {\n groundOverlay.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (typeof url !== 'undefined' && groundOverlay !== null) {\n groundOverlay.set('url', url);\n groundOverlay.setMap(map);\n }\n }, [groundOverlay, url]);\n useEffect(() => {\n if (typeof visible !== 'undefined' && groundOverlay !== null) {\n groundOverlay.setOpacity(visible ? 1 : 0);\n }\n }, [groundOverlay, visible]);\n useEffect(() => {\n var newBounds = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.south, bounds.west), new google.maps.LatLng(bounds.north, bounds.east));\n if (typeof bounds !== 'undefined' && groundOverlay !== null) {\n groundOverlay.set('bounds', newBounds);\n groundOverlay.setMap(map);\n }\n }, [groundOverlay, bounds]);\n return null;\n}\nvar GroundOverlayF = memo(GroundOverlayFunctional);\nclass GroundOverlay extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n groundOverlay: null\n });\n _defineProperty(this, \"setGroundOverlayCallback\", () => {\n if (this.state.groundOverlay !== null && this.props.onLoad) {\n this.props.onLoad(this.state.groundOverlay);\n }\n });\n }\n componentDidMount() {\n invariant(!!this.props.url || !!this.props.bounds, \"For GroundOverlay, url and bounds are passed in to constructor and are immutable after instantiated. This is the behavior of Google Maps JavaScript API v3 ( See https://developers.google.com/maps/documentation/javascript/reference#GroundOverlay) Hence, use the corresponding two props provided by `react-google-maps-api`, url and bounds. In some cases, you'll need the GroundOverlay component to reflect the changes of url and bounds. You can leverage the React's key property to remount the component. Typically, just `key={url}` would serve your need. See https://github.com/tomchentw/react-google-maps/issues/655\");\n var groundOverlay = new google.maps.GroundOverlay(this.props.url, this.props.bounds, _objectSpread$1(_objectSpread$1({}, this.props.options), {}, {\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$5,\n eventMap: eventMap$5,\n prevProps: {},\n nextProps: this.props,\n instance: groundOverlay\n });\n this.setState(function setGroundOverlay() {\n return {\n groundOverlay\n };\n }, this.setGroundOverlayCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.groundOverlay !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$5,\n eventMap: eventMap$5,\n prevProps,\n nextProps: this.props,\n instance: this.state.groundOverlay\n });\n }\n }\n componentWillUnmount() {\n if (this.state.groundOverlay) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.groundOverlay);\n }\n this.state.groundOverlay.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(GroundOverlay, \"defaultProps\", {\n onLoad: noop\n});\n_defineProperty(GroundOverlay, \"contextType\", MapContext);\n\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nvar eventMap$4 = {};\nvar updaterMap$4 = {\n data(instance, data) {\n instance.setData(data);\n },\n map(instance, map) {\n instance.setMap(map);\n },\n options(instance, options) {\n instance.setOptions(options);\n }\n};\nfunction HeatmapLayerFunctional(_ref) {\n var {\n data,\n onLoad,\n onUnmount,\n options\n } = _ref;\n var map = useContext(MapContext);\n var [instance, setInstance] = useState(null);\n useEffect(() => {\n if (!google.maps.visualization) {\n invariant(!!google.maps.visualization, 'Did you include prop libraries={[\"visualization\"]} in useJsApiScript? %s', google.maps.visualization);\n }\n }, []);\n useEffect(() => {\n invariant(!!data, 'data property is required in HeatmapLayer %s', data);\n }, [data]);\n // Order does matter\n useEffect(() => {\n if (instance !== null) {\n instance.setMap(map);\n }\n }, [map]);\n useEffect(() => {\n if (options && instance !== null) {\n instance.setOptions(options);\n }\n }, [instance, options]);\n useEffect(() => {\n var heatmapLayer = new google.maps.visualization.HeatmapLayer(_objectSpread(_objectSpread({}, options), {}, {\n data,\n map\n }));\n setInstance(heatmapLayer);\n if (onLoad) {\n onLoad(heatmapLayer);\n }\n return () => {\n if (instance !== null) {\n if (onUnmount) {\n onUnmount(instance);\n }\n instance.setMap(null);\n }\n };\n }, []);\n return null;\n}\nvar HeatmapLayerF = memo(HeatmapLayerFunctional);\nclass HeatmapLayer extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n heatmapLayer: null\n });\n _defineProperty(this, \"setHeatmapLayerCallback\", () => {\n if (this.state.heatmapLayer !== null && this.props.onLoad) {\n this.props.onLoad(this.state.heatmapLayer);\n }\n });\n }\n componentDidMount() {\n invariant(!!google.maps.visualization, 'Did you include prop libraries={[\"visualization\"]} to ? %s', google.maps.visualization);\n invariant(!!this.props.data, 'data property is required in HeatmapLayer %s', this.props.data);\n var heatmapLayer = new google.maps.visualization.HeatmapLayer(_objectSpread(_objectSpread({}, this.props.options), {}, {\n data: this.props.data,\n map: this.context\n }));\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$4,\n eventMap: eventMap$4,\n prevProps: {},\n nextProps: this.props,\n instance: heatmapLayer\n });\n this.setState(function setHeatmapLayer() {\n return {\n heatmapLayer\n };\n }, this.setHeatmapLayerCallback);\n }\n componentDidUpdate(prevProps) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$4,\n eventMap: eventMap$4,\n prevProps,\n nextProps: this.props,\n instance: this.state.heatmapLayer\n });\n }\n componentWillUnmount() {\n if (this.state.heatmapLayer !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.heatmapLayer);\n }\n unregisterEvents(this.registeredEvents);\n this.state.heatmapLayer.setMap(null);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(HeatmapLayer, \"contextType\", MapContext);\n\nvar eventMap$3 = {\n onCloseClick: 'closeclick',\n onPanoChanged: 'pano_changed',\n onPositionChanged: 'position_changed',\n onPovChanged: 'pov_changed',\n onResize: 'resize',\n onStatusChanged: 'status_changed',\n onVisibleChanged: 'visible_changed',\n onZoomChanged: 'zoom_changed'\n};\nvar updaterMap$3 = {\n register(instance, provider, options) {\n instance.registerPanoProvider(provider, options);\n },\n links(instance, links) {\n instance.setLinks(links);\n },\n motionTracking(instance, motionTracking) {\n instance.setMotionTracking(motionTracking);\n },\n options(instance, options) {\n instance.setOptions(options);\n },\n pano(instance, pano) {\n instance.setPano(pano);\n },\n position(instance, position) {\n instance.setPosition(position);\n },\n pov(instance, pov) {\n instance.setPov(pov);\n },\n visible(instance, visible) {\n instance.setVisible(visible);\n },\n zoom(instance, zoom) {\n instance.setZoom(zoom);\n }\n};\nclass StreetViewPanorama extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n streetViewPanorama: null\n });\n _defineProperty(this, \"setStreetViewPanoramaCallback\", () => {\n if (this.state.streetViewPanorama !== null && this.props.onLoad) {\n this.props.onLoad(this.state.streetViewPanorama);\n }\n });\n }\n componentDidMount() {\n var _this$context$getStre, _this$context;\n var streetViewPanorama = (_this$context$getStre = (_this$context = this.context) === null || _this$context === void 0 ? void 0 : _this$context.getStreetView()) !== null && _this$context$getStre !== void 0 ? _this$context$getStre : null;\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$3,\n eventMap: eventMap$3,\n prevProps: {},\n nextProps: this.props,\n instance: streetViewPanorama\n });\n this.setState(() => {\n return {\n streetViewPanorama\n };\n }, this.setStreetViewPanoramaCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.streetViewPanorama !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$3,\n eventMap: eventMap$3,\n prevProps,\n nextProps: this.props,\n instance: this.state.streetViewPanorama\n });\n }\n }\n componentWillUnmount() {\n if (this.state.streetViewPanorama !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.streetViewPanorama);\n }\n unregisterEvents(this.registeredEvents);\n this.state.streetViewPanorama.setVisible(false);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(StreetViewPanorama, \"contextType\", MapContext);\n\nclass StreetViewService extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n streetViewService: null\n });\n _defineProperty(this, \"setStreetViewServiceCallback\", () => {\n if (this.state.streetViewService !== null && this.props.onLoad) {\n this.props.onLoad(this.state.streetViewService);\n }\n });\n }\n componentDidMount() {\n var streetViewService = new google.maps.StreetViewService();\n this.setState(function setStreetViewService() {\n return {\n streetViewService\n };\n }, this.setStreetViewServiceCallback);\n }\n componentWillUnmount() {\n if (this.state.streetViewService !== null && this.props.onUnmount) {\n this.props.onUnmount(this.state.streetViewService);\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(StreetViewService, \"contextType\", MapContext);\n\nclass DirectionsService extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n directionsService: null\n });\n _defineProperty(this, \"setDirectionsServiceCallback\", () => {\n if (this.state.directionsService !== null && this.props.onLoad) {\n this.props.onLoad(this.state.directionsService);\n }\n });\n }\n componentDidMount() {\n invariant(!!this.props.options, 'DirectionsService expected options object as parameter, but got %s', this.props.options);\n var directionsService = new google.maps.DirectionsService();\n this.setState(function setDirectionsService() {\n return {\n directionsService\n };\n }, this.setDirectionsServiceCallback);\n }\n componentDidUpdate() {\n if (this.state.directionsService !== null) {\n this.state.directionsService.route(this.props.options, this.props.callback);\n }\n }\n componentWillUnmount() {\n if (this.state.directionsService !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.directionsService);\n }\n }\n }\n render() {\n return null;\n }\n}\n\nvar eventMap$2 = {\n onDirectionsChanged: 'directions_changed'\n};\nvar updaterMap$2 = {\n directions(instance, directions) {\n instance.setDirections(directions);\n },\n map(instance, map) {\n instance.setMap(map);\n },\n options(instance, options) {\n instance.setOptions(options);\n },\n panel(instance, panel) {\n instance.setPanel(panel);\n },\n routeIndex(instance, routeIndex) {\n instance.setRouteIndex(routeIndex);\n }\n};\nclass DirectionsRenderer extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"state\", {\n directionsRenderer: null\n });\n _defineProperty(this, \"setDirectionsRendererCallback\", () => {\n if (this.state.directionsRenderer !== null) {\n this.state.directionsRenderer.setMap(this.context);\n if (this.props.onLoad) {\n this.props.onLoad(this.state.directionsRenderer);\n }\n }\n });\n }\n componentDidMount() {\n var directionsRenderer = new google.maps.DirectionsRenderer(this.props.options);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$2,\n eventMap: eventMap$2,\n prevProps: {},\n nextProps: this.props,\n instance: directionsRenderer\n });\n this.setState(function setDirectionsRenderer() {\n return {\n directionsRenderer\n };\n }, this.setDirectionsRendererCallback);\n }\n componentDidUpdate(prevProps) {\n if (this.state.directionsRenderer !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$2,\n eventMap: eventMap$2,\n prevProps,\n nextProps: this.props,\n instance: this.state.directionsRenderer\n });\n }\n }\n componentWillUnmount() {\n if (this.state.directionsRenderer !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.directionsRenderer);\n }\n unregisterEvents(this.registeredEvents);\n if (this.state.directionsRenderer) {\n this.state.directionsRenderer.setMap(null);\n }\n }\n }\n render() {\n return null;\n }\n}\n_defineProperty(DirectionsRenderer, \"contextType\", MapContext);\n\nclass DistanceMatrixService extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n distanceMatrixService: null\n });\n _defineProperty(this, \"setDistanceMatrixServiceCallback\", () => {\n if (this.state.distanceMatrixService !== null && this.props.onLoad) {\n this.props.onLoad(this.state.distanceMatrixService);\n }\n });\n }\n componentDidMount() {\n invariant(!!this.props.options, 'DistanceMatrixService expected options object as parameter, but go %s', this.props.options);\n var distanceMatrixService = new google.maps.DistanceMatrixService();\n this.setState(function setDistanceMatrixService() {\n return {\n distanceMatrixService\n };\n }, this.setDistanceMatrixServiceCallback);\n }\n componentDidUpdate() {\n if (this.state.distanceMatrixService !== null) {\n this.state.distanceMatrixService.getDistanceMatrix(this.props.options, this.props.callback);\n }\n }\n componentWillUnmount() {\n if (this.state.distanceMatrixService !== null && this.props.onUnmount) {\n this.props.onUnmount(this.state.distanceMatrixService);\n }\n }\n render() {\n return null;\n }\n}\n\nvar eventMap$1 = {\n onPlacesChanged: 'places_changed'\n};\nvar updaterMap$1 = {\n bounds(instance, bounds) {\n instance.setBounds(bounds);\n }\n};\nclass StandaloneSearchBox extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"containerElement\", createRef());\n _defineProperty(this, \"state\", {\n searchBox: null\n });\n _defineProperty(this, \"setSearchBoxCallback\", () => {\n if (this.state.searchBox !== null && this.props.onLoad) {\n this.props.onLoad(this.state.searchBox);\n }\n });\n }\n componentDidMount() {\n invariant(!!google.maps.places, 'You need to provide libraries={[\"places\"]} prop to component %s', google.maps.places);\n if (this.containerElement !== null && this.containerElement.current !== null) {\n var input = this.containerElement.current.querySelector('input');\n if (input !== null) {\n var searchBox = new google.maps.places.SearchBox(input, this.props.options);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$1,\n eventMap: eventMap$1,\n prevProps: {},\n nextProps: this.props,\n instance: searchBox\n });\n this.setState(function setSearchBox() {\n return {\n searchBox\n };\n }, this.setSearchBoxCallback);\n }\n }\n }\n componentDidUpdate(prevProps) {\n if (this.state.searchBox !== null) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap: updaterMap$1,\n eventMap: eventMap$1,\n prevProps,\n nextProps: this.props,\n instance: this.state.searchBox\n });\n }\n }\n componentWillUnmount() {\n if (this.state.searchBox !== null) {\n if (this.props.onUnmount) {\n this.props.onUnmount(this.state.searchBox);\n }\n unregisterEvents(this.registeredEvents);\n }\n }\n render() {\n return jsx(\"div\", {\n ref: this.containerElement,\n children: Children.only(this.props.children)\n });\n }\n}\n_defineProperty(StandaloneSearchBox, \"contextType\", MapContext);\n\nvar eventMap = {\n onPlaceChanged: 'place_changed'\n};\nvar updaterMap = {\n bounds(instance, bounds) {\n instance.setBounds(bounds);\n },\n restrictions(instance, restrictions) {\n instance.setComponentRestrictions(restrictions);\n },\n fields(instance, fields) {\n instance.setFields(fields);\n },\n options(instance, options) {\n instance.setOptions(options);\n },\n types(instance, types) {\n instance.setTypes(types);\n }\n};\nclass Autocomplete extends PureComponent {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"registeredEvents\", []);\n _defineProperty(this, \"containerElement\", createRef());\n _defineProperty(this, \"state\", {\n autocomplete: null\n });\n _defineProperty(this, \"setAutocompleteCallback\", () => {\n if (this.state.autocomplete !== null && this.props.onLoad) {\n this.props.onLoad(this.state.autocomplete);\n }\n });\n }\n componentDidMount() {\n var _this$containerElemen;\n invariant(!!google.maps.places, 'You need to provide libraries={[\"places\"]} prop to component %s', google.maps.places);\n // TODO: why current could be equal null?\n var input = (_this$containerElemen = this.containerElement.current) === null || _this$containerElemen === void 0 ? void 0 : _this$containerElemen.querySelector('input');\n if (input) {\n var autocomplete = new google.maps.places.Autocomplete(input, this.props.options);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap,\n eventMap,\n prevProps: {},\n nextProps: this.props,\n instance: autocomplete\n });\n this.setState(() => {\n return {\n autocomplete\n };\n }, this.setAutocompleteCallback);\n }\n }\n componentDidUpdate(prevProps) {\n unregisterEvents(this.registeredEvents);\n this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({\n updaterMap,\n eventMap,\n prevProps,\n nextProps: this.props,\n instance: this.state.autocomplete\n });\n }\n componentWillUnmount() {\n if (this.state.autocomplete !== null) {\n unregisterEvents(this.registeredEvents);\n }\n }\n render() {\n return jsx(\"div\", {\n ref: this.containerElement,\n className: this.props.className,\n children: Children.only(this.props.children)\n });\n }\n}\n_defineProperty(Autocomplete, \"defaultProps\", {\n className: ''\n});\n_defineProperty(Autocomplete, \"contextType\", MapContext);\n\nexport { Autocomplete, BicyclingLayer, BicyclingLayerF, Circle, CircleF, Data, DataF, DirectionsRenderer, DirectionsService, DistanceMatrixService, DrawingManager, DrawingManagerF, FLOAT_PANE, GoogleMap, index_esm as GoogleMapsMarkerClusterer, GoogleMarkerClusterer$1 as GoogleMarkerClusterer, GroundOverlay, GroundOverlayF, HeatmapLayer, HeatmapLayerF, InfoBoxComponent as InfoBox, InfoBoxF, InfoWindow, InfoWindowF, KmlLayer, LoadScript, LoadScriptNext$1 as LoadScriptNext, MAP_PANE, MARKER_LAYER, MapContext, Marker, ClustererComponent as MarkerClusterer, MarkerClustererF, MarkerF, OVERLAY_LAYER, OVERLAY_MOUSE_TARGET, OverlayView, OverlayViewF, Polygon, PolygonF, Polyline, PolylineF, Rectangle, RectangleF, StandaloneSearchBox, StreetViewPanorama, StreetViewService, TrafficLayer, TrafficLayerF, TransitLayer, TransitLayerF, useGoogleMap, useJsApiLoader, useLoadScript };\n//# sourceMappingURL=esm.js.map\n","//app/frontend/components/AddressAutocompleteMap.tsx\nimport React, { useRef, useEffect, useState } from 'react';\nimport { TextInput, Select } from '@mantine/core';\nimport { Autocomplete } from '@react-google-maps/api';\n\ninterface TimezoneOption {\n value: string;\n label: string;\n}\n\ninterface AddressAutocompleteProps {\n value: string;\n onChange: (value: string) => void;\n onTimezoneSelect: (timeZoneId: string) => void;\n timezoneValue: string;\n // Optional: you can pass additional props if needed (e.g., required, styles)\n}\n\nconst AddressAutocomplete: React.FC = ({\n value,\n onChange,\n onTimezoneSelect,\n timezoneValue,\n}) => {\n const autocompleteRef = useRef(null);\n const [timezoneOptions, setTimezoneOptions] = useState([]);\n const [loading, setLoading] = useState(false);\n\n // Fetch list of timezones on component mount\n useEffect(() => {\n fetchTimezoneList();\n }, []);\n\n const fetchTimezoneList = async () => {\n try {\n const apiKey = 'N2IE9BKU2EQR'; // Your TimeZoneDB API key\n const response = await fetch(`https://api.timezonedb.com/v2.1/list-time-zone?key=${apiKey}&format=json`);\n const data = await response.json();\n\n if (data.status === 'OK' && data.zones) {\n const options = data.zones.map((zone: any) => ({\n value: zone.zoneName,\n label: `${zone.zoneName} (${formatGMTOffset(zone.gmtOffset)})`,\n }));\n setTimezoneOptions(options);\n } else {\n console.error('Error fetching timezone list:', data.message);\n }\n } catch (error) {\n console.error('Error fetching timezone list:', error);\n }\n };\n\n const formatGMTOffset = (offsetSeconds: number) => {\n const hours = Math.floor(Math.abs(offsetSeconds) / 3600);\n const minutes = Math.floor((Math.abs(offsetSeconds) % 3600) / 60);\n const sign = offsetSeconds >= 0 ? '+' : '-';\n return `GMT${sign}${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;\n };\n\n const handleLoad = (autocomplete: google.maps.places.Autocomplete) => {\n autocompleteRef.current = autocomplete;\n };\n\n const handlePlaceChanged = () => {\n if (autocompleteRef.current) {\n const place = autocompleteRef.current.getPlace();\n console.log('🛐 place:', place);\n if (place && place.formatted_address && place.geometry) {\n const address = place.formatted_address;\n onChange(address); // update the address field\n console.log('🛐 address:', address);\n const location = place.geometry?.location;\n if (location) {\n fetchTimezoneAndUpdateField(location.lat(), location.lng());\n console.log('🛐 locationLocation:', location.lat(), location.lng());\n } else {\n console.warn('Location is undefined');\n }\n } else {\n console.warn('Place does not have a formatted address or geometry');\n }\n }\n };\n\n const fetchTimezoneAndUpdateField = async (lat: number, lng: number) => {\n setLoading(true);\n console.log('🛐 Fetching timezone for:', lat, lng);\n try {\n const apiKey = 'N2IE9BKU2EQR'; // Your TimeZoneDB API key\n const url = `https://api.timezonedb.com/v2.1/get-time-zone?key=${apiKey}&format=json&by=position&lat=${lat}&lng=${lng}`;\n\n const response = await fetch(url);\n const data = await response.json();\n\n console.log('🛐 data:', data);\n console.log('🛐 data.status:', data.status);\n\n if (data.status === 'OK') {\n console.log('Fetched Timezone:', data.zoneName);\n // Just pass the raw timezone ID directly\n onTimezoneSelect(data.zoneName);\n } else {\n console.error('Error in TimeZoneDB data:', data.message);\n }\n } catch (error) {\n console.error('Error fetching timezone:', error);\n } finally {\n setLoading(false);\n }\n };\n\n return (\n <>\n \n onChange(e.target.value)}\n labelProps={{\n style: {\n display: 'block',\n textAlign: 'left',\n marginBottom: '5px',\n color: 'white',\n },\n }}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n \n\n value && onTimezoneSelect(value)}\n searchable\n labelProps={{\n style: {\n display: 'block',\n textAlign: 'left',\n marginBottom: '5px',\n color: 'white',\n },\n }}\n disabled={loading}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n \n );\n};\n\nexport default AddressAutocomplete;\n","import { useState, useEffect, useRef } from 'react';\nimport { useForm } from '@mantine/form';\nimport { Select, Button, Drawer, Group, Text, Box, Pill, ActionIcon, Tooltip, Paper } from '@mantine/core';\nimport { DatePickerInput, TimeInput, Calendar, DatePicker } from '@mantine/dates';\nimport {\n IconPencil,\n IconTrash,\n IconX,\n IconCheck,\n IconClock,\n IconInfoCircle,\n IconRefresh,\n IconClockEdit,\n} from '@tabler/icons-react';\nimport dayjs from 'dayjs';\nimport { useMediaQuery } from '@mantine/hooks';\nimport timezoneData from '../entrypoints/utilities/timezones.json';\n\ninterface RecurringEventFieldsProps {\n form: any;\n}\n\n// Define interface for modified occurrences to store both date and time info\ninterface ModifiedOccurrence {\n originalDateId: number; // Store the original date's timestamp ID\n date: Date;\n startTime: string;\n endTime: string;\n isSkipped?: boolean; // Flag to mark skipped occurrences\n spansNextDay?: boolean; // Flag to indicate if the event spans to the next day\n}\n\nconst TIMEZONE_OPTIONS = Object.entries(timezoneData).map(([value, label]) => ({\n value,\n label: `${label} (${value})`,\n}));\n\nexport default function RecurringEventFields({ form }: RecurringEventFieldsProps) {\n const [recurrenceDates, setRecurrenceDates] = useState([]);\n const [modifiedOccurrences, setModifiedOccurrences] = useState([]);\n const [selectedOccurrence, setSelectedOccurrence] = useState(null);\n const [originalDateId, setOriginalDateId] = useState(null);\n const [selectedTime, setSelectedTime] = useState({ start: '', end: '' });\n const [eventSpansNextDay, setEventSpansNextDay] = useState(false);\n const [occurrenceSpansNextDay, setOccurrenceSpansNextDay] = useState(false);\n\n const [drawerOpen, setDrawerOpen] = useState(false);\n const isMobile = useMediaQuery('(max-width: 768px)');\n const [ordinalOccurrence, setOrdinalOccurrence] = useState('');\n const [originalValues, setOriginalValues] = useState({\n start: '',\n end: '',\n spansNextDay: false,\n });\n\n const startTimeRef = useRef(null);\n const endTimeRef = useRef(null);\n const drawerStartTimeRef = useRef(null);\n const drawerEndTimeRef = useRef(null);\n\n const startPickerControl = (\n startTimeRef.current?.showPicker()}>\n \n \n );\n const endPickerControl = (\n endTimeRef.current?.showPicker()}>\n \n \n );\n\n const drawerStartPickerControl = (\n drawerStartTimeRef.current?.showPicker()}>\n \n \n );\n const drawerEndPickerControl = (\n drawerEndTimeRef.current?.showPicker()}>\n \n \n );\n\n // Calculate day of week for monthly recurrence\n const dayOfWeek = form.values.recurring_event_start_date\n ? dayjs(form.values.recurring_event_start_date).format('dddd')\n : '';\n\n // Generate a clean array of final occurrences for database submission\n const getFinalOccurrencesForSubmission = () => {\n return recurrenceDates\n .filter((date) => {\n // Filter out skipped occurrences\n const dateId = date.getTime();\n const modified = modifiedOccurrences.find(\n (occ) => occ.originalDateId === dateId || occ.date.getTime() === dateId,\n );\n\n return !(modified && modified.isSkipped);\n })\n .map((date) => {\n const dateId = date.getTime();\n const modified = modifiedOccurrences.find(\n (occ) => (occ.originalDateId === dateId || occ.date.getTime() === dateId) && !occ.isSkipped,\n );\n\n // Format the date and time as needed for your Rails backend\n return {\n date: date.toISOString().split('T')[0], // YYYY-MM-DD format\n start_time: modified ? modified.startTime : form.values.recurring_event_start_time,\n end_time: modified ? modified.endTime : form.values.recurring_event_end_time,\n spans_next_day: modified\n ? modified.spansNextDay !== undefined\n ? modified.spansNextDay\n : form.values.spans_next_day || false\n : form.values.spans_next_day || false,\n };\n });\n };\n\n // Export the occurrences data to the parent form\n useEffect(() => {\n // This will update a field in your form with the final occurrences data\n // whenever any relevant data changes\n const finalOccurrences = getFinalOccurrencesForSubmission();\n form.setFieldValue('recurring_event_occurrences', finalOccurrences);\n\n console.log('Final Occurrences for Submission:', finalOccurrences);\n }, [\n recurrenceDates,\n modifiedOccurrences,\n form.values.recurring_event_start_time,\n form.values.recurring_event_end_time,\n ]);\n\n useEffect(() => {\n console.log('Current value of eventSpansNextDay:', eventSpansNextDay);\n }, [eventSpansNextDay]);\n\n useEffect(() => {\n console.log('Current value of occurrenceSpansNextDay:', occurrenceSpansNextDay);\n }, [occurrenceSpansNextDay]);\n\n // Log the current state of recurrence dates and modifications\n useEffect(() => {\n // Get a clean representation of the data for logging\n const occurrencesData = recurrenceDates.map((date) => {\n const dateId = date.getTime();\n const modified = modifiedOccurrences.find(\n (occ) => occ.originalDateId === dateId || occ.date.getTime() === dateId,\n );\n\n return {\n date: dayjs(date).format('YYYY-MM-DD'),\n time:\n modified && modified.isSkipped\n ? 'SKIPPED'\n : modified\n ? `${modified.startTime} - ${modified.endTime}`\n : `${form.values.recurring_event_start_time} - ${form.values.recurring_event_end_time}`,\n status: modified ? (modified.isSkipped ? 'skipped' : 'modified') : 'default',\n originalDateId: modified?.originalDateId ? dayjs(new Date(modified.originalDateId)).format('YYYY-MM-DD') : null,\n spansNextDay: modified\n ? modified.spansNextDay !== undefined\n ? modified.spansNextDay\n : form.values.spans_next_day || false\n : form.values.spans_next_day || false,\n };\n });\n\n console.log('Current Occurrences:', occurrencesData);\n console.log('Raw Modified Occurrences:', modifiedOccurrences);\n }, [\n recurrenceDates,\n modifiedOccurrences,\n form.values.recurring_event_start_time,\n form.values.recurring_event_end_time,\n form.values.spans_next_day,\n ]);\n\n // Get maximum allowed occurrences for the current pattern\n const getMaxOccurrencesForPattern = (pattern: string) => {\n switch (pattern) {\n case 'Weekly':\n return 12; // Maximum of 12 occurrences for weekly\n case 'Bi-Weekly':\n return 6; // Maximum of 6 occurrences for bi-weekly\n case 'Monthly':\n return 3; // Maximum of 3 occurrences for monthly\n default:\n return 12; // Default to 12 if no pattern specified\n }\n };\n\n // Handle recurrence pattern change - enforce occurrence limits\n useEffect(() => {\n if (!form.values.recurrence_pattern) return;\n\n const maxAllowed = getMaxOccurrencesForPattern(form.values.recurrence_pattern);\n const currentValue = parseInt(form.values.num_occurrences || '0', 10);\n\n // If current value is greater than max allowed or not set, update it\n if (currentValue > maxAllowed || currentValue === 0) {\n form.setFieldValue('num_occurrences', maxAllowed);\n console.log(`Updated occurrences to ${maxAllowed} (max for ${form.values.recurrence_pattern})`);\n }\n\n // Clean up any modifications for dates that will no longer exist\n if (recurrenceDates.length > 0) {\n // We'll need to regenerate potential dates to compare against\n let baseDate = form.values.recurring_event_start_date\n ? new Date(form.values.recurring_event_start_date)\n : new Date();\n\n let potentialDates: Date[] = [];\n for (let i = 0; i < maxAllowed; i++) {\n let newDate = new Date(baseDate);\n\n if (form.values.recurrence_pattern === 'Weekly') newDate.setDate(baseDate.getDate() + i * 7);\n else if (form.values.recurrence_pattern === 'Bi-Weekly') newDate.setDate(baseDate.getDate() + i * 14);\n else if (form.values.recurrence_pattern === 'Monthly') newDate = dayjs(baseDate).add(i, 'month').toDate();\n\n potentialDates.push(newDate);\n }\n\n // Filter out modifications for dates that won't exist anymore\n setModifiedOccurrences((prevModifications) => {\n return prevModifications.filter((mod) => {\n // Check if any potential date matches this modification\n return potentialDates.some((date) => {\n const dateId = date.getTime();\n return mod.originalDateId === dateId || mod.date.getTime() === dateId;\n });\n });\n });\n }\n }, [form.values.recurrence_pattern]);\n\n // Generate Recurrence Dates\n useEffect(() => {\n const { recurring_event_start_date, recurrence_pattern, num_occurrences } = form.values;\n if (!recurring_event_start_date || !num_occurrences) return;\n\n let dates: Date[] = [];\n let baseDate = new Date(recurring_event_start_date);\n\n for (let i = 0; i < num_occurrences; i++) {\n let newDate = new Date(baseDate);\n\n if (recurrence_pattern === 'Weekly') newDate.setDate(baseDate.getDate() + i * 7);\n if (recurrence_pattern === 'Bi-Weekly') newDate.setDate(baseDate.getDate() + i * 14);\n if (recurrence_pattern === 'Monthly') {\n newDate = dayjs(baseDate).add(i, 'month').toDate();\n }\n\n dates.push(newDate);\n }\n\n // Set ordinal occurrence for monthly pattern\n if (recurrence_pattern === 'Monthly' && baseDate) {\n const day = baseDate.getDate();\n const weekNum = Math.ceil(day / 7);\n const ordinals = ['First', 'Second', 'Third', 'Fourth', 'Last'];\n setOrdinalOccurrence(ordinals[Math.min(weekNum - 1, 4)]);\n }\n\n setRecurrenceDates(dates);\n }, [form.values.recurring_event_start_date, form.values.recurrence_pattern, form.values.num_occurrences]);\n\n // Modify Occurrence\n const handleModify = (date: Date) => {\n const dateId = date.getTime();\n setOriginalDateId(dateId);\n setSelectedOccurrence(date);\n\n // Find an existing modification for this occurrence\n const modifiedOccurrence = modifiedOccurrences.find((occ) => occ.originalDateId === dateId);\n\n if (modifiedOccurrence) {\n setSelectedTime({\n start: modifiedOccurrence.startTime,\n end: modifiedOccurrence.endTime,\n });\n setOccurrenceSpansNextDay(modifiedOccurrence.spansNextDay ?? form.values.spans_next_day);\n } else {\n // Store the current values to check for modifications later\n setSelectedTime({\n start: form.values.recurring_event_start_time || '',\n end: form.values.recurring_event_end_time || '',\n });\n setOccurrenceSpansNextDay(form.values.spans_next_day || false);\n }\n\n // Store the original values for comparison when saving\n setOriginalValues({\n start: form.values.recurring_event_start_time || '',\n end: form.values.recurring_event_end_time || '',\n spansNextDay: form.values.spans_next_day || false,\n });\n\n setDrawerOpen(true);\n };\n\n const saveModification = () => {\n if (!selectedOccurrence || originalDateId === null) {\n console.error('❌ No occurrence selected for modification.');\n return;\n }\n\n console.log('📝 Time values before saving:', {\n start: selectedTime.start,\n end: selectedTime.end,\n spansNextDay: occurrenceSpansNextDay, // Updated this line\n });\n\n // Validate time format (HH:MM format)\n const timeRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;\n if (!timeRegex.test(selectedTime.start) || !timeRegex.test(selectedTime.end)) {\n console.error('❌ Invalid time format. Expected HH:MM format.');\n return;\n }\n\n // Check if any modifications were made\n const dateWasChanged = selectedOccurrence.getTime() !== originalDateId;\n const timeWasChanged =\n selectedTime.start !== form.values.recurring_event_start_time ||\n selectedTime.end !== form.values.recurring_event_end_time;\n const spansNextDayChanged = occurrenceSpansNextDay !== form.values.spans_next_day;\n\n const hasModifications = dateWasChanged || timeWasChanged || spansNextDayChanged;\n\n if (!hasModifications) {\n console.log('✅ No modifications detected. Closing drawer.');\n setDrawerOpen(false);\n return;\n }\n\n // Find existing modification by originalDateId\n const existingIndex = modifiedOccurrences.findIndex((occ) => occ.originalDateId === originalDateId);\n\n // Update or add to modifiedOccurrences list\n const updatedOccurrence = {\n originalDateId,\n date: selectedOccurrence,\n startTime: selectedTime.start,\n endTime: selectedTime.end,\n spansNextDay: occurrenceSpansNextDay, // Updated this line\n };\n\n if (existingIndex >= 0) {\n const updatedOccurrences = [...modifiedOccurrences];\n updatedOccurrences[existingIndex] = updatedOccurrence;\n setModifiedOccurrences(updatedOccurrences);\n } else {\n setModifiedOccurrences([...modifiedOccurrences, updatedOccurrence]);\n }\n\n // Update the recurrence dates list if the date was changed\n if (dateWasChanged) {\n setRecurrenceDates((prevDates) =>\n prevDates.map((date) => (date.getTime() === originalDateId ? selectedOccurrence : date)),\n );\n }\n\n console.log('✅ Modification saved successfully.');\n setDrawerOpen(false);\n };\n\n // Get occurrence display time (either modified or default)\n const getOccurrenceTime = (date: Date) => {\n const dateId = date.getTime();\n const modified = modifiedOccurrences.find((occ) => {\n // Check if this is a modified occurrence by comparing its ID or the new date\n return (occ.originalDateId === dateId || occ.date.getTime() === dateId) && !occ.isSkipped;\n });\n\n if (modified) {\n return {\n start: modified.startTime,\n end: modified.endTime,\n spansNextDay: modified.spansNextDay !== undefined ? modified.spansNextDay : form.values.spans_next_day || false,\n };\n }\n\n return {\n start: form.values.recurring_event_start_time,\n end: form.values.recurring_event_end_time,\n spansNextDay: form.values.spans_next_day || false,\n };\n };\n\n // Check if an occurrence has been modified\n const isOccurrenceModified = (date: Date) => {\n const dateId = date.getTime();\n return modifiedOccurrences.some(\n (occ) => (occ.originalDateId === dateId || occ.date.getTime() === dateId) && !occ.isSkipped,\n );\n };\n\n // Check if an occurrence has been skipped\n const isOccurrenceSkipped = (date: Date) => {\n const dateId = date.getTime();\n return modifiedOccurrences.some(\n (occ) => (occ.originalDateId === dateId || occ.date.getTime() === dateId) && occ.isSkipped,\n );\n };\n\n // Get a specific occurrence by date\n const getOccurrence = (date: Date) => {\n const dateId = date.getTime();\n return modifiedOccurrences.find((occ) => occ.originalDateId === dateId || occ.date.getTime() === dateId);\n };\n\n // Format time string to AM/PM format\n const formatTimeToAMPM = (timeStr: string) => {\n if (!timeStr) return '';\n\n try {\n return dayjs(`2025-01-01 ${timeStr}`, 'YYYY-MM-DD HH:mm').format('h:mm A');\n } catch (e) {\n console.error('Error formatting time:', e);\n return timeStr; // Return original if format fails\n }\n };\n\n // Handle skipping an occurrence\n const handleSkipOccurrence = (date: Date) => {\n const dateId = date.getTime();\n\n // Check if this occurrence is already in the modified list\n const existingIndex = modifiedOccurrences.findIndex(\n (occ) => occ.originalDateId === dateId || occ.date.getTime() === dateId,\n );\n\n if (existingIndex >= 0) {\n // Update existing occurrence to be skipped\n const updatedOccurrences = [...modifiedOccurrences];\n updatedOccurrences[existingIndex] = {\n ...updatedOccurrences[existingIndex],\n isSkipped: true,\n };\n setModifiedOccurrences(updatedOccurrences);\n } else {\n // Add new skipped occurrence\n setModifiedOccurrences([\n ...modifiedOccurrences,\n {\n originalDateId: dateId,\n date,\n startTime: form.values.recurring_event_start_time || '',\n endTime: form.values.recurring_event_end_time || '',\n isSkipped: true,\n },\n ]);\n }\n };\n\n // Handle restoring an occurrence to original state\n const handleRestoreOccurrence = (date: Date) => {\n const dateId = date.getTime();\n\n // Remove this occurrence from the modified list to restore default behavior\n setModifiedOccurrences(\n modifiedOccurrences.filter((occ) => !(occ.originalDateId === dateId || occ.date.getTime() === dateId)),\n );\n\n // If this was a date change, restore the original date in the recurrence dates\n const modifiedOcc = modifiedOccurrences.find(\n (occ) => occ.originalDateId === dateId || occ.date.getTime() === dateId,\n );\n\n if (modifiedOcc && modifiedOcc.originalDateId !== modifiedOcc.date.getTime()) {\n // Find the original date in recurrence dates\n setRecurrenceDates((prevDates) => {\n return prevDates.map((d) => {\n if (d.getTime() === modifiedOcc.date.getTime()) {\n // Create a new date with the original ID\n const originalDate = new Date(modifiedOcc.originalDateId);\n return originalDate;\n }\n return d;\n });\n });\n }\n };\n\n return (\n
      \n \n form.setFieldValue('recurring_event_start_date', date ? date.toISOString() : '')}\n required\n styles={{ label: { color: '#FFF7ED' } }}\n />\n\n form.setFieldValue('recurrence_pattern', value)}\n />\n \n\n \n
      \n form.setFieldValue('recurring_event_start_time', e.target.value)}\n rightSection={startPickerControl}\n ref={startTimeRef}\n required\n styles={{ label: { color: '#FFF7ED' } }}\n />\n
      \n
      \n form.setFieldValue('recurring_event_end_time', e.target.value)}\n required\n styles={{ label: { color: '#FFF7ED' } }}\n />\n
      \n\n {/* Spans Next Day Section */}\n
      \n\n {/* Recurrence Pattern */}\n \n {/* Recurrence Pattern & # of Occurrences */}\n\n \n \n \n Next Day?\n \n \n \n \n \n \n
      \n {\n console.log('Event duration selected:', newValue);\n setEventSpansNextDay(newValue === 'Ends Next Day');\n }}\n styles={{ label: { color: '#FFF7ED' } }}\n clearable\n />\n \n\n (i + 2).toString())\n : form.values.recurrence_pattern === 'Bi-Weekly'\n ? Array.from({ length: 5 }, (_, i) => (i + 2).toString())\n : Array.from({ length: 2 }, (_, i) => (i + 2).toString())\n }\n value={form.values.num_occurrences?.toString() || '2'}\n onChange={(value) => form.setFieldValue('num_occurrences', value ? parseInt(value, 10) : 0)}\n />\n \n\n {form.values.recurrence_pattern === 'Monthly' && (\n \n \n \n Ordinal Occurrence\n \n \n {ordinalOccurrence}\n \n \n \n \n Day of the Week\n \n \n {dayOfWeek}\n \n \n \n )}\n\n
      \n {recurrenceDates.map((date, index) => {\n const modified = isOccurrenceModified(date);\n const skipped = isOccurrenceSkipped(date);\n const occurrenceTime = getOccurrenceTime(date);\n\n const formattedStartTime = formatTimeToAMPM(occurrenceTime.start);\n const formattedEndTime = formatTimeToAMPM(occurrenceTime.end);\n\n return (\n \n \n \n \n {dayjs(date).format('ddd, MMM D, YYYY')} {' - '}\n {skipped ? 'SKIPPED' : `${formattedStartTime} to ${formattedEndTime}`}\n \n {modified && (\n \n \n \n )}\n {skipped && (\n \n \n \n )}\n \n \n {!skipped && (\n handleModify(date)}\n styles={{ root: { padding: '0.75rem' } }}\n >\n \n \n )}\n\n {(modified || skipped) && (\n handleRestoreOccurrence(date)}\n styles={{ root: { padding: '0.75rem' } }}\n >\n \n \n )}\n\n {!skipped && (\n handleSkipOccurrence(date)}\n styles={{ root: { padding: '0.75rem' } }}\n >\n \n \n )}\n \n \n \n );\n })}\n
      \n\n {/* Modify Drawer */}\n setDrawerOpen(false)}\n title=\"Modify Occurrence\"\n position=\"right\"\n styles={{\n content: { backgroundColor: '#3d3c3e' },\n header: { backgroundColor: '#2c2b2d', marginBottom: '2rem' },\n title: { color: '#f2f2f2', fontWeight: 600, fontSize: '1.5rem' },\n }}\n >\n {/* Select Occurrence Date */}\n {\n if (date) {\n setSelectedOccurrence(date);\n console.log('Date changed to:', date);\n }\n }}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n\n {/* Modify Start Time */}\n {\n console.log('Start time changed to:', e.target.value);\n setSelectedTime({ ...selectedTime, start: e.target.value });\n }}\n />\n\n {/* Modify End Time */}\n {\n console.log('End time changed to:', e.target.value);\n setSelectedTime({ ...selectedTime, end: e.target.value });\n }}\n />\n\n {/* Spans Next Day Option */}\n
      \n \n \n Next Day?\n \n \n \n \n \n \n
      \n {\n console.log('Occurrence duration selected:', newValue);\n setOccurrenceSpansNextDay(newValue === 'Ends Next Day');\n }}\n styles={{ label: { color: '#FFF7ED' } }}\n clearable\n />\n \n\n {/* Save Button */}\n \n \n \n \n \n \n );\n}\n","import { useState, useEffect, useMemo, useRef, Key, JSX } from 'react';\nimport { Head, usePage, router, PageProps } from '@inertiajs/react';\nimport { useForm } from '@mantine/form';\nimport {\n Container,\n TextInput,\n Select,\n Button,\n Group,\n Paper,\n Title,\n SegmentedControl,\n Accordion,\n Alert,\n MantineProvider,\n createTheme,\n Text,\n MultiSelect,\n ActionIcon,\n Stack,\n Avatar,\n Box,\n Pill,\n LoadingOverlay,\n} from '@mantine/core';\nimport { DatePickerInput, TimeInput, Calendar } from '@mantine/dates';\nimport { useDebouncedValue, useDisclosure } from '@mantine/hooks';\nimport { useUser, User } from '../../src/context/UserContext';\nimport { Notifications, showNotification } from '@mantine/notifications';\nimport {\n IconAlertCircle,\n IconCheck,\n IconCalendarTime,\n IconUsersGroup,\n IconClock,\n IconCalendarPlus,\n IconMapPinFilled,\n IconList,\n IconLink,\n IconAlertTriangle,\n IconInfoCircle,\n} from '@tabler/icons-react';\nimport { RichTextEditor } from '@mantine/tiptap';\nimport { useEditor, EditorContent } from '@tiptap/react';\nimport Highlight from '@tiptap/extension-highlight';\nimport StarterKit from '@tiptap/starter-kit';\nimport Underline from '@tiptap/extension-underline';\nimport TextAlign from '@tiptap/extension-text-align';\nimport Heading from '@tiptap/extension-heading';\nimport Link from '@tiptap/extension-link';\nimport ImageUploadModal from '../../components/ImageUploadModal';\nimport AddressAutocomplete from '../../components/AddressAutocompleteMap';\nimport RecurringEventFields from '../../components/RecurringEventFields';\nimport timezoneData from '../../entrypoints/utilities/timezones.json';\nimport dayjs from 'dayjs';\nimport { useMediaQuery } from '@mantine/hooks';\n\nimport '@mantine/core/styles.css';\nimport '@mantine/notifications/styles.css';\nimport '../../styles/Login-form.css';\nimport '@mantine/tiptap/styles.css';\nimport '@mantine/dates/styles.css';\n\ntype Artist = {\n id: number;\n name: string;\n avatar_url: string;\n};\n\ninterface User {\n id: number;\n email: string;\n username: string;\n avatar_url: string | null;\n roles: string[];\n organizer_ids?: number[];\n}\n\ninterface EventType {\n id: number;\n name: string;\n}\n\ninterface DanceStyle {\n id: number;\n name: string;\n}\n\ninterface EventData {\n id: number;\n name: string;\n slug?: string;\n description?: string;\n address?: string;\n online_event?: boolean;\n is_recurring?: boolean;\n spans_next_day?: boolean;\n timezone?: string[];\n event_start_date?: string;\n event_end_date?: string;\n website_url?: string;\n ticket_url?: string;\n facebook_url?: string;\n event_type_ids?: number[];\n dance_style_ids?: number[];\n event_frequency_id?: number;\n tiktok_url: string;\n meetup_url: string;\n instagram_url: string;\n event_image_url: string | null;\n artists_ids?: number[];\n user_id?: number;\n event_status_id?: number;\n organizer_ids?: number[];\n event_image?: File | null;\n event_start_time?: string;\n event_end_time?: string;\n}\n\ninterface EventFrequency {\n id: number;\n name: string;\n}\n\ninterface RecurringEvent {\n id: number;\n title: string;\n}\n\ninterface CreateEventPageProps extends PageProps, Record {\n event: {\n id: number;\n name: string;\n slug?: string;\n description?: string;\n address?: string;\n online_event?: boolean;\n is_recurring?: boolean;\n spans_next_day?: boolean;\n timezone?: string;\n event_start_date?: string;\n event_end_date?: string;\n event_start_time?: string;\n event_end_time?: string;\n website_url?: string;\n ticket_url?: string;\n facebook_url?: string;\n event_type_ids?: number[];\n dance_style_ids?: number[];\n event_frequency_id?: number;\n tiktok_url: string;\n meetup_url: string;\n instagram_url: string;\n event_image_url: string;\n artists?: Artist[];\n artists_ids?: number[];\n dance_style?: DanceStyle[];\n recurring_event?: RecurringEvent;\n user_id?: number;\n event_status_id?: number;\n organizer_ids?: number[];\n };\n artists?: Artist[];\n event_types: EventType[];\n dance_styles: DanceStyle[];\n event_frequencies: EventFrequency[];\n organizers?: Array<[string, number]>;\n errors?: Record;\n user?: Array<[string, number]>;\n}\n\nconst ordinalOptions = ['1st', '2nd', '3rd', '4th', '5th', 'Last'];\nconst dayOptions = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\n\nexport default function CreateEvent() {\n const [isRecurring, setIsRecurring] = useState(false);\n const [ordinalOccurrence, setOrdinalOccurrence] = useState('');\n const [dayOfWeek, setDayOfWeek] = useState('');\n\n const { user, refreshUser } = useUser() as { user: User | null; refreshUser: () => Promise };\n\n const { props } = usePage();\n\n const {\n event,\n errors,\n artists: propArtists,\n event_types: propEventTypes,\n dance_styles: propDanceStyles,\n event_frequencies: propEventFrequencies,\n users: propUsers,\n event_statuses: propEventStatuses,\n organizers: propOrganizers,\n } = props;\n\n const [eventName, setEventName] = useState('');\n const [slug, setSlug] = useState('');\n const [debouncedSlug] = useDebouncedValue(slug, 500); // 500ms debounce\n const [slugStatus, setSlugStatus] = useState<'idle' | 'checking' | 'valid' | 'invalid'>('idle');\n const [seoImagePreview, setSeoImagePreview] = useState(event.event_image_url);\n\n const handleImageChange = (file: File) => {\n // Update your local component state:\n setValues((prevValues) => {\n const newValues = { ...prevValues, event_image: file };\n\n return newValues;\n });\n\n // Also update the form's state:\n form.setFieldValue('event_image', file);\n\n // Update preview:\n setSeoImagePreview(URL.createObjectURL(file));\n };\n\n // Create a function to parameterize the event name\n const handleEventNameChange = (e) => {\n const newEventName = e.target.value;\n form.setFieldValue('name', newEventName);\n\n // Generate parameterized slug\n const parameterizedSlug = newEventName\n .toLowerCase()\n .replace(/\\s+/g, '-') // Replace spaces with hyphen\n .replace(/[^a-z0-9-]/g, '') // Remove all characters except lowercase letters, numbers, and hyphens\n .replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen\n .replace(/^-|-$/g, ''); // Remove leading and trailing hyphens\n\n setSlug(parameterizedSlug);\n form.setFieldValue('slug', parameterizedSlug);\n };\n\n const form = useForm({\n initialValues: {\n id: event.id || null,\n name: event.name || '',\n slug: event.slug || '',\n description: event.description || '',\n address: event.address || '',\n timezone: event.timezone || '',\n online_event: event.online_event ? 'true' : 'false',\n is_recurring: event.is_recurring ? 'true' : 'false',\n spans_next_day: event.spans_next_day ? 'true' : 'false',\n event_start_date: event.event_start_date,\n event_start_time: event.event_start_time,\n event_end_time: event.event_end_time,\n event_end_date: event.event_end_date,\n website_url: event.website_url,\n ticket_url: event.ticket_url,\n facebook_url: event.facebook_url,\n instagram_url: event.instagram_url,\n meetup_url: event.meetup_url,\n tiktok_url: event.tiktok_url,\n event_type_ids: event.event_type_ids || [],\n artistIds: event.artist_ids || [],\n dance_style_ids: event.dance_style_ids || [],\n event_frequency_id: event.event_frequency_id || '',\n user_id: event.user_id || null,\n event_status_id: event.event_status_id || null,\n organizer_ids: event.organizer_ids || [],\n recurring_event_occurrences: [],\n recurring_event_attributes: {\n start_date: '',\n start_time: '',\n end_time: '',\n recurrence_pattern: '',\n num_occurrences: 0,\n re_timezone: '',\n spans_next_day: false,\n ordinal_occurrence: '',\n occurrence_day: '',\n },\n },\n validate: {\n name: (value) => (value ? null : 'Event name is required'),\n slug: (value) => (value ? null : 'Slug is required'),\n address: (value, values) =>\n values.online_event === 'true' ? null : value ? null : 'Address is required for in-person events',\n event_frequency_id: (value) => {\n // Skip for drafts\n if (isDraft) return null;\n\n // Check if a frequency is selected\n return value ? null : 'Event frequency is required';\n },\n description: (value) => {\n // If using the editor instance\n if (editor) {\n // Get plain text content (strips HTML tags)\n const plainText = editor.getText();\n\n // Check if it meets the minimum length requirement\n if (plainText.length < 20) {\n return 'Description must be at least 20 characters long';\n }\n }\n return null;\n },\n timezone: (value) => (value ? null : 'Timezone is required'),\n event_start_date: (value, values) => {\n // Skip validation for recurring events\n if (values.is_recurring === 'true') return null;\n\n // Regular validation\n return value ? null : 'Event start date is required';\n },\n\n event_start_time: (value, values) => {\n // Skip validation for recurring events\n if (values.is_recurring === 'true') return null;\n\n // Regular validation\n return value ? null : 'Event start time is required';\n },\n event_end_date: (value, values) => {\n if (!value || !values.event_start_date) return null;\n const start = new Date(values.event_start_date);\n const end = new Date(value);\n if (end < start) {\n return 'Event end date must be the same as or after the event start date';\n }\n return null;\n },\n event_end_time: (value, values) => {\n if (!value || !values.event_start_time || !values.event_start_date || !values.event_end_date) {\n return null;\n }\n\n const startDate = new Date(values.event_start_date);\n const endDate = new Date(values.event_end_date);\n\n const [startHour, startMinute] = values.event_start_time.split(':').map(Number);\n const [endHour, endMinute] = value.split(':').map(Number);\n\n // ✅ If both dates are the same, compare the time\n if (startDate.toDateString() === endDate.toDateString()) {\n if (endHour < startHour || (endHour === startHour && endMinute <= startMinute)) {\n return 'Event end time must be after event start time when the dates are the same';\n }\n } else {\n // ✅ If end date is before start date, show an error\n if (endDate < startDate) {\n return 'Event end date cannot be before event start date';\n }\n }\n\n return null;\n },\n event_type_ids: (value) =>\n Array.isArray(value) && value.length > 0 ? null : 'At least one event type is required',\n dance_style_ids: (value) =>\n Array.isArray(value) && value.length > 0 ? null : 'At least one dance style is required',\n website_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid website URL starting with http:// or https://';\n }\n return null;\n },\n ticket_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid passes URL starting with http:// or https://';\n }\n return null;\n },\n facebook_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid Facebook URL starting with http:// or https://';\n }\n return null;\n },\n instagram_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid Instagram URL starting with http:// or https://';\n }\n return null;\n },\n meetup_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid Meetup URL starting with http:// or https://';\n }\n return null;\n },\n tiktok_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid TikTok URL starting with http:// or https://';\n }\n return null;\n },\n event_image: (value, values) => {\n // Skip validation for drafts\n if (isDraft) return null;\n\n // For new events, require an image\n if (!event.id && !value && !croppedImage) {\n return 'Please upload an event image';\n }\n\n // For existing events, check if they already have an image\n if (event.id && !value && !croppedImage && !event.event_image_url) {\n return 'Please upload an event image';\n }\n\n return null;\n },\n },\n validateInputOnChange: true,\n });\n\n const DRAFT_STATUS_ID = 3;\n const isDraft = event.event_status_id === DRAFT_STATUS_ID;\n const [values, setValues] = useState(event);\n const startTimeRef = useRef(null);\n const endTimeRef = useRef(null);\n const startPickerControl = (\n startTimeRef.current?.showPicker()}>\n \n \n );\n const endPickerControl = (\n endTimeRef.current?.showPicker()}>\n \n \n );\n\n const isMobile = useMediaQuery('(max-width: 768px)');\n\n const handleStartTimeChange = (e: React.ChangeEvent) => {\n const timeValue = e.target.value; // e.g., \"18:09\"\n\n form.setFieldValue('event_start_time', timeValue); // ✅ Update form values\n\n setValues((prevValues) => ({\n ...prevValues,\n event_start_time: timeValue, // ✅ Ensure values are updated\n }));\n\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n };\n\n const handleEndTimeChange = (e: React.ChangeEvent) => {\n const timeValue = e.target.value; // e.g., \"16:09\"\n\n form.setFieldValue('event_end_time', timeValue); // ✅ Update form values\n\n setValues((prevValues) => ({\n ...prevValues,\n event_end_time: timeValue, // ✅ Ensure values are updated\n }));\n\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n };\n\n const TIMEZONE_OPTIONS = Object.entries(timezoneData).map(([value, label]) => ({\n value,\n label: `${label} (${value})`,\n }));\n\n function validateURL(input: string) {\n const urlPattern = /^(http:\\/\\/|https:\\/\\/)/i;\n return urlPattern.test(input);\n }\n\n const users = Array.isArray(propUsers) ? propUsers : [];\n const event_types = Array.isArray(propEventTypes) ? propEventTypes : [];\n const artists = Array.isArray(propArtists) ? propArtists : [];\n const dance_styles = Array.isArray(propDanceStyles) ? propDanceStyles : [];\n const event_frequencies = Array.isArray(propEventFrequencies) ? propEventFrequencies : [];\n const event_statuses = Array.isArray(propEventStatuses) ? propEventStatuses : [];\n\n const filteredOrganizers = useMemo(() => {\n const organizers = user?.roles?.includes('SuperAdmin')\n ? propOrganizers || []\n : (propOrganizers || []).filter((org) => user?.organizer_ids?.includes(org.id));\n\n // Sort organizers alphabetically by name\n return [...organizers].sort((a, b) => a.name.localeCompare(b.name));\n }, [propOrganizers, user]);\n\n const is_superadmin = user?.roles?.includes('SuperAdmin') || false;\n\n const frequencyOrder = ['One Time', 'Weekly', 'Every Two Weeks', 'Monthly', 'Annual'];\n\n const sortedEventFrequencies = event_frequencies.sort((a, b) => {\n return frequencyOrder.indexOf(a.name) - frequencyOrder.indexOf(b.name);\n });\n\n const [overlayVisible, setOverlayVisible] = useState(false);\n\n const sortedDanceStyles = dance_styles.sort((a, b) => a.name.localeCompare(b.name));\n\n const sortedEventTypes = event_types.sort((a, b) => a.name.localeCompare(b.name));\n\n const sortedOrganizers = filteredOrganizers.sort((a, b) => a.name.localeCompare(b.name));\n\n const theme = createTheme({\n primaryColor: 'orange',\n colors: {\n orange: [\n '#FEF5ED',\n '#FDE3D1',\n '#FCB693',\n '#FA9D73',\n '#F87F4D',\n '#F66A33',\n '#EA580C',\n '#C44B0A',\n '#9E3D08',\n '#783006',\n ],\n },\n fontFamily: 'Poppins, sans-serif',\n headings: { fontFamily: 'Poppins, sans-serif' },\n components: {\n InputLabel: {\n styles: (theme: { fontSizes: { sm: any } }) => ({\n label: {\n color: '#FFF7ED', // Ensure this color applies\n fontSize: theme.fontSizes.sm, // Optional: Adjust size\n fontWeight: 500, // Optional: Adjust weight\n },\n }),\n },\n Input: {\n styles: () => ({\n input: {\n backgroundColor: '#686868', // Correctly sets input background\n color: '#F2F2F2', // Ensures text inside the input is visible\n borderColor: '#787878', // Optional: Adjust border color\n '&::placeholder': {\n color: '#fff', // Optional: Lighten placeholder text\n },\n },\n }),\n },\n },\n });\n\n // Helper function to format GMT offset\n const formatOffset = (offsetSeconds: number) => {\n const hours = Math.floor(Math.abs(offsetSeconds) / 3600);\n const minutes = Math.floor((Math.abs(offsetSeconds) % 3600) / 60);\n const sign = offsetSeconds >= 0 ? '+' : '-';\n return `GMT${sign}${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;\n };\n\n useEffect(() => {\n const fetchTimezones = async () => {\n setIsLoadingTimezones(true);\n try {\n const apiKey = 'N2IE9BKU2EQR'; // Your TimeZoneDB API key\n const response = await fetch(`https://api.timezonedb.com/v2.1/list-time-zone?key=${apiKey}&format=json`);\n const data = await response.json();\n\n if (data.status === 'OK' && data.zones && Array.isArray(data.zones)) {\n // Format the timezone options\n const options = data.zones.map((zone: any) => ({\n value: zone.zoneName, // IANA timezone ID (e.g., \"America/Chicago\")\n label: `${zone.zoneName} (${formatOffset(zone.gmtOffset)})`, // Display name with GMT offset\n }));\n\n setTimezoneOptions(options);\n } else {\n console.error('Error fetching timezone list:', data.message || 'Unknown error');\n }\n } catch (error) {\n console.error('Failed to fetch timezones:', error);\n } finally {\n setIsLoadingTimezones(false);\n }\n };\n\n fetchTimezones();\n }, []);\n\n // Check slug when debounced value changes\n useEffect(() => {\n async function checkSlugAvailability() {\n if (!debouncedSlug || debouncedSlug.length < 3) {\n setSlugStatus('idle');\n return;\n }\n\n setSlugStatus('checking');\n\n try {\n const url = `/events/check_slug?slug=${encodeURIComponent(debouncedSlug)}`;\n const response = await fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (response.ok) {\n const data = await response.json();\n setSlugStatus(data.valid ? 'valid' : 'invalid');\n } else {\n setSlugStatus('idle');\n }\n } catch (error) {\n console.error('Error checking slug availability:', error);\n setSlugStatus('idle');\n }\n }\n\n checkSlugAvailability();\n }, [debouncedSlug]);\n\n useEffect(() => {\n setIsRecurring(form.values.is_recurring === 'true');\n\n if (form.values.event_start_date) {\n const date = dayjs(form.values.event_start_date);\n const ordinalIndex = Math.ceil(date.date() / 7) - 1;\n const calculatedOrdinal = ordinalOptions[Math.min(ordinalIndex, ordinalOptions.length - 1)];\n const calculatedDay = dayOptions[date.day()];\n\n setOrdinalOccurrence(calculatedOrdinal);\n setDayOfWeek(calculatedDay);\n }\n }, [form.values.is_recurring, form.values.event_start_date]);\n\n const handleAddressChange = (newAddress: string) => {\n form.setFieldValue('address', newAddress);\n setValues((prevValues) => ({\n ...prevValues,\n address: newAddress,\n }));\n };\n\n const [address, setAddress] = useState(form.values.address || '');\n const [timezone, setTimezone] = useState(form.values.timezone || '');\n\n const [timezoneOptions, setTimezoneOptions] = useState<{ value: string; label: string }[]>([]);\n const [isLoadingTimezones, setIsLoadingTimezones] = useState(true);\n const [isLoading, setIsLoading] = useState(false);\n\n const [croppedImage, setCroppedImage] = useState(null);\n\n const handleSubmit = async (\n submittedValues: typeof form.values & { event_image?: File },\n submitType: 'draft' | 'publish',\n ) => {\n setIsLoading(true);\n\n // Use event_status_id to determine if updating a draft event (status 3) or creating new\n const isEditing = form.values.event_status_id === 3;\n const url = isEditing ? `/events/${event.slug}?no_redirect=true` : '/events';\n const method = isEditing ? 'PATCH' : 'POST';\n\n // Run validation based on submitType\n if (submitType === 'draft') {\n if (!form.values.name || form.values.name.trim() === '') {\n showNotification({\n title: 'Validation Error',\n message: 'Event name is required even for drafts.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n });\n setIsLoading(false);\n setOverlayVisible(false);\n return;\n }\n } else {\n const validationErrors = form.validate();\n if (validationErrors.hasErrors) {\n Notifications.clean();\n Object.entries(validationErrors.errors).forEach(([label, message], index) => {\n const formattedLabel = label\n .replace(/_/g, ' ')\n .split(' ')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n setTimeout(() => {\n Notifications.show({\n title: `Error with ${formattedLabel}`,\n message: message,\n color: 'red',\n icon: ,\n autoClose: 8000,\n position: 'top-right',\n });\n }, index * 200);\n });\n setIsLoading(false);\n return;\n }\n }\n\n // If recurring event, set recurring attributes (merging new values)\n if (form.values.is_recurring === 'true' && form.values.recurring_event_occurrences?.length > 0) {\n const firstOccurrence = form.values.recurring_event_occurrences[0];\n form.values.recurring_event_attributes = {\n ...form.values.recurring_event_attributes,\n start_date: form.values.recurring_event_start_date || '',\n start_time: firstOccurrence?.start_time || '',\n end_time: firstOccurrence?.end_time || '',\n recurrence_pattern: form.values.recurrence_pattern || '',\n num_occurrences: parseInt(form.values.num_occurrences || '0', 10),\n re_timezone: form.values.timezone || '',\n spans_next_day: firstOccurrence?.spans_next_day || false,\n };\n\n if (form.values.recurrence_pattern === 'Monthly') {\n const startDate = new Date(form.values.recurring_event_start_date);\n const dayOfWeek = startDate.toLocaleString('en-US', { weekday: 'long' });\n const dayOfMonth = startDate.getDate();\n const weekNum = Math.ceil(dayOfMonth / 7);\n const ordinals = ['First', 'Second', 'Third', 'Fourth', 'Last'];\n const ordinal = ordinals[Math.min(weekNum - 1, 4)];\n form.values.recurring_event_attributes.occurrence_day = dayOfWeek;\n form.values.recurring_event_attributes.ordinal_occurrence = ordinal;\n }\n }\n\n // Build FormData merging new form values with existing event values if needed\n const formData = new FormData();\n\n // Set the submission type flag\n if (submitType === 'draft') {\n formData.append('save_draft', 'true');\n } else {\n formData.append('submit_for_approval', 'true');\n // If updating a draft for approval, explicitly change the event status to 2 (pending)\n if (isEditing) {\n formData.append('event[event_status_id]', '2');\n }\n }\n\n // Helper function to merge field value: use form value, else fallback to existing event value\n const mergeField = (field: keyof EventData): string =>\n form.values[field] || (event && event[field] ? event[field] : '');\n\n // Append date and time fields (merging existing values if not modified)\n const startDateStr = mergeField('event_start_date');\n const startTimeStr = mergeField('event_start_time');\n const endDateStr = mergeField('event_end_date');\n const endTimeStr = mergeField('event_end_time');\n if (submitType === 'publish' || (startDateStr && startTimeStr)) {\n if (startDateStr && startTimeStr) {\n const combinedStart = `${startDateStr.split('T')[0]}T${startTimeStr}:00Z`;\n formData.append('event[event_start_date]', combinedStart);\n }\n if (endDateStr && endTimeStr) {\n const combinedEnd = `${endDateStr.split('T')[0]}T${endTimeStr}:00Z`;\n formData.append('event[event_end_date]', combinedEnd);\n }\n }\n\n // Append timezone, using fallback if necessary\n if (Array.isArray(form.values.timezone)) {\n formData.append('event[timezone]', form.values.timezone[0] || mergeField('timezone'));\n } else {\n formData.append('event[timezone]', form.values.timezone || mergeField('timezone'));\n }\n\n // Append other required fields (merging with existing values)\n formData.append('event[name]', mergeField('name'));\n if (form.values.slug || event.slug) formData.append('event[slug]', form.values.slug || event.slug);\n formData.append('event[address]', mergeField('address'));\n\n // Append the description from the editor\n if (editor && typeof editor.getHTML === 'function') {\n formData.append('event[description]', editor.getHTML());\n }\n\n // Append images: only add if new image file is provided or if a croppedImage exists\n if (form.values.event_image) {\n formData.append('event[event_image]', form.values.event_image);\n }\n if (croppedImage) {\n formData.append('event[cropped_image]', croppedImage);\n }\n\n // Append optional URL fields\n ['website_url', 'ticket_url', 'facebook_url', 'instagram_url', 'meetup_url', 'tiktok_url'].forEach((field) => {\n const value = form.values[field] || (event && event[field]) || '';\n if (value) formData.append(`event[${field}]`, value);\n });\n\n // Append boolean fields\n formData.append('event[online_event]', form.values.online_event === 'true' ? 'true' : 'false');\n formData.append('event[is_recurring]', form.values.is_recurring === 'true' ? 'true' : 'false');\n formData.append('event[spans_next_day]', form.values.spans_next_day === 'true' ? 'true' : 'false');\n\n // Append custom occurrences if applicable\n const finalOccurrences: { date: string; start_time: string; end_time: string; spans_next_day: boolean }[] =\n form.values.recurring_event_occurrences || [];\n if (form.values.is_recurring === 'true' && finalOccurrences.length > 0) {\n formData.append('event[use_custom_occurrences]', 'true');\n finalOccurrences.forEach((occurrence, index) => {\n formData.append(`event[custom_occurrences][${index}][date]`, occurrence.date);\n formData.append(`event[custom_occurrences][${index}][start_time]`, occurrence.start_time);\n formData.append(`event[custom_occurrences][${index}][end_time]`, occurrence.end_time);\n formData.append(`event[custom_occurrences][${index}][spans_next_day]`, occurrence.spans_next_day.toString());\n });\n }\n\n // Append arrays for event types, dance styles, artists, and organizers\n if (Array.isArray(form.values.event_type_ids)) {\n form.values.event_type_ids.forEach((id) => formData.append('event[event_type_ids][]', id.toString()));\n }\n if (Array.isArray(form.values.dance_style_ids)) {\n form.values.dance_style_ids.forEach((id) => formData.append('event[dance_style_ids][]', id.toString()));\n }\n if (Array.isArray(form.values.artistIds)) {\n form.values.artistIds.forEach((id) => formData.append('event[artist_ids][]', id.toString()));\n }\n if (Array.isArray(form.values.organizer_ids)) {\n form.values.organizer_ids.forEach((id) => formData.append('event[organizer_ids][]', id.toString()));\n }\n\n // Append recurring event attributes if applicable\n if (form.values.is_recurring === 'true' && form.values.recurring_event_attributes) {\n Object.entries(form.values.recurring_event_attributes).forEach(([key, value]) => {\n formData.append(`event[recurring_event_attributes][${key}]`, value?.toString() || '');\n });\n }\n\n // Get CSRF token and send the request\n try {\n const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content;\n if (!csrfToken) {\n console.error('CSRF token not found');\n setIsLoading(false);\n setOverlayVisible(false);\n return;\n }\n\n const response = await fetch(url, {\n method,\n headers: {\n Accept: submitType === 'draft' ? 'text/html' : 'application/json',\n 'X-CSRF-Token': csrfToken,\n },\n credentials: 'include',\n body: formData,\n });\n\n if (response.ok) {\n let data = {};\n if (submitType !== 'draft') {\n try {\n data = await response.json();\n } catch (e) {\n console.log('Response was not JSON, continuing with redirect...');\n }\n }\n const eventSlug = data.slug || form.values.slug;\n let successMessage = '';\n if (submitType === 'draft') {\n successMessage = 'Event draft was saved successfully!';\n } else if (form.values.is_recurring === 'true') {\n const pattern = form.values.recurrence_pattern || 'regular';\n const occurrences = form.values.num_occurrences || form.values.recurring_event_occurrences?.length || '?';\n successMessage = `Successfully submitted ${pattern} recurring event with ${occurrences} occurrences!`;\n } else {\n successMessage = 'Event was submitted successfully!';\n }\n showNotification({\n title: submitType === 'draft' ? 'Draft Saved' : 'Submission Successful',\n message: successMessage,\n color: 'green',\n icon: ,\n autoClose: 6000,\n position: 'top-right',\n });\n\n // Redirect accordingly\n if (submitType === 'draft') {\n const username = user?.username;\n setTimeout(() => (window.location.href = `/users/${username}`), 1500);\n } else if (form.values.is_recurring === 'true' && eventSlug) {\n setTimeout(() => (window.location.href = `/re/${eventSlug}`), 1500);\n } else {\n setTimeout(() => (window.location.href = `/events/${eventSlug}`), 1500);\n }\n } else {\n setOverlayVisible(false);\n const contentType = response.headers.get('content-type');\n if (contentType && contentType.includes('application/json')) {\n try {\n const data = await response.json();\n console.log('Server error response:', data);\n if (data.errors) {\n Notifications.clean();\n Object.entries(data.errors).forEach(([field, message], index) => {\n const formattedField = field\n .replace(/_/g, ' ')\n .split(' ')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n form.setFieldError(field, Array.isArray(message) ? message[0] : message);\n setTimeout(() => {\n Notifications.show({\n title: `Error with ${formattedField}`,\n message: Array.isArray(message) ? message[0] : message,\n color: 'red',\n icon: ,\n autoClose: 8000,\n position: 'top-right',\n });\n }, index * 200);\n });\n } else if (data.error) {\n showNotification({\n title: 'Submission Failed',\n message: data.error,\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n } else {\n showNotification({\n title: 'Submission Failed',\n message: 'An error occurred. Please check all fields and try again.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n }\n } catch (e) {\n console.error('Error parsing JSON response:', e);\n showNotification({\n title: 'Submission Failed',\n message: 'Could not process server response.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n }\n } else {\n try {\n const textResponse = await response.text();\n console.log('Non-JSON response:', textResponse.substring(0, 200));\n showNotification({\n title: 'Submission Failed',\n message: `Server returned status ${response.status}: ${response.statusText}`,\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n } catch (e) {\n console.error('Error reading response text:', e);\n showNotification({\n title: 'Submission Failed',\n message: 'Could not read server response.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n }\n }\n }\n } catch (error) {\n setOverlayVisible(false);\n showNotification({\n title: 'Unexpected Error',\n message: 'An unexpected error occurred. Please try again.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n console.error('Error creating/updating event:', error);\n } finally {\n setIsLoading(false);\n }\n };\n\n const editor = useEditor({\n extensions: [\n StarterKit,\n Highlight,\n Underline,\n TextAlign.configure({ types: ['heading', 'paragraph'] }),\n Heading.configure({ levels: [1, 2, 3] }),\n Link.configure({ openOnClick: true }),\n ],\n content: form.values.description,\n onUpdate: ({ editor }) => {\n const html = editor.getHTML();\n\n form.setFieldValue('description', html);\n },\n });\n\n const statusMapping: Record = {\n 1: { status: 'Active', color: 'green', icon: },\n 2: { status: 'Pending', color: 'yellow', icon: },\n 3: { status: 'Draft', color: 'blue', icon: },\n };\n\n const eventStatus =\n event.event_status_id && statusMapping[event.event_status_id]\n ? statusMapping[event.event_status_id]\n : { status: 'None', color: 'gray', icon: };\n\n return (\n \n \n \n \n {event.event_status_id ? (\n \n ) : null}\n \n Create New Event\n \n
      \n \n \n \n \n \n Event Host & Name\n \n \n \n 0 ? '' : 'Select event organizers'\n }\n name=\"organizer_ids\"\n data={filteredOrganizers.map((org) => ({\n value: org.id.toString(),\n label: org.name,\n }))}\n value={(form.values.organizer_ids || []).map((id) => id.toString())}\n onChange={(values) => {\n const numericValues = Array.isArray(values) ? values.map((v) => Number(v)) : [];\n form.setFieldValue('organizer_ids', numericValues);\n }}\n searchable\n clearable\n mt=\"md\"\n styles={{ label: { color: '#FFF7ED' } }}\n />\n\n \n\n ) => setSlug(e.target.value),\n })}\n mt=\"md\"\n required\n styles={{ label: { color: '#FFF7ED' } }}\n />\n {slugStatus === 'checking' && (\n \n Checking availability...\n \n )}\n {slugStatus === 'valid' && (\n \n Slug is available.\n \n )}\n {slugStatus === 'invalid' && (\n \n Slug is already taken.\n \n )}\n \n \n \n\n \n \n \n \n \n Location Info\n \n \n \n \n Is this an online event or in-person event?\n \n \n\n {form.values.online_event !== 'true' && (\n {\n setAddress(newAddress);\n form.setFieldValue('address', newAddress);\n }}\n onTimezoneSelect={(newTimezone) => {\n setTimezone(newTimezone);\n form.setFieldValue('timezone', newTimezone);\n }}\n timezoneValue={timezone}\n />\n )}\n \n \n \n\n \n \n \n \n \n Date & Time Info\n \n \n \n \n\n {isRecurring && }\n\n
      \n \n {\n // If the value is just a date string (YYYY-MM-DD), parse it properly in local timezone\n if (\n form.values.event_start_date.length === 10 &&\n form.values.event_start_date.includes('-')\n ) {\n // Create date at noon to avoid any timezone boundary issues\n const [year, month, day] = form.values.event_start_date.split('-').map(Number);\n const date = new Date(year, month - 1, day, 12, 0, 0);\n\n return date;\n } else {\n // Otherwise, use the standard Date constructor\n const date = new Date(form.values.event_start_date);\n return date;\n }\n })()\n : null\n }\n onChange={(date) => {\n if (date) {\n const localDate = new Date(date);\n localDate.setHours(0, 0, 0, 0);\n\n // Get the date components directly from the local date object\n const year = localDate.getFullYear();\n const month = String(localDate.getMonth() + 1).padStart(2, '0');\n const day = String(localDate.getDate()).padStart(2, '0');\n const dateString = `${year}-${month}-${day}`;\n\n // Store only the date portion, without time information\n form.setFieldValue('event_start_date', dateString);\n\n // Also copy the same date to the end date\n form.setFieldValue('event_end_date', dateString);\n } else {\n form.setFieldValue('event_start_date', '');\n // Optionally clear end date when start date is cleared\n // form.setFieldValue('event_end_date', '');\n }\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n }}\n required={!isDraft}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n\n {\n handleStartTimeChange(e);\n\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n }}\n required={!isDraft}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n \n\n \n {\n // If the value is just a date string (YYYY-MM-DD), parse it properly in local timezone\n if (\n form.values.event_end_date.length === 10 &&\n form.values.event_end_date.includes('-')\n ) {\n // Create date at noon to avoid any timezone boundary issues\n const [year, month, day] = form.values.event_end_date.split('-').map(Number);\n const date = new Date(year, month - 1, day, 12, 0, 0);\n\n return date;\n } else {\n // Otherwise, use the standard Date constructor\n const date = new Date(form.values.event_end_date);\n return date;\n }\n })()\n : null\n }\n onChange={(date) => {\n if (date) {\n const localDate = new Date(date);\n localDate.setHours(0, 0, 0, 0);\n\n // Get the date components directly from the local date object\n const year = localDate.getFullYear();\n const month = String(localDate.getMonth() + 1).padStart(2, '0');\n const day = String(localDate.getDate()).padStart(2, '0');\n const dateString = `${year}-${month}-${day}`;\n\n form.setFieldValue('event_end_date', dateString);\n } else {\n form.setFieldValue('event_end_date', '');\n }\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n }}\n required={!isDraft}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n {\n handleEndTimeChange(e);\n\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n }}\n required={!isDraft}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n \n
      \n\n {(form.errors.event_end_date || form.errors.event_end_time) && (\n }>\n {form.errors.event_end_date &&
      {form.errors.event_end_date}
      }\n {form.errors.event_end_time &&
      {form.errors.event_end_time}
      }\n
      \n )}\n
      \n
      \n
      \n\n \n \n \n \n \n Event Details\n \n \n \n \n\n 0\n ? ''\n : 'Choose your event types'\n }\n data={sortedEventTypes.map((style) => ({\n value: style.id.toString(),\n label: style.name,\n }))}\n value={\n // Ensure we always have an array and convert numbers to strings\n (Array.isArray(form.values.event_type_ids) ? form.values.event_type_ids : []).map((id) =>\n id.toString(),\n )\n }\n onChange={(values) => {\n // Convert the selected string IDs back to numbers\n const numericValues = values.map(Number);\n form.setFieldValue('event_type_ids', numericValues);\n }}\n searchable\n clearable\n required={!isDraft}\n />\n\n 0 ? '' : 'Choose dance styles'\n }\n data={sortedDanceStyles.map((style) => ({\n value: style.id.toString(),\n label: style.name,\n }))}\n value={(Array.isArray(form.values.dance_style_ids) ? form.values.dance_style_ids : []).map((id) =>\n id.toString(),\n )}\n onChange={(values) => {\n // Convert the selected string IDs back to numbers\n const numericValues = values.map(Number);\n form.setFieldValue('dance_style_ids', numericValues);\n }}\n searchable\n clearable\n mt=\"lg\"\n required={!isDraft}\n />\n\n ({\n value: freq.id.toString(),\n label: freq.name,\n }))}\n value={form.values.event_frequency_id ? form.values.event_frequency_id.toString() : null}\n onChange={(value) => {\n form.setFieldValue('event_frequency_id', value ? Number(value) : null);\n // Validate this field immediately after change\n form.validateField('event_frequency_id');\n }}\n onBlur={() => form.validateField('event_frequency_id')}\n error={form.errors.event_frequency_id}\n searchable\n clearable\n mt=\"lg\"\n mb=\"xl\"\n required={!isDraft}\n />\n\n \n Event Description\n \n {editor && (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n )}\n \n \n \n\n \n \n \n \n \n Artists\n \n \n \n 0 ? '' : 'Choose artists'}\n styles={{\n label: { color: '#FFF7ED', fontSize: '16px' }, // Label font size\n input: { fontSize: '16px' }, // Input field font size\n dropdown: { fontSize: '16px' }, // Dropdown items font size\n }}\n data={artists.map((artist) => ({\n value: artist.id.toString(), // value as string\n label: artist.name,\n }))}\n value={(form.values.artistIds || []).map(String)}\n onChange={(values) => {\n const numericValues = Array.isArray(values) ? values.map(Number) : [];\n form.setFieldValue('artistIds', numericValues);\n }}\n searchable\n clearable\n />\n\n {/* Display selected artist avatars below */}\n {form.values.artistIds.length > 0 && (\n \n \n {form.values.artistIds.map((id: Key | null | undefined) => {\n const artist = artists.find((a) => a.id === id);\n return artist ? (\n \n ) : null;\n })}\n \n \n )}\n \n \n \n\n \n \n \n \n \n Links\n \n \n \n \n\n \n\n \n\n \n\n \n\n \n \n \n \n\n {/* Example error display */}\n {errors && Object.keys(errors).length > 0 && (\n \n {Object.entries(errors).map(([field, messages]) => (\n
      \n {field}: {messages.join(', ')}\n
      \n ))}\n
      \n )}\n\n \n handleSubmit(form.values, 'draft')}\n >\n Save as Draft\n \n\n handleSubmit(form.values, 'publish')}\n >\n {form.values.is_recurring === 'true'\n ? 'Submit Recurring Event For Approval'\n : 'Submit Event For Approval'}\n \n \n
      \n
      \n
      \n
      \n );\n}\n","import React, { useState } from 'react';\nimport { Card, Button, Modal, Text, Group } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { Inertia } from '@inertiajs/inertia';\n\nconst DangerZoneCard = ({ eventId, eventName }) => {\n const [opened, setOpened] = useState(false);\n const [loading, setLoading] = useState(false);\n\n // Grab CSRF token from meta tag\n const csrfToken = document.querySelector(\"meta[name='csrf-token']\")?.getAttribute('content');\n\n const handleDelete = async () => {\n setLoading(true);\n try {\n const response = await fetch(`/events/${eventId}`, {\n method: 'DELETE',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-CSRF-Token': csrfToken || '',\n },\n credentials: 'include',\n });\n\n if (!response.ok) {\n throw new Error('Deletion failed.');\n }\n\n // Assume the server returns a JSON with a message and redirect URL.\n const data = await response.json();\n\n showNotification({\n title: 'Event Deleted',\n message: data.message || 'Event has been successfully deleted.',\n color: 'green',\n });\n\n // Redirect using Inertia to the user profile page.\n Inertia.visit(data.redirect || '/users/profile');\n } catch (error) {\n showNotification({\n title: 'Deletion Error',\n message: error.message || 'An error occurred while deleting the event.',\n color: 'red',\n });\n } finally {\n setLoading(false);\n setOpened(false);\n }\n };\n\n return (\n \n \n Danger Zone\n \n \n This will delete the event {eventName}.\n \n \n\n setOpened(false)}\n title=\"Confirm Delete\"\n centered\n styles={{\n header: { backgroundColor: '#ffcccc' }, // light red header\n content: { backgroundColor: '#ffe5e5' }, // light red background\n }}\n >\n \n Are you sure you want to delete the event {eventName}? This action cannot be undone.\n \n \n \n \n \n \n \n );\n};\n\nexport default DangerZoneCard;\n","import { getDefaultOptions } from 'date-fns';\n/**\n * Returns the formatted time zone name of the provided `timeZone` or the current\n * system time zone if omitted, accounting for DST according to the UTC value of\n * the date.\n */\nexport function tzIntlTimeZoneName(length, date, options) {\n const defaultOptions = getDefaultOptions();\n const dtf = getDTF(length, options.timeZone, options.locale ?? defaultOptions.locale);\n return 'formatToParts' in dtf ? partsTimeZone(dtf, date) : hackyTimeZone(dtf, date);\n}\nfunction partsTimeZone(dtf, date) {\n const formatted = dtf.formatToParts(date);\n for (let i = formatted.length - 1; i >= 0; --i) {\n if (formatted[i].type === 'timeZoneName') {\n return formatted[i].value;\n }\n }\n return undefined;\n}\nfunction hackyTimeZone(dtf, date) {\n const formatted = dtf.format(date).replace(/\\u200E/g, '');\n const tzNameMatch = / [\\w-+ ]+$/.exec(formatted);\n return tzNameMatch ? tzNameMatch[0].substr(1) : '';\n}\n// If a locale has been provided `en-US` is used as a fallback in case it is an\n// invalid locale, otherwise the locale is left undefined to use the system locale.\nfunction getDTF(length, timeZone, locale) {\n return new Intl.DateTimeFormat(locale ? [locale.code, 'en-US'] : undefined, {\n timeZone: timeZone,\n timeZoneName: length,\n });\n}\n","/**\n * Returns the [year, month, day, hour, minute, seconds] tokens of the provided\n * `date` as it will be rendered in the `timeZone`.\n */\nexport function tzTokenizeDate(date, timeZone) {\n const dtf = getDateTimeFormat(timeZone);\n return 'formatToParts' in dtf ? partsOffset(dtf, date) : hackyOffset(dtf, date);\n}\nconst typeToPos = {\n year: 0,\n month: 1,\n day: 2,\n hour: 3,\n minute: 4,\n second: 5,\n};\nfunction partsOffset(dtf, date) {\n try {\n const formatted = dtf.formatToParts(date);\n const filled = [];\n for (let i = 0; i < formatted.length; i++) {\n const pos = typeToPos[formatted[i].type];\n if (pos !== undefined) {\n filled[pos] = parseInt(formatted[i].value, 10);\n }\n }\n return filled;\n }\n catch (error) {\n if (error instanceof RangeError) {\n return [NaN];\n }\n throw error;\n }\n}\nfunction hackyOffset(dtf, date) {\n const formatted = dtf.format(date);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const parsed = /(\\d+)\\/(\\d+)\\/(\\d+),? (\\d+):(\\d+):(\\d+)/.exec(formatted);\n // const [, fMonth, fDay, fYear, fHour, fMinute, fSecond] = parsed\n // return [fYear, fMonth, fDay, fHour, fMinute, fSecond]\n return [\n parseInt(parsed[3], 10),\n parseInt(parsed[1], 10),\n parseInt(parsed[2], 10),\n parseInt(parsed[4], 10),\n parseInt(parsed[5], 10),\n parseInt(parsed[6], 10),\n ];\n}\n// Get a cached Intl.DateTimeFormat instance for the IANA `timeZone`. This can be used\n// to get deterministic local date/time output according to the `en-US` locale which\n// can be used to extract local time parts as necessary.\nconst dtfCache = {};\n// New browsers use `hourCycle`, IE and Chrome <73 does not support it and uses `hour12`\nconst testDateFormatted = new Intl.DateTimeFormat('en-US', {\n hourCycle: 'h23',\n timeZone: 'America/New_York',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n}).format(new Date('2014-06-25T04:00:00.123Z'));\nconst hourCycleSupported = testDateFormatted === '06/25/2014, 00:00:00' ||\n testDateFormatted === '‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00';\nfunction getDateTimeFormat(timeZone) {\n if (!dtfCache[timeZone]) {\n dtfCache[timeZone] = hourCycleSupported\n ? new Intl.DateTimeFormat('en-US', {\n hourCycle: 'h23',\n timeZone: timeZone,\n year: 'numeric',\n month: 'numeric',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n : new Intl.DateTimeFormat('en-US', {\n hour12: false,\n timeZone: timeZone,\n year: 'numeric',\n month: 'numeric',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n });\n }\n return dtfCache[timeZone];\n}\n","/**\n * Use instead of `new Date(Date.UTC(...))` to support years below 100 which doesn't work\n * otherwise due to the nature of the\n * [`Date` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years.\n *\n * For `Date.UTC(...)`, use `newDateUTC(...).getTime()`.\n */\nexport function newDateUTC(fullYear, month, day, hour, minute, second, millisecond) {\n const utcDate = new Date(0);\n utcDate.setUTCFullYear(fullYear, month, day);\n utcDate.setUTCHours(hour, minute, second, millisecond);\n return utcDate;\n}\n","import { tzTokenizeDate } from '../tzTokenizeDate/index.js';\nimport { newDateUTC } from '../newDateUTC/index.js';\nconst MILLISECONDS_IN_HOUR = 3600000;\nconst MILLISECONDS_IN_MINUTE = 60000;\nconst patterns = {\n timezone: /([Z+-].*)$/,\n timezoneZ: /^(Z)$/,\n timezoneHH: /^([+-]\\d{2})$/,\n timezoneHHMM: /^([+-])(\\d{2}):?(\\d{2})$/,\n};\n// Parse constious time zone offset formats to an offset in milliseconds\nexport function tzParseTimezone(timezoneString, date, isUtcDate) {\n // Empty string\n if (!timezoneString) {\n return 0;\n }\n // Z\n let token = patterns.timezoneZ.exec(timezoneString);\n if (token) {\n return 0;\n }\n let hours;\n let absoluteOffset;\n // ±hh\n token = patterns.timezoneHH.exec(timezoneString);\n if (token) {\n hours = parseInt(token[1], 10);\n if (!validateTimezone(hours)) {\n return NaN;\n }\n return -(hours * MILLISECONDS_IN_HOUR);\n }\n // ±hh:mm or ±hhmm\n token = patterns.timezoneHHMM.exec(timezoneString);\n if (token) {\n hours = parseInt(token[2], 10);\n const minutes = parseInt(token[3], 10);\n if (!validateTimezone(hours, minutes)) {\n return NaN;\n }\n absoluteOffset = Math.abs(hours) * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE;\n return token[1] === '+' ? -absoluteOffset : absoluteOffset;\n }\n // IANA time zone\n if (isValidTimezoneIANAString(timezoneString)) {\n date = new Date(date || Date.now());\n const utcDate = isUtcDate ? date : toUtcDate(date);\n const offset = calcOffset(utcDate, timezoneString);\n const fixedOffset = isUtcDate ? offset : fixOffset(date, offset, timezoneString);\n return -fixedOffset;\n }\n return NaN;\n}\nfunction toUtcDate(date) {\n return newDateUTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());\n}\nfunction calcOffset(date, timezoneString) {\n const tokens = tzTokenizeDate(date, timezoneString);\n // ms dropped because it's not provided by tzTokenizeDate\n const asUTC = newDateUTC(tokens[0], tokens[1] - 1, tokens[2], tokens[3] % 24, tokens[4], tokens[5], 0).getTime();\n let asTS = date.getTime();\n const over = asTS % 1000;\n asTS -= over >= 0 ? over : 1000 + over;\n return asUTC - asTS;\n}\nfunction fixOffset(date, offset, timezoneString) {\n const localTS = date.getTime();\n // Our UTC time is just a guess because our offset is just a guess\n let utcGuess = localTS - offset;\n // Test whether the zone matches the offset for this ts\n const o2 = calcOffset(new Date(utcGuess), timezoneString);\n // If so, offset didn't change, and we're done\n if (offset === o2) {\n return offset;\n }\n // If not, change the ts by the difference in the offset\n utcGuess -= o2 - offset;\n // If that gives us the local time we want, we're done\n const o3 = calcOffset(new Date(utcGuess), timezoneString);\n if (o2 === o3) {\n return o2;\n }\n // If it's different, we're in a hole time. The offset has changed, but we don't adjust the time\n return Math.max(o2, o3);\n}\nfunction validateTimezone(hours, minutes) {\n return -23 <= hours && hours <= 23 && (minutes == null || (0 <= minutes && minutes <= 59));\n}\nconst validIANATimezoneCache = {};\nfunction isValidTimezoneIANAString(timeZoneString) {\n if (validIANATimezoneCache[timeZoneString])\n return true;\n try {\n new Intl.DateTimeFormat(undefined, { timeZone: timeZoneString });\n validIANATimezoneCache[timeZoneString] = true;\n return true;\n }\n catch (error) {\n return false;\n }\n}\n","import { tzIntlTimeZoneName } from '../../_lib/tzIntlTimeZoneName/index.js';\nimport { tzParseTimezone } from '../../_lib/tzParseTimezone/index.js';\nconst MILLISECONDS_IN_MINUTE = 60 * 1000;\nexport const formatters = {\n // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)\n X: function (date, token, options) {\n const timezoneOffset = getTimeZoneOffset(options.timeZone, date);\n if (timezoneOffset === 0) {\n return 'Z';\n }\n switch (token) {\n // Hours and optional minutes\n case 'X':\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n // Hours, minutes and optional seconds without `:` delimeter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XX`\n case 'XXXX':\n case 'XX': // Hours and minutes without `:` delimeter\n return formatTimezone(timezoneOffset);\n // Hours, minutes and optional seconds with `:` delimeter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XXX`\n case 'XXXXX':\n case 'XXX': // Hours and minutes with `:` delimeter\n default:\n return formatTimezone(timezoneOffset, ':');\n }\n },\n // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)\n x: function (date, token, options) {\n const timezoneOffset = getTimeZoneOffset(options.timeZone, date);\n switch (token) {\n // Hours and optional minutes\n case 'x':\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n // Hours, minutes and optional seconds without `:` delimeter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xx`\n case 'xxxx':\n case 'xx': // Hours and minutes without `:` delimeter\n return formatTimezone(timezoneOffset);\n // Hours, minutes and optional seconds with `:` delimeter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xxx`\n case 'xxxxx':\n case 'xxx': // Hours and minutes with `:` delimeter\n default:\n return formatTimezone(timezoneOffset, ':');\n }\n },\n // Timezone (GMT)\n O: function (date, token, options) {\n const timezoneOffset = getTimeZoneOffset(options.timeZone, date);\n switch (token) {\n // Short\n case 'O':\n case 'OO':\n case 'OOO':\n return 'GMT' + formatTimezoneShort(timezoneOffset, ':');\n // Long\n case 'OOOO':\n default:\n return 'GMT' + formatTimezone(timezoneOffset, ':');\n }\n },\n // Timezone (specific non-location)\n z: function (date, token, options) {\n switch (token) {\n // Short\n case 'z':\n case 'zz':\n case 'zzz':\n return tzIntlTimeZoneName('short', date, options);\n // Long\n case 'zzzz':\n default:\n return tzIntlTimeZoneName('long', date, options);\n }\n },\n};\nfunction getTimeZoneOffset(timeZone, originalDate) {\n const timeZoneOffset = timeZone\n ? tzParseTimezone(timeZone, originalDate, true) / MILLISECONDS_IN_MINUTE\n : originalDate?.getTimezoneOffset() ?? 0;\n if (Number.isNaN(timeZoneOffset)) {\n throw new RangeError('Invalid time zone specified: ' + timeZone);\n }\n return timeZoneOffset;\n}\nfunction addLeadingZeros(number, targetLength) {\n const sign = number < 0 ? '-' : '';\n let output = Math.abs(number).toString();\n while (output.length < targetLength) {\n output = '0' + output;\n }\n return sign + output;\n}\nfunction formatTimezone(offset, delimiter = '') {\n const sign = offset > 0 ? '-' : '+';\n const absOffset = Math.abs(offset);\n const hours = addLeadingZeros(Math.floor(absOffset / 60), 2);\n const minutes = addLeadingZeros(Math.floor(absOffset % 60), 2);\n return sign + hours + delimiter + minutes;\n}\nfunction formatTimezoneWithOptionalMinutes(offset, delimiter) {\n if (offset % 60 === 0) {\n const sign = offset > 0 ? '-' : '+';\n return sign + addLeadingZeros(Math.abs(offset) / 60, 2);\n }\n return formatTimezone(offset, delimiter);\n}\nfunction formatTimezoneShort(offset, delimiter = '') {\n const sign = offset > 0 ? '-' : '+';\n const absOffset = Math.abs(offset);\n const hours = Math.floor(absOffset / 60);\n const minutes = absOffset % 60;\n if (minutes === 0) {\n return sign + String(hours);\n }\n return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);\n}\n","/**\n * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.\n * They usually appear for dates that denote time before the timezones were introduced\n * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891\n * and GMT+01:00:00 after that date)\n *\n * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,\n * which would lead to incorrect calculations.\n *\n * This function returns the timezone offset in milliseconds that takes seconds in account.\n */\nexport function getTimezoneOffsetInMilliseconds(date) {\n const utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));\n utcDate.setUTCFullYear(date.getFullYear());\n return +date - +utcDate;\n}\n","/** Regex to identify the presence of a time zone specifier in a date string */\nexport const tzPattern = /(Z|[+-]\\d{2}(?::?\\d{2})?| UTC| [a-zA-Z]+\\/[a-zA-Z_]+(?:\\/[a-zA-Z_]+)?)$/;\n","import { getTimezoneOffsetInMilliseconds } from '../_lib/getTimezoneOffsetInMilliseconds/index.js';\nimport { tzParseTimezone } from '../_lib/tzParseTimezone/index.js';\nimport { tzPattern } from '../_lib/tzPattern/index.js';\nconst MILLISECONDS_IN_HOUR = 3600000;\nconst MILLISECONDS_IN_MINUTE = 60000;\nconst DEFAULT_ADDITIONAL_DIGITS = 2;\nconst patterns = {\n dateTimePattern: /^([0-9W+-]+)(T| )(.*)/,\n datePattern: /^([0-9W+-]+)(.*)/,\n plainTime: /:/,\n // year tokens\n YY: /^(\\d{2})$/,\n YYY: [\n /^([+-]\\d{2})$/, // 0 additional digits\n /^([+-]\\d{3})$/, // 1 additional digit\n /^([+-]\\d{4})$/, // 2 additional digits\n ],\n YYYY: /^(\\d{4})/,\n YYYYY: [\n /^([+-]\\d{4})/, // 0 additional digits\n /^([+-]\\d{5})/, // 1 additional digit\n /^([+-]\\d{6})/, // 2 additional digits\n ],\n // date tokens\n MM: /^-(\\d{2})$/,\n DDD: /^-?(\\d{3})$/,\n MMDD: /^-?(\\d{2})-?(\\d{2})$/,\n Www: /^-?W(\\d{2})$/,\n WwwD: /^-?W(\\d{2})-?(\\d{1})$/,\n HH: /^(\\d{2}([.,]\\d*)?)$/,\n HHMM: /^(\\d{2}):?(\\d{2}([.,]\\d*)?)$/,\n HHMMSS: /^(\\d{2}):?(\\d{2}):?(\\d{2}([.,]\\d*)?)$/,\n // time zone tokens (to identify the presence of a tz)\n timeZone: tzPattern,\n};\n/**\n * @name toDate\n * @category Common Helpers\n * @summary Convert the given argument to an instance of Date.\n *\n * @description\n * Convert the given argument to an instance of Date.\n *\n * If the argument is an instance of Date, the function returns its clone.\n *\n * If the argument is a number, it is treated as a timestamp.\n *\n * If an argument is a string, the function tries to parse it.\n * Function accepts complete ISO 8601 formats as well as partial implementations.\n * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601\n * If the function cannot parse the string or the values are invalid, it returns Invalid Date.\n *\n * If the argument is none of the above, the function returns Invalid Date.\n *\n * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.\n * All *date-fns* functions will throw `RangeError` if `options.additionalDigits` is not 0, 1, 2 or undefined.\n *\n * @param argument the value to convert\n * @param options the object with options. See [Options]{@link https://date-fns.org/docs/Options}\n * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format\n * @param {string} [options.timeZone=''] - used to specify the IANA time zone offset of a date String.\n *\n * @returns the parsed date in the local time zone\n * @throws {TypeError} 1 argument required\n * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2\n *\n * @example\n * // Convert string '2014-02-11T11:30:30' to date:\n * const result = toDate('2014-02-11T11:30:30')\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert string '+02014101' to date,\n * // if the additional number of digits in the extended year format is 1:\n * const result = toDate('+02014101', {additionalDigits: 1})\n * //=> Fri Apr 11 2014 00:00:00\n */\nexport function toDate(argument, options = {}) {\n if (arguments.length < 1) {\n throw new TypeError('1 argument required, but only ' + arguments.length + ' present');\n }\n if (argument === null) {\n return new Date(NaN);\n }\n const additionalDigits = options.additionalDigits == null ? DEFAULT_ADDITIONAL_DIGITS : Number(options.additionalDigits);\n if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {\n throw new RangeError('additionalDigits must be 0, 1 or 2');\n }\n // Clone the date\n if (argument instanceof Date ||\n (typeof argument === 'object' && Object.prototype.toString.call(argument) === '[object Date]')) {\n // Prevent the date to lose the milliseconds when passed to new Date() in IE10\n return new Date(argument.getTime());\n }\n else if (typeof argument === 'number' ||\n Object.prototype.toString.call(argument) === '[object Number]') {\n return new Date(argument);\n }\n else if (!(Object.prototype.toString.call(argument) === '[object String]')) {\n return new Date(NaN);\n }\n const dateStrings = splitDateString(argument);\n const { year, restDateString } = parseYear(dateStrings.date, additionalDigits);\n const date = parseDate(restDateString, year);\n if (date === null || isNaN(date.getTime())) {\n return new Date(NaN);\n }\n if (date) {\n const timestamp = date.getTime();\n let time = 0;\n let offset;\n if (dateStrings.time) {\n time = parseTime(dateStrings.time);\n if (time === null || isNaN(time)) {\n return new Date(NaN);\n }\n }\n if (dateStrings.timeZone || options.timeZone) {\n offset = tzParseTimezone(dateStrings.timeZone || options.timeZone, new Date(timestamp + time));\n if (isNaN(offset)) {\n return new Date(NaN);\n }\n }\n else {\n // get offset accurate to hour in time zones that change offset\n offset = getTimezoneOffsetInMilliseconds(new Date(timestamp + time));\n offset = getTimezoneOffsetInMilliseconds(new Date(timestamp + time + offset));\n }\n return new Date(timestamp + time + offset);\n }\n else {\n return new Date(NaN);\n }\n}\nfunction splitDateString(dateString) {\n const dateStrings = {};\n let parts = patterns.dateTimePattern.exec(dateString);\n let timeString;\n if (!parts) {\n parts = patterns.datePattern.exec(dateString);\n if (parts) {\n dateStrings.date = parts[1];\n timeString = parts[2];\n }\n else {\n dateStrings.date = null;\n timeString = dateString;\n }\n }\n else {\n dateStrings.date = parts[1];\n timeString = parts[3];\n }\n if (timeString) {\n const token = patterns.timeZone.exec(timeString);\n if (token) {\n dateStrings.time = timeString.replace(token[1], '');\n dateStrings.timeZone = token[1].trim();\n }\n else {\n dateStrings.time = timeString;\n }\n }\n return dateStrings;\n}\nfunction parseYear(dateString, additionalDigits) {\n if (dateString) {\n const patternYYY = patterns.YYY[additionalDigits];\n const patternYYYYY = patterns.YYYYY[additionalDigits];\n // YYYY or ±YYYYY\n let token = patterns.YYYY.exec(dateString) || patternYYYYY.exec(dateString);\n if (token) {\n const yearString = token[1];\n return {\n year: parseInt(yearString, 10),\n restDateString: dateString.slice(yearString.length),\n };\n }\n // YY or ±YYY\n token = patterns.YY.exec(dateString) || patternYYY.exec(dateString);\n if (token) {\n const centuryString = token[1];\n return {\n year: parseInt(centuryString, 10) * 100,\n restDateString: dateString.slice(centuryString.length),\n };\n }\n }\n // Invalid ISO-formatted year\n return {\n year: null,\n };\n}\nfunction parseDate(dateString, year) {\n // Invalid ISO-formatted year\n if (year === null) {\n return null;\n }\n let date;\n let month;\n let week;\n // YYYY\n if (!dateString || !dateString.length) {\n date = new Date(0);\n date.setUTCFullYear(year);\n return date;\n }\n // YYYY-MM\n let token = patterns.MM.exec(dateString);\n if (token) {\n date = new Date(0);\n month = parseInt(token[1], 10) - 1;\n if (!validateDate(year, month)) {\n return new Date(NaN);\n }\n date.setUTCFullYear(year, month);\n return date;\n }\n // YYYY-DDD or YYYYDDD\n token = patterns.DDD.exec(dateString);\n if (token) {\n date = new Date(0);\n const dayOfYear = parseInt(token[1], 10);\n if (!validateDayOfYearDate(year, dayOfYear)) {\n return new Date(NaN);\n }\n date.setUTCFullYear(year, 0, dayOfYear);\n return date;\n }\n // yyyy-MM-dd or YYYYMMDD\n token = patterns.MMDD.exec(dateString);\n if (token) {\n date = new Date(0);\n month = parseInt(token[1], 10) - 1;\n const day = parseInt(token[2], 10);\n if (!validateDate(year, month, day)) {\n return new Date(NaN);\n }\n date.setUTCFullYear(year, month, day);\n return date;\n }\n // YYYY-Www or YYYYWww\n token = patterns.Www.exec(dateString);\n if (token) {\n week = parseInt(token[1], 10) - 1;\n if (!validateWeekDate(week)) {\n return new Date(NaN);\n }\n return dayOfISOWeekYear(year, week);\n }\n // YYYY-Www-D or YYYYWwwD\n token = patterns.WwwD.exec(dateString);\n if (token) {\n week = parseInt(token[1], 10) - 1;\n const dayOfWeek = parseInt(token[2], 10) - 1;\n if (!validateWeekDate(week, dayOfWeek)) {\n return new Date(NaN);\n }\n return dayOfISOWeekYear(year, week, dayOfWeek);\n }\n // Invalid ISO-formatted date\n return null;\n}\nfunction parseTime(timeString) {\n let hours;\n let minutes;\n // hh\n let token = patterns.HH.exec(timeString);\n if (token) {\n hours = parseFloat(token[1].replace(',', '.'));\n if (!validateTime(hours)) {\n return NaN;\n }\n return (hours % 24) * MILLISECONDS_IN_HOUR;\n }\n // hh:mm or hhmm\n token = patterns.HHMM.exec(timeString);\n if (token) {\n hours = parseInt(token[1], 10);\n minutes = parseFloat(token[2].replace(',', '.'));\n if (!validateTime(hours, minutes)) {\n return NaN;\n }\n return (hours % 24) * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE;\n }\n // hh:mm:ss or hhmmss\n token = patterns.HHMMSS.exec(timeString);\n if (token) {\n hours = parseInt(token[1], 10);\n minutes = parseInt(token[2], 10);\n const seconds = parseFloat(token[3].replace(',', '.'));\n if (!validateTime(hours, minutes, seconds)) {\n return NaN;\n }\n return (hours % 24) * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE + seconds * 1000;\n }\n // Invalid ISO-formatted time\n return null;\n}\nfunction dayOfISOWeekYear(isoWeekYear, week, day) {\n week = week || 0;\n day = day || 0;\n const date = new Date(0);\n date.setUTCFullYear(isoWeekYear, 0, 4);\n const fourthOfJanuaryDay = date.getUTCDay() || 7;\n const diff = week * 7 + day + 1 - fourthOfJanuaryDay;\n date.setUTCDate(date.getUTCDate() + diff);\n return date;\n}\n// Validation functions\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nfunction isLeapYearIndex(year) {\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\nfunction validateDate(year, month, date) {\n if (month < 0 || month > 11) {\n return false;\n }\n if (date != null) {\n if (date < 1) {\n return false;\n }\n const isLeapYear = isLeapYearIndex(year);\n if (isLeapYear && date > DAYS_IN_MONTH_LEAP_YEAR[month]) {\n return false;\n }\n if (!isLeapYear && date > DAYS_IN_MONTH[month]) {\n return false;\n }\n }\n return true;\n}\nfunction validateDayOfYearDate(year, dayOfYear) {\n if (dayOfYear < 1) {\n return false;\n }\n const isLeapYear = isLeapYearIndex(year);\n if (isLeapYear && dayOfYear > 366) {\n return false;\n }\n if (!isLeapYear && dayOfYear > 365) {\n return false;\n }\n return true;\n}\nfunction validateWeekDate(week, day) {\n if (week < 0 || week > 52) {\n return false;\n }\n if (day != null && (day < 0 || day > 6)) {\n return false;\n }\n return true;\n}\nfunction validateTime(hours, minutes, seconds) {\n if (hours < 0 || hours >= 25) {\n return false;\n }\n if (minutes != null && (minutes < 0 || minutes >= 60)) {\n return false;\n }\n if (seconds != null && (seconds < 0 || seconds >= 60)) {\n return false;\n }\n return true;\n}\n","import { format as dateFnsFormat } from 'date-fns/format';\nimport { formatters } from './formatters/index.js';\nimport { toDate } from '../toDate/index.js';\nconst tzFormattingTokensRegExp = /([xXOz]+)|''|'(''|[^'])+('|$)/g;\n/**\n * @name format\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. The result may consty by locale.\n *\n * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://git.io/fxCyr\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n * (see the last example)\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 7 below the table).\n *\n * Accepted patterns:\n * | Unit | Pattern | Result examples | Notes |\n * |---------------------------------|---------|-----------------------------------|-------|\n * | Era | G..GGG | AD, BC | |\n * | | GGGG | Anno Domini, Before Christ | 2 |\n * | | GGGGG | A, B | |\n * | Calendar year | y | 44, 1, 1900, 2017 | 5 |\n * | | yo | 44th, 1st, 0th, 17th | 5,7 |\n * | | yy | 44, 01, 00, 17 | 5 |\n * | | yyy | 044, 001, 1900, 2017 | 5 |\n * | | yyyy | 0044, 0001, 1900, 2017 | 5 |\n * | | yyyyy | ... | 3,5 |\n * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |\n * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |\n * | | YY | 44, 01, 00, 17 | 5,8 |\n * | | YYY | 044, 001, 1900, 2017 | 5 |\n * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |\n * | | YYYYY | ... | 3,5 |\n * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |\n * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |\n * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |\n * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |\n * | | RRRRR | ... | 3,5,7 |\n * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |\n * | | uu | -43, 01, 1900, 2017 | 5 |\n * | | uuu | -043, 001, 1900, 2017 | 5 |\n * | | uuuu | -0043, 0001, 1900, 2017 | 5 |\n * | | uuuuu | ... | 3,5 |\n * | Quarter (formatting) | Q | 1, 2, 3, 4 | |\n * | | Qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | QQ | 01, 02, 03, 04 | |\n * | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |\n * | | qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | qq | 01, 02, 03, 04 | |\n * | | qqq | Q1, Q2, Q3, Q4 | |\n * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | qqqqq | 1, 2, 3, 4 | 4 |\n * | Month (formatting) | M | 1, 2, ..., 12 | |\n * | | Mo | 1st, 2nd, ..., 12th | 7 |\n * | | MM | 01, 02, ..., 12 | |\n * | | MMM | Jan, Feb, ..., Dec | |\n * | | MMMM | January, February, ..., December | 2 |\n * | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | L | 1, 2, ..., 12 | |\n * | | Lo | 1st, 2nd, ..., 12th | 7 |\n * | | LL | 01, 02, ..., 12 | |\n * | | LLL | Jan, Feb, ..., Dec | |\n * | | LLLL | January, February, ..., December | 2 |\n * | | LLLLL | J, F, ..., D | |\n * | Local week of year | w | 1, 2, ..., 53 | |\n * | | wo | 1st, 2nd, ..., 53th | 7 |\n * | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | I | 1, 2, ..., 53 | 7 |\n * | | Io | 1st, 2nd, ..., 53th | 7 |\n * | | II | 01, 02, ..., 53 | 7 |\n * | Day of month | d | 1, 2, ..., 31 | |\n * | | do | 1st, 2nd, ..., 31st | 7 |\n * | | dd | 01, 02, ..., 31 | |\n * | Day of year | D | 1, 2, ..., 365, 366 | 8 |\n * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |\n * | | DD | 01, 02, ..., 365, 366 | 8 |\n * | | DDD | 001, 002, ..., 365, 366 | |\n * | | DDDD | ... | 3 |\n * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Su | |\n * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | EEEEE | M, T, W, T, F, S, S | |\n * | | EEEEEE | Mo, Tu, We, Th, Fr, Su, Sa | |\n * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |\n * | | io | 1st, 2nd, ..., 7th | 7 |\n * | | ii | 01, 02, ..., 07 | 7 |\n * | | iii | Mon, Tue, Wed, ..., Su | 7 |\n * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |\n * | | iiiii | M, T, W, T, F, S, S | 7 |\n * | | iiiiii | Mo, Tu, We, Th, Fr, Su, Sa | 7 |\n * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |\n * | | eo | 2nd, 3rd, ..., 1st | 7 |\n * | | ee | 02, 03, ..., 01 | |\n * | | eee | Mon, Tue, Wed, ..., Su | |\n * | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | eeeee | M, T, W, T, F, S, S | |\n * | | eeeeee | Mo, Tu, We, Th, Fr, Su, Sa | |\n * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |\n * | | co | 2nd, 3rd, ..., 1st | 7 |\n * | | cc | 02, 03, ..., 01 | |\n * | | ccc | Mon, Tue, Wed, ..., Su | |\n * | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | ccccc | M, T, W, T, F, S, S | |\n * | | cccccc | Mo, Tu, We, Th, Fr, Su, Sa | |\n * | AM, PM | a..aaa | AM, PM | |\n * | | aaaa | a.m., p.m. | 2 |\n * | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | b..bbb | AM, PM, noon, midnight | |\n * | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | bbbbb | a, p, n, mi | |\n * | Flexible day period | B..BBB | at night, in the morning, ... | |\n * | | BBBB | at night, in the morning, ... | 2 |\n * | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |\n * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |\n * | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |\n * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |\n * | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |\n * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |\n * | | KK | 1, 2, ..., 11, 0 | |\n * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |\n * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |\n * | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | m | 0, 1, ..., 59 | |\n * | | mo | 0th, 1st, ..., 59th | 7 |\n * | | mm | 00, 01, ..., 59 | |\n * | Second | s | 0, 1, ..., 59 | |\n * | | so | 0th, 1st, ..., 59th | 7 |\n * | | ss | 00, 01, ..., 59 | |\n * | Fraction of second | S | 0, 1, ..., 9 | |\n * | | SS | 00, 01, ..., 99 | |\n * | | SSS | 000, 0001, ..., 999 | |\n * | | SSSS | ... | 3 |\n * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |\n * | | XX | -0800, +0530, Z | |\n * | | XXX | -08:00, +05:30, Z | |\n * | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |\n * | | xx | -0800, +0530, +0000 | |\n * | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |\n * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |\n * | Timezone (specific non-locat.) | z...zzz | PDT, EST, CEST | 6 |\n * | | zzzz | Pacific Daylight Time | 2,6 |\n * | Seconds timestamp | t | 512969520 | 7 |\n * | | tt | ... | 3,7 |\n * | Milliseconds timestamp | T | 512969520900 | 7 |\n * | | TT | ... | 3,7 |\n * | Long localized date | P | 05/29/1453 | 7 |\n * | | PP | May 29, 1453 | 7 |\n * | | PPP | May 29th, 1453 | 7 |\n * | | PPPP | Sunday, May 29th, 1453 | 2,7 |\n * | Long localized time | p | 12:00 AM | 7 |\n * | | pp | 12:00:00 AM | 7 |\n * | | ppp | 12:00:00 AM GMT+2 | 7 |\n * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |\n * | Combination of date and time | Pp | 05/29/1453, 12:00 AM | 7 |\n * | | PPpp | May 29, 1453, 12:00:00 AM | 7 |\n * | | PPPppp | May 29th, 1453 at ... | 7 |\n * | | PPPPpppp| Sunday, May 29th, 1453 at ... | 2,7 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)\n * the output will be the same as default pattern for this unit, usually\n * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units\n * are marked with \"2\" in the last column of the table.\n *\n * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`\n *\n * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`\n *\n * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).\n * The output will be padded with zeros to match the length of the pattern.\n *\n * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`\n *\n * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 5. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` always returns the last two digits of a year,\n * while `uu` pads single digit years to 2 characters and returns other years unchanged:\n *\n * | Year | `yy` | `uu` |\n * |------|------|------|\n * | 1 | 01 | 01 |\n * | 14 | 14 | 14 |\n * | 376 | 76 | 376 |\n * | 1453 | 53 | 1453 |\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}\n * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).\n *\n * 6. Specific non-location timezones are created using the Intl browser API. The output is determined by the\n * preferred standard of the current locale (en-US by default) which may not always give the expected result.\n * For this reason it is recommended to supply a `locale` in the format options when formatting a time zone name.\n *\n * 7. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `t`: seconds timestamp\n * - `T`: milliseconds timestamp\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 8. These tokens are often confused with others. See: https://git.io/fxCyr\n *\n *\n * ### v2.0.0 breaking changes:\n *\n * - [Changes that are common for the whole\n * library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).\n *\n * - The second argument is now required for the sake of explicitness.\n *\n * ```javascript\n * // Before v2.0.0\n * format(new Date(2016, 0, 1))\n *\n * // v2.0.0 onward\n * format(new Date(2016, 0, 1), \"yyyy-MM-dd'T'HH:mm:ss.SSSxxx\")\n * ```\n *\n * - New format string API for `format` function\n * which is based on [Unicode Technical Standard\n * #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table). See [this\n * post](https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg) for more details.\n *\n * - Characters are now escaped using single quote symbols (`'`) instead of square brackets.\n *\n * @param date the original date\n * @param formatStr the string of tokens\n * @param options the object with options. See [Options]{@link https://date-fns.org/docs/Options}\n * @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link\n * https://date-fns.org/docs/toDate}\n * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)\n * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is\n * @param {Locale} [options.locale=defaultLocale] - the locale object. See\n * [Locale]{@link https://date-fns.org/docs/Locale}\n * @param {Boolean} [options.awareOfUnicodeTokens=false] - if true, allows usage of Unicode tokens causes confusion:\n * - Some of the day of year tokens (`D`, `DD`) that are confused with the day of month tokens (`d`, `dd`).\n * - Some of the local week-numbering year tokens (`YY`, `YYYY`) that are confused with the calendar year tokens\n * (`yy`, `yyyy`). See: https://git.io/fxCyr\n * @param {String} [options.timeZone=''] - used to specify the IANA time zone offset of a date String.\n * @param {Date|Number} [options.originalDate] - can be used to pass the original unmodified date to `format` to\n * improve correctness of the replaced timezone token close to the DST threshold.\n * @throws {TypeError} 2 arguments required\n * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2\n * @throws {RangeError} `options.locale` must contain `localize` property\n * @throws {RangeError} `options.locale` must contain `formatLong` property\n * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6\n * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7\n * @throws {RangeError} `options.awareOfUnicodeTokens` must be set to `true` to use `XX` token; see:\n * https://git.io/fxCyr\n *\n * @example\n * // Represent 11 February 2014 in middle-endian format:\n * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')\n * //=> '02/11/2014'\n *\n * @example\n * // Represent 2 July 2014 in Esperanto:\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = format(new Date(2014, 6, 2), \"do 'de' MMMM yyyy\", {\n * locale: eoLocale\n * })\n * //=> '2-a de julio 2014'\n *\n * @example\n * // Escape string by single quote characters:\n * const result = format(new Date(2014, 6, 2, 15), \"h 'o''clock'\")\n * //=> \"3 o'clock\"\n */\nexport function format(date, formatStr, options = {}) {\n formatStr = String(formatStr);\n const matches = formatStr.match(tzFormattingTokensRegExp);\n if (matches) {\n const d = toDate(options.originalDate || date, options);\n // Work through each match and replace the tz token in the format string with the quoted\n // formatted time zone so the remaining tokens can be filled in by date-fns#format.\n formatStr = matches.reduce(function (result, token) {\n if (token[0] === \"'\") {\n return result; // This is a quoted portion, matched only to ensure we don't match inside it\n }\n const pos = result.indexOf(token);\n const precededByQuotedSection = result[pos - 1] === \"'\";\n const replaced = result.replace(token, \"'\" + formatters[token[0]](d, token, options) + \"'\");\n // If the replacement results in two adjoining quoted strings, the back to back quotes\n // are removed, so it doesn't look like an escaped quote.\n return precededByQuotedSection\n ? replaced.substring(0, pos - 1) + replaced.substring(pos + 1)\n : replaced;\n }, formatStr);\n }\n return dateFnsFormat(date, formatStr, options);\n}\n","import { useState, useEffect, useMemo, useRef, Key, JSX } from 'react';\nimport { PageProps } from '@inertiajs/inertia';\nimport { Head, usePage, router } from '@inertiajs/react';\nimport { useUser, User } from '../../src/context/UserContext';\nimport { useForm } from '@mantine/form';\nimport {\n Container,\n TextInput,\n Radio,\n RadioGroup,\n Button,\n MantineProvider,\n createTheme,\n Box,\n Paper,\n Title,\n MultiSelect,\n Accordion,\n Text,\n Avatar,\n Stack,\n Select,\n Alert,\n SegmentedControl,\n ActionIcon,\n Group,\n InputLabel,\n Badge,\n LoadingOverlay,\n} from '@mantine/core';\nimport { DatePickerInput, TimeInput } from '@mantine/dates';\nimport { Notifications, showNotification } from '@mantine/notifications';\nimport {\n IconAlertCircle,\n IconCheck,\n IconLink,\n IconBrandInstagram,\n IconBrandFacebook,\n IconTicket,\n IconMapPinFilled,\n IconCalendarTime,\n IconCalendarPlus,\n IconList,\n IconUsersGroup,\n IconInfoCircle,\n IconClock,\n IconAlertTriangle,\n} from '@tabler/icons-react';\nimport { RichTextEditor } from '@mantine/tiptap';\nimport { useEditor, EditorContent } from '@tiptap/react';\nimport Highlight from '@tiptap/extension-highlight';\nimport StarterKit from '@tiptap/starter-kit';\nimport Underline from '@tiptap/extension-underline';\nimport TextAlign from '@tiptap/extension-text-align';\nimport Heading from '@tiptap/extension-heading';\nimport Link from '@tiptap/extension-link';\nimport timezoneData from '../../entrypoints/utilities/timezones.json';\nimport ImageUploadModal from '../../components/ImageUploadModal';\nimport DangerZoneCard from '../../components/DangerZoneCard';\nimport { format } from 'date-fns-tz';\nimport AddressAutocomplete from '../../components/AddressAutocompleteMap';\nimport { parseISO } from 'date-fns';\n\nimport '@mantine/core/styles.css';\nimport '@mantine/notifications/styles.css';\nimport '../../styles/Login-form.css';\nimport '@mantine/tiptap/styles.css';\nimport '@mantine/dates/styles.css';\n\n// Type definitions remain the same\ntype Artist = {\n id: number;\n name: string;\n avatar_url: string;\n};\n\ninterface User {\n id: number;\n email: string;\n username: string;\n avatar_url: string | null;\n roles: string[];\n organizer_ids?: number[];\n}\n\ninterface EventType {\n id: number;\n name: string;\n}\n\ninterface DanceStyle {\n id: number;\n name: string;\n}\n\ninterface EventData {\n id: number;\n name: string;\n slug?: string;\n description?: string;\n address?: string;\n online_event?: boolean;\n is_recurring?: boolean;\n spans_next_day?: boolean;\n timezone?: string;\n event_start_date?: string;\n event_end_date?: string;\n website_url?: string;\n ticket_url?: string;\n facebook_url?: string;\n event_type_ids?: number[];\n dance_style_ids?: number[];\n event_frequency_id?: number;\n tiktok_url: string;\n meetup_url: string;\n instagram_url: string;\n event_image_url: string | null;\n artists_ids?: number[];\n user_id?: number;\n event_status_id?: number;\n organizer_ids?: number[];\n event_image?: File | null;\n event_start_time?: string;\n event_end_time?: string;\n}\n\ninterface EventFrequency {\n id: number;\n name: string;\n}\n\ninterface RecurringEvent {\n id: number;\n title: string;\n}\n\ntype OrganizerTuple = [string, number];\n\ninterface EditEventPageProps extends InertiaPageProps, PageProps {\n event: {\n id: number;\n name: string;\n slug?: string;\n description?: string;\n address?: string;\n online_event?: boolean;\n is_recurring?: boolean;\n spans_next_day?: boolean;\n timezone?: string;\n event_start_date?: string;\n event_end_date?: string;\n event_start_time?: string;\n event_end_time?: string;\n website_url?: string;\n ticket_url?: string;\n facebook_url?: string;\n event_type_ids?: number[];\n dance_style_ids?: number[];\n event_frequency_id?: number;\n tiktok_url: string;\n meetup_url: string;\n instagram_url: string;\n event_image_url: string;\n artists?: Artist[];\n artists_ids?: number[];\n dance_style?: DanceStyle[];\n recurring_event?: RecurringEvent;\n user_id?: number;\n event_status_id?: number;\n organizer_ids?: number[];\n };\n artists?: Artist[];\n event_types: EventType[];\n dance_styles: DanceStyle[];\n event_frequencies: EventFrequency[];\n organizers?: Array<[string, number]>;\n errors?: Record;\n user?: Array<[string, number]>;\n}\n\ninterface AddressInfo {\n address: string;\n lat: number;\n lng: number;\n timeZoneId: string;\n}\n\ninterface AddressAutocompleteProps {\n value: string;\n onChange: (value: string) => void;\n onTimezoneSelect: (timeZoneId: string) => void;\n}\n\nconst theme = createTheme({\n primaryColor: 'orange',\n colors: {\n orange: [\n '#FEF5ED',\n '#FDE3D1',\n '#FCB693',\n '#FA9D73',\n '#F87F4D',\n '#F66A33',\n '#EA580C',\n '#C44B0A',\n '#9E3D08',\n '#783006',\n ],\n },\n fontFamily: 'Poppins, sans-serif',\n headings: { fontFamily: 'Poppins, sans-serif' },\n components: {\n InputLabel: {\n styles: (theme: { fontSizes: { sm: any } }) => ({\n label: {\n color: '#FFF7ED', // Ensure this color applies\n fontSize: theme.fontSizes.sm, // Optional: Adjust size\n fontWeight: 500, // Optional: Adjust weight\n },\n }),\n },\n Input: {\n styles: () => ({\n input: {\n backgroundColor: '#686868', // Correctly sets input background\n color: '#F2F2F2', // Ensures text inside the input is visible\n borderColor: '#787878', // Optional: Adjust border color\n '&::placeholder': {\n color: '#fff', // Optional: Lighten placeholder text\n },\n },\n }),\n },\n },\n});\n\nexport default function EditEvent() {\n // 1. Context Hooks\n const { user, refreshUser } = useUser() as { user: User | null; refreshUser: () => Promise };\n const { props } = usePage();\n const [isLoadingTimezones, setIsLoadingTimezones] = useState(true);\n const [timezoneOptions, setTimezoneOptions] = useState<{ value: string; label: string }[]>([]);\n const [timezone, setTimezone] = useState('');\n const [address, setAddress] = useState('');\n\n // 2. Destructure props\n const {\n event,\n errors,\n artists: propArtists,\n event_types: propEventTypes,\n dance_styles: propDanceStyles,\n event_frequencies: propEventFrequencies,\n users: propUsers,\n event_statuses: propEventStatuses,\n organizers: propOrganizers,\n } = props;\n\n const statusMapping: Record = {\n 1: { status: 'Active', color: 'green', icon: },\n 2: { status: 'Pending', color: 'yellow', icon: },\n 3: { status: 'Draft', color: 'blue', icon: },\n };\n\n const eventStatus =\n event.event_status_id && statusMapping[event.event_status_id]\n ? statusMapping[event.event_status_id]\n : { status: 'Unknown', color: 'gray', icon: };\n\n // 3. State Hooks\n const [isLoading, setIsLoading] = useState(false);\n const [overlayVisible, setOverlayVisible] = useState(false);\n\n const [seoImagePreview, setSeoImagePreview] = useState(event.event_image_url);\n\n const [values, setValues] = useState(event);\n const startTimeRef = useRef(null);\n const endTimeRef = useRef(null);\n\n const startPickerControl = (\n startTimeRef.current?.showPicker()}>\n \n \n );\n const endPickerControl = (\n endTimeRef.current?.showPicker()}>\n \n \n );\n\n const eventStartTime = event.event_start_date\n ? format(new Date(event.event_start_date), 'HH:mm', { timeZone: 'UTC' })\n : '';\n const eventEndTime = event.event_end_date ? format(new Date(event.event_end_date), 'HH:mm', { timeZone: 'UTC' }) : '';\n\n const DRAFT_STATUS_ID = 3;\n const isDraft = event.event_status_id === DRAFT_STATUS_ID;\n\n const getIanaTimezone = (timezoneLabel: string): string => {\n // Normalize the label: replace all whitespace with underscores\n const normalizedLabel = timezoneLabel.replace(/\\s+/g, '_');\n\n // Try to find a match in your timezoneData (assuming your keys are in correct IANA format)\n const entry = Object.entries(timezoneData).find(([value, label]) => value === normalizedLabel);\n if (entry) {\n const [ianaTimezone] = entry;\n\n return ianaTimezone;\n } else {\n console.warn('⚠️ No match found, defaulting to UTC!');\n return 'UTC';\n }\n };\n\n const handleStartTimeChange = (e: React.ChangeEvent) => {\n const timeValue = e.target.value; // e.g., \"18:09\"\n\n form.setFieldValue('event_start_time', timeValue); // ✅ Update form values\n\n setValues((prevValues) => ({\n ...prevValues,\n event_start_time: timeValue, // ✅ Ensure values are updated\n }));\n\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n };\n\n const handleEndTimeChange = (e: React.ChangeEvent) => {\n const timeValue = e.target.value; // e.g., \"16:09\"\n\n form.setFieldValue('event_end_time', timeValue); // ✅ Update form values\n\n setValues((prevValues) => ({\n ...prevValues,\n event_end_time: timeValue, // ✅ Ensure values are updated\n }));\n\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n };\n\n function validateURL(input: string) {\n const urlPattern = /^(http:\\/\\/|https:\\/\\/)/i;\n return urlPattern.test(input);\n }\n\n const startDate = event.event_start_date ? new Date(event.event_start_date) : null;\n const endDate = event.event_end_date ? new Date(event.event_end_date) : null;\n\n const getDatePortion = (isoString: string) => {\n if (!isoString) return null;\n // Extract just the YYYY-MM-DD portion\n return isoString.split('T')[0];\n };\n\n // 5. Form Hook\n const form = useForm({\n initialValues: {\n name: event.name || '',\n slug: event.slug || '',\n description: event.description || '',\n address: event.address || '',\n timezone: event.timezone || '',\n online_event: event.online_event ? 'true' : 'false',\n is_recurring: event.is_recurring ? 'true' : 'false',\n spans_next_day: event.spans_next_day ? 'true' : 'false',\n event_start_date: event.event_start_date,\n event_start_time: event.event_start_time,\n event_end_time: event.event_end_time,\n event_end_date: event.event_end_date ? getDatePortion(event.event_end_date) : null,\n website_url: event.website_url || '',\n ticket_url: event.ticket_url || '',\n facebook_url: event.facebook_url || '',\n instagram_url: event.instagram_url || '',\n meetup_url: event.meetup_url || '',\n tiktok_url: event.tiktok_url || '',\n event_type_ids: event.event_type_ids || [],\n artistIds: event.artist_ids || [],\n dance_style_ids: event.dance_style_ids || [],\n event_frequency_id: event.event_frequency_id || '',\n user_id: event.user_id || null,\n event_status_id: event.event_status_id || null,\n organizer_ids: event.organizer_ids || [],\n event_image_url: event.event_image_url || null,\n },\n validate: {\n name: (value) => (value ? null : 'Event name is required'),\n slug: (value) => (value ? null : 'Slug is required'),\n description: (value) => {\n // If using the editor instance\n if (editor) {\n // Get plain text content (strips HTML tags)\n const plainText = editor.getText();\n\n // Check if it meets the minimum length requirement\n if (plainText.length < 20) {\n return 'Description must be at least 20 characters long';\n }\n }\n return null;\n },\n event_start_date: (value) => (value ? null : 'Event start date is required'),\n event_start_time: (value) => (value ? null : 'Event start time is required'),\n event_end_date: (value, values) => {\n if (!value || !values.event_start_date) return null;\n const start = new Date(values.event_start_date);\n const end = new Date(value);\n if (end < start) {\n return 'Event end date must be the same as or after the event start date';\n }\n return null;\n },\n event_end_time: (value, values) => {\n if (!value || !values.event_start_time || !values.event_start_date || !values.event_end_date) {\n return null;\n }\n\n const [startHour, startMinute] = values.event_start_time.split(':').map(Number);\n const [endHour, endMinute] = value.split(':').map(Number);\n\n // Parse dates for comparison\n let startDate, endDate;\n\n // Create consistent date objects for comparison\n if (values.event_start_date.includes('T')) {\n // Parse ISO timestamp\n const tempStartDate = new Date(values.event_start_date);\n startDate = new Date(tempStartDate.getUTCFullYear(), tempStartDate.getUTCMonth(), tempStartDate.getUTCDate());\n } else {\n // Parse YYYY-MM-DD format\n const [startYear, startMonth, startDay] = values.event_start_date.split('-').map(Number);\n startDate = new Date(startYear, startMonth - 1, startDay);\n }\n\n if (values.event_end_date.includes('T')) {\n // Parse ISO timestamp\n const tempEndDate = new Date(values.event_end_date);\n endDate = new Date(tempEndDate.getUTCFullYear(), tempEndDate.getUTCMonth(), tempEndDate.getUTCDate());\n } else {\n // Parse YYYY-MM-DD format\n const [endYear, endMonth, endDay] = values.event_end_date.split('-').map(Number);\n endDate = new Date(endYear, endMonth - 1, endDay);\n }\n\n // Compare dates without time components\n const startDateOnly = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());\n const endDateOnly = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());\n\n // Check if dates are the same (comparing just the date portion)\n if (startDateOnly.getTime() === endDateOnly.getTime()) {\n // Same day: End time must be after start time\n if (endHour < startHour || (endHour === startHour && endMinute <= startMinute)) {\n return 'Event end time must be after event start time when the dates are the same';\n }\n } else if (endDateOnly < startDateOnly) {\n // End date before start date\n return 'Event end date cannot be before event start date';\n }\n // If dates are different and end date is after start date, any end time is valid\n\n return null;\n },\n timezone: (value) => (value ? null : 'Timezone is required'),\n website_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid website URL starting with http:// or https://';\n }\n return null;\n },\n ticket_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid passes URL starting with http:// or https://';\n }\n return null;\n },\n facebook_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid Facebook URL starting with http:// or https://';\n }\n return null;\n },\n instagram_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid Instagram URL starting with http:// or https://';\n }\n return null;\n },\n meetup_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid Meetup URL starting with http:// or https://';\n }\n return null;\n },\n tiktok_url: (value) => {\n if (value && !validateURL(value)) {\n return 'Please enter a valid TikTok URL starting with http:// or https://';\n }\n return null;\n },\n event_type_ids: (value) =>\n Array.isArray(value) && value.length > 0 ? null : 'At least one event type is required',\n dance_style_ids: (value) =>\n Array.isArray(value) && value.length > 0 ? null : 'At least one dance style is required',\n },\n validateInputOnChange: true,\n });\n\n // Helper function to format GMT offset\n const formatOffset = (offsetSeconds: number) => {\n const hours = Math.floor(Math.abs(offsetSeconds) / 3600);\n const minutes = Math.floor((Math.abs(offsetSeconds) % 3600) / 60);\n const sign = offsetSeconds >= 0 ? '+' : '-';\n return `GMT${sign}${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;\n };\n\n useEffect(() => {\n const fetchTimezones = async () => {\n setIsLoadingTimezones(true);\n try {\n const apiKey = 'N2IE9BKU2EQR'; // Your TimeZoneDB API key\n const response = await fetch(`https://api.timezonedb.com/v2.1/list-time-zone?key=${apiKey}&format=json`);\n const data = await response.json();\n\n if (data.status === 'OK' && data.zones && Array.isArray(data.zones)) {\n // Format the timezone options\n const options = data.zones.map((zone: any) => ({\n value: zone.zoneName, // IANA timezone ID (e.g., \"America/Chicago\")\n label: `${zone.zoneName} (${formatOffset(zone.gmtOffset)})`, // Display name with GMT offset\n }));\n\n setTimezoneOptions(options);\n\n // Check if the current event timezone exists in the fetched timezones\n // If it does, make sure it's in the correct format\n if (form.values.timezone) {\n const matchedTimezone = options.find((option) => option.value === form.values.timezone);\n if (matchedTimezone) {\n // Timezone exists in the list, update it to ensure correct format\n form.setFieldValue('timezone', matchedTimezone.value);\n }\n }\n } else {\n console.error('Error fetching timezone list:', data.message || 'Unknown error');\n }\n } catch (error) {\n console.error('Failed to fetch timezones:', error);\n } finally {\n setIsLoadingTimezones(false);\n }\n };\n\n fetchTimezones();\n }, []);\n\n useEffect(() => {\n if (event) {\n console.log('Event image URL:', event.event_image_url);\n setSeoImagePreview(event.event_image_url);\n }\n }, [event]);\n\n useEffect(() => {\n if (user) {\n setIsLoading(false);\n }\n\n console.log('Event data received:', event);\n console.log('Form initial values:', form.values);\n\n if (Object.keys(form.errors).length > 0) {\n const firstErrorKey = Object.keys(form.errors)[0];\n const firstErrorMessage = form.errors[firstErrorKey];\n\n showNotification({\n title: 'Validation Error',\n message: firstErrorMessage || 'Please fix the errors before submitting.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n }\n }, [user, form.errors]);\n\n // 6. Editor Hook\n const editor = useEditor({\n extensions: [\n StarterKit,\n Highlight,\n Underline,\n TextAlign.configure({ types: ['heading', 'paragraph'] }),\n Heading.configure({ levels: [1, 2, 3] }),\n Link.configure({ openOnClick: true }),\n ],\n content: form.values.description,\n onUpdate: ({ editor }) => {\n const html = editor.getHTML();\n\n form.setFieldValue('description', html);\n },\n });\n\n // 7. Derived State and Data Processing\n const event_types = Array.isArray(propEventTypes) ? propEventTypes : [];\n const artists = Array.isArray(propArtists) ? propArtists : [];\n const dance_styles = Array.isArray(propDanceStyles) ? propDanceStyles : [];\n const event_frequencies = Array.isArray(propEventFrequencies) ? propEventFrequencies : [];\n const users = Array.isArray(propUsers) ? propUsers : [];\n const event_statuses = Array.isArray(propEventStatuses) ? propEventStatuses : [];\n const filteredOrganizers = useMemo(() => {\n const organizers = user?.roles?.includes('SuperAdmin')\n ? propOrganizers || []\n : (propOrganizers || []).filter((org) => user?.organizer_ids?.includes(org.id));\n\n // Sort organizers alphabetically by name\n return [...organizers].sort((a, b) => a.name.localeCompare(b.name));\n }, [propOrganizers, user]);\n\n const is_superadmin = user?.roles?.includes('SuperAdmin') || false;\n\n const frequencyOrder = ['One Time', 'Weekly', 'Every Two Weeks', 'Monthly', 'Annual'];\n const sortedEventFrequencies = event_frequencies.sort((a, b) => {\n return frequencyOrder.indexOf(a.name) - frequencyOrder.indexOf(b.name);\n });\n\n const [croppedImage, setCroppedImage] = useState(null);\n\n const handleImageChange = (file: File) => {\n // Update your local component state:\n setValues((prevValues) => {\n const newValues = { ...prevValues, event_image: file };\n\n return newValues;\n });\n\n // Also update the form's state:\n form.setFieldValue('event_image', file);\n\n // Update preview:\n setSeoImagePreview(URL.createObjectURL(file));\n };\n\n const handleTimezoneChange = (selectedLabel: string) => {\n const ianaTimezone = getIanaTimezone(selectedLabel); // Convert label to IANA timezone\n\n if (!ianaTimezone || ianaTimezone.length < 3) {\n console.error('🚨 Error: Invalid timezone selected!', ianaTimezone);\n return;\n }\n\n // Update state and form as a string, not an array\n setValues((prevValues) => ({\n ...prevValues,\n timezone: ianaTimezone,\n }));\n\n form.setFieldValue('timezone', ianaTimezone);\n };\n\n const TIMEZONE_OPTIONS = Object.entries(timezoneData).map(([value, label]) => ({\n value,\n label: `${label} (${value})`,\n }));\n\n const handleSubmit = async (submittedValues: typeof form.values & { event_image?: File; draft?: boolean }) => {\n setIsLoading(true);\n console.log('isLoading set to true');\n setOverlayVisible(true);\n console.log('overlayVisible set to true');\n\n console.log('State is Loading:', isLoading);\n console.log('State Overlay Visible:', overlayVisible);\n\n // Check if this is a draft submission (either from current status or from button click)\n const isDraft =\n submittedValues.draft === true ||\n eventStatus.status === 'Draft' ||\n form.values.event_status_id === DRAFT_STATUS_ID;\n\n try {\n // Get CSRF Token\n const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content;\n if (!csrfToken) {\n console.error('CSRF token not found');\n return;\n }\n\n // ✅ Build FormData for Submission\n const formData = new FormData();\n\n // For drafts, include all event information regardless of completeness\n // For non-drafts, everything should already be validated\n\n // Handle date fields safely\n if (form.values.event_start_date && form.values.event_start_time) {\n const rawStartDate = form.values.event_start_date;\n // Safe string operations with null checks\n const startDatePortion =\n rawStartDate && typeof rawStartDate === 'string' && rawStartDate.includes('T')\n ? rawStartDate.split('T')[0]\n : rawStartDate;\n\n const combinedStart = `${startDatePortion}T${form.values.event_start_time}:00`;\n formData.append('event[event_start_date]', combinedStart);\n } else if (form.values.event_start_date) {\n // If only date exists but no time, still save the date\n formData.append('event[event_start_date]', form.values.event_start_date);\n }\n\n if (form.values.event_end_date && form.values.event_end_time) {\n const rawEndDate = form.values.event_end_date;\n // Safe string operations with null checks\n const endDatePortion =\n rawEndDate && typeof rawEndDate === 'string' && rawEndDate.includes('T')\n ? rawEndDate.split('T')[0]\n : rawEndDate;\n\n const combinedEnd = `${endDatePortion}T${form.values.event_end_time}:00`;\n formData.append('event[event_end_date]', combinedEnd);\n } else if (form.values.event_end_date) {\n // If only date exists but no time, still save the date\n formData.append('event[event_end_date]', form.values.event_end_date);\n }\n\n // Always include timezone if it exists, even for drafts\n if (form.values.timezone) {\n if (Array.isArray(form.values.timezone)) {\n formData.append('event[timezone]', form.values.timezone[0]);\n } else {\n formData.append('event[timezone]', form.values.timezone);\n }\n }\n\n // Always include all form values for both drafts and submissions\n // Required fields\n formData.append('event[name]', form.values.name);\n if (form.values.slug) formData.append('event[slug]', form.values.slug);\n if (form.values.address) formData.append('event[address]', form.values.address);\n\n // Append description from the editor if it exists\n if (editor && typeof editor.getHTML === 'function') {\n formData.append('event[description]', editor.getHTML());\n }\n\n // Append event image if provided\n if (submittedValues.event_image) {\n formData.append('event[event_image]', submittedValues.event_image);\n }\n\n // Handle cropped image if available\n if (croppedImage) {\n formData.append('event[cropped_image]', croppedImage);\n }\n\n // Append optional fields - always include any provided values\n ['website_url', 'ticket_url', 'facebook_url', 'instagram_url', 'meetup_url', 'tiktok_url'].forEach((field) => {\n if (form.values[field]) formData.append(`event[${field}]`, form.values[field]);\n });\n\n // Boolean fields - always include\n formData.append('event[online_event]', form.values.online_event === 'true' ? 'true' : 'false');\n formData.append('event[is_recurring]', form.values.is_recurring === 'true' ? 'true' : 'false');\n formData.append('event[spans_next_day]', form.values.spans_next_day === 'true' ? 'true' : 'false');\n\n // ✅ Append Arrays Properly (Each Item Individually) - include any provided values\n if (Array.isArray(form.values.event_type_ids) && form.values.event_type_ids.length > 0) {\n form.values.event_type_ids.forEach((id) => formData.append('event[event_type_ids][]', id.toString()));\n }\n\n if (Array.isArray(form.values.dance_style_ids) && form.values.dance_style_ids.length > 0) {\n form.values.dance_style_ids.forEach((id) => formData.append('event[dance_style_ids][]', id.toString()));\n }\n\n if (Array.isArray(form.values.artistIds) && form.values.artistIds.length > 0) {\n form.values.artistIds.forEach((id) => formData.append('event[artist_ids][]', id.toString()));\n }\n\n if (Array.isArray(form.values.organizer_ids) && form.values.organizer_ids.length > 0) {\n form.values.organizer_ids.forEach((id) => formData.append('event[organizer_ids][]', id.toString()));\n }\n\n // Append parameters based on submission type\n if (isDraft) {\n formData.append('save_changes', 'true');\n } else {\n formData.append('submit_for_approval', 'true');\n }\n\n // Send PUT request\n const response = await fetch(`/events/${form.values.slug}`, {\n method: 'PUT',\n headers: { Accept: 'application/json', 'X-CSRF-Token': csrfToken },\n credentials: 'include',\n body: formData,\n });\n\n if (response.ok) {\n showNotification({\n title: 'Update Successful',\n message: isDraft ? 'Event draft was successfully saved!' : 'Event was successfully updated!',\n color: 'green',\n icon: ,\n autoClose: 6000,\n position: 'top-right',\n });\n\n setTimeout(() => (window.location.href = `/events/${form.values.slug}`), 1500);\n } else {\n const data = await response.json().catch(() => ({}));\n\n showNotification({\n title: 'Submission Failed',\n message: data.error || 'An error occurred while updating the event.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n\n if (data.errors) form.setErrors(data.errors);\n }\n } catch (error) {\n showNotification({\n title: 'Unexpected Error',\n message: 'An unexpected error occurred. Please try again.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n position: 'top-right',\n });\n\n console.error('Error updating event:', error);\n } finally {\n setIsLoading(false);\n }\n };\n\n const handleAddressChange = (newAddress: string) => {\n form.setFieldValue('address', newAddress);\n setValues((prevValues) => ({\n ...prevValues,\n address: newAddress,\n }));\n };\n\n return (\n \n \n \n \n {is_superadmin && (\n \n \n \n \n Admin Info\n \n \n ID: {event.id}\n \n \n\n {/* Select User */}\n ({\n value: id.toString(),\n label: username,\n }))}\n value={form.values.user_id ? form.values.user_id.toString() : null}\n onChange={(value) => form.setFieldValue('user_id', value ? Number(value) : null)}\n searchable\n clearable\n />\n\n {/* Select Event Status */}\n ({\n value: status.id.toString(),\n label: status.name,\n }))}\n value={form.values.event_status_id ? form.values.event_status_id.toString() : null}\n onChange={(value) => form.setFieldValue('event_status_id', value ? Number(value) : null)}\n clearable\n />\n \n \n )}\n \n {event.recurring_event && (\n }\n title=\"Editing a Recurring Event Instance\"\n color=\"orange\"\n radius=\"sm\"\n variant=\"filled\"\n mb=\"md\"\n mt=\"md\"\n >\n \n You are currently editing a single instance of the recurring event:{' '}\n {event.recurring_event.title}.\n \n \n These changes will not affect the other occurrences of this event.\n \n \n )}\n \n \n Edit Event: {event.name}\n \n
      handleSubmit({ ...form.values, event_image: values.event_image }))}>\n \n \n \n \n \n Event Host & Name\n \n \n \n 0 ? '' : 'Select event organizers'\n }\n name=\"organizer_ids\"\n data={filteredOrganizers.map((org) => ({\n value: org.id.toString(),\n label: org.name,\n }))}\n value={(form.values.organizer_ids || []).map((id) => id.toString())}\n onChange={(values) => {\n const numericValues = Array.isArray(values) ? values.map((v) => Number(v)) : [];\n form.setFieldValue('organizer_ids', numericValues);\n }}\n searchable\n clearable\n mt=\"md\"\n styles={{ label: { color: '#FFF7ED' } }}\n />\n \n\n \n \n \n \n\n \n \n \n \n \n Location Info\n \n \n \n \n Is this an online event or in-person event?\n \n \n\n {form.values.online_event === 'false' && (\n {\n setAddress(newAddress);\n form.setFieldValue('address', newAddress);\n }}\n onTimezoneSelect={(newTimezone) => {\n setTimezone(newTimezone);\n form.setFieldValue('timezone', newTimezone);\n }}\n timezoneValue={form.values.timezone}\n />\n )}\n \n \n \n\n \n \n \n \n \n Date & Time Info\n \n \n \n \n\n \n {\n console.log('Raw event_start_date value:', form.values.event_start_date);\n console.log('Value type:', typeof form.values.event_start_date);\n console.log('Value length:', form.values.event_start_date.length);\n\n // If the value is just a date string (YYYY-MM-DD), parse it properly\n if (\n form.values.event_start_date.length === 10 &&\n form.values.event_start_date.includes('-')\n ) {\n // Create date at noon to avoid any timezone boundary issues\n const [year, month, day] = form.values.event_start_date.split('-').map(Number);\n console.log('Parsed components:', { year, month, day });\n const date = new Date(year, month - 1, day, 12, 0, 0);\n console.log('📆 Date created with noon local time:', date);\n return date;\n } else {\n // Otherwise, use the standard Date constructor\n console.log('Using standard Date constructor');\n const date = new Date(form.values.event_start_date);\n console.log('📆 Date created with standard constructor:', date);\n return date;\n }\n })()\n : null\n }\n onChange={(date) => {\n if (date) {\n const localDate = new Date(date);\n localDate.setHours(0, 0, 0, 0);\n\n // Get the date components directly from the local date object\n const year = localDate.getFullYear();\n const month = String(localDate.getMonth() + 1).padStart(2, '0');\n const day = String(localDate.getDate()).padStart(2, '0');\n const dateString = `${year}-${month}-${day}`;\n\n // Store only the date portion, without time information\n form.setFieldValue('event_start_date', dateString);\n } else {\n form.setFieldValue('event_start_date', '');\n }\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n }}\n required={!isDraft}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n\n {\n handleStartTimeChange(e);\n\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n }}\n required={!isDraft}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n \n\n \n {\n console.log('Raw event_end_date value:', form.values.event_end_date);\n\n // Parse the date while respecting the UTC timezone\n if (form.values.event_end_date.includes('T')) {\n // If it has a 'T', it's a full ISO timestamp\n const utcDate = new Date(form.values.event_end_date);\n\n // Create a new date with just the UTC date components to avoid timezone shift\n return new Date(\n utcDate.getUTCFullYear(),\n utcDate.getUTCMonth(),\n utcDate.getUTCDate(),\n 12,\n 0,\n 0,\n );\n } else {\n // If it's just YYYY-MM-DD\n const [year, month, day] = form.values.event_end_date.split('-').map(Number);\n return new Date(year, month - 1, day, 12, 0, 0);\n }\n })()\n : null\n }\n onChange={(date) => {\n if (date) {\n // Extract UTC date components and create ISO date string (date only)\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n form.setFieldValue('event_end_date', `${year}-${month}-${day}`);\n } else {\n form.setFieldValue('event_end_date', '');\n }\n }}\n required={!isDraft}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n {\n handleEndTimeChange(e);\n\n form.validateField('event_end_date');\n form.validateField('event_end_time');\n }}\n required={!isDraft}\n styles={{ label: { color: '#FFF7ED' } }}\n />\n \n {(form.errors.event_end_date || form.errors.event_end_time) && (\n }>\n {form.errors.event_end_date &&
      {form.errors.event_end_date}
      }\n {form.errors.event_end_time &&
      {form.errors.event_end_time}
      }\n
      \n )}\n
      \n
      \n
      \n\n \n \n \n \n \n Event Details\n \n \n \n 0\n ? ''\n : 'Choose your event types'\n }\n data={event_types.map((type) => ({\n value: type.id.toString(), // Convert ID to string for MultiSelect\n label: type.name,\n }))}\n value={\n // Ensure we always have an array and convert numbers to strings\n (Array.isArray(form.values.event_type_ids) ? form.values.event_type_ids : []).map((id) =>\n id.toString(),\n )\n }\n onChange={(values) => {\n // Convert the selected string IDs back to numbers\n const numericValues = values.map(Number);\n form.setFieldValue('event_type_ids', numericValues);\n }}\n searchable\n clearable\n required={!isDraft}\n />\n\n 0 ? '' : 'Choose dance styles'\n }\n data={dance_styles.map((style) => ({\n value: style.id.toString(),\n label: style.name,\n }))}\n value={(Array.isArray(form.values.dance_style_ids) ? form.values.dance_style_ids : []).map((id) =>\n id.toString(),\n )}\n onChange={(values) => {\n // Convert the selected string IDs back to numbers\n const numericValues = values.map(Number);\n form.setFieldValue('dance_style_ids', numericValues);\n }}\n searchable\n clearable\n mt=\"lg\"\n required={!isDraft}\n />\n\n ({\n value: freq.id.toString(), // Mantine requires string values\n label: freq.name, // Display frequency name\n }))}\n value={form.values.event_frequency_id ? form.values.event_frequency_id.toString() : null}\n onChange={(value) => form.setFieldValue('event_frequency_id', value ? Number(value) : null)}\n searchable\n clearable\n mt=\"lg\"\n mb=\"xl\"\n required={!isDraft}\n />\n\n \n Event Description\n \n {editor && (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n )}\n \n \n \n\n \n \n \n \n \n Artists\n \n \n \n ({\n value: artist.id.toString(), // value as string\n label: artist.name,\n }))}\n value={(form.values.artistIds || []).map(String)}\n onChange={(values) => {\n const numericValues = Array.isArray(values) ? values.map(Number) : [];\n form.setFieldValue('artistIds', numericValues);\n }}\n searchable\n clearable\n />\n\n {/* Display selected artist avatars below */}\n {form.values.artistIds.length > 0 && (\n \n \n {form.values.artistIds.map((id: Key | null | undefined) => {\n const artist = artists.find((a) => a.id === id);\n return artist ? (\n \n ) : null;\n })}\n \n \n )}\n \n \n \n\n \n \n \n \n \n Links\n \n \n \n \n\n \n\n \n\n \n\n \n\n \n \n \n \n\n {/* Example error display */}\n {errors && Object.keys(errors).length > 0 && (\n \n {Object.entries(errors).map(([field, messages]) => (\n
      \n {field}: {messages.join(', ')}\n
      \n ))}\n
      \n )}\n\n {event.event_status_id === 3 ? (\n \n {\n // For draft, only validate name\n if (!form.values.name || form.values.name.trim() === '') {\n showNotification({\n title: 'Validation Error',\n message: 'Event name is required even for drafts.',\n color: 'red',\n icon: ,\n autoClose: 5000,\n });\n return;\n }\n\n // If name exists, proceed with draft submission\n handleSubmit({\n ...form.values,\n event_image: values.event_image,\n draft: true, // Add a flag to indicate this is a draft submission\n });\n }}\n >\n Save Changes as Draft\n \n\n {\n // For publish, run full validation\n const validationErrors = form.validate();\n if (validationErrors.hasErrors) {\n // Clear any existing notifications first\n Notifications.clean();\n\n // Show a notification for each validation error with a slight delay\n Object.entries(validationErrors.errors).forEach(([label, message], index) => {\n // Format the label to be more readable\n const formattedLabel = label\n // Replace underscores with spaces\n .replace(/_/g, ' ')\n // Split into words, capitalize each one, and join back\n .split(' ')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n\n setTimeout(() => {\n Notifications.show({\n title: `Error with ${formattedLabel}`,\n message: message,\n color: 'red',\n icon: ,\n autoClose: 8000,\n position: 'top-right',\n });\n }, index * 200); // 200ms delay between each notification\n });\n\n setIsLoading(false);\n return;\n }\n\n // If validation passes, proceed with publish submission\n handleSubmit({\n ...form.values,\n event_image: values.event_image,\n draft: false, // Flag to indicate this is not a draft submission\n });\n }}\n >\n Submit Event For Approval\n \n \n ) : (\n {\n // If validation passes, proceed with update\n handleSubmit({ ...form.values, event_image: values.event_image });\n }}\n >\n Update Event\n \n )}\n \n {/* Danger Zone Section */}\n
      \n \n
      \n \n
      \n
      \n );\n}\n","import React, { useState, useEffect } from 'react';\nimport { usePage } from '@inertiajs/react';\nimport { PageProps } from '@inertiajs/core';\nimport { useForm } from '@mantine/form';\nimport {\n Container,\n TextInput,\n MultiSelect,\n Button,\n MantineProvider,\n createTheme,\n Box,\n Paper,\n Title,\n Text,\n Group,\n} from '@mantine/core';\nimport { Notifications, showNotification } from '@mantine/notifications';\nimport { router } from '@inertiajs/react';\n\nimport { IconAlertCircle, IconCheck, IconLink } from '@tabler/icons-react';\nimport { RichTextEditor } from '@mantine/tiptap';\nimport { useEditor } from '@tiptap/react';\nimport Highlight from '@tiptap/extension-highlight';\nimport StarterKit from '@tiptap/starter-kit';\nimport Underline from '@tiptap/extension-underline';\nimport TextAlign from '@tiptap/extension-text-align';\nimport Heading from '@tiptap/extension-heading';\nimport Link from '@tiptap/extension-link';\nimport ImageUploadModal from '../../components/ImageUploadModal';\nimport { useUser, User } from '../../src/context/UserContext';\n\nimport '@mantine/core/styles.css';\nimport '@mantine/notifications/styles.css';\nimport '../../styles/Login-form.css';\nimport '@mantine/tiptap/styles.css';\n\ninterface Artist {\n id: number;\n name: string;\n avatar_url?: string;\n}\n\ninterface Organizer {\n id: number;\n name: string;\n slug: string;\n description: string;\n website_url?: string;\n instagram_url?: string;\n facebook_url?: string;\n organization_image_url?: string;\n organizer_status_id: number;\n artists: Artist[];\n [key: string]: any;\n}\n\ninterface EditOrganizerPageProps extends PageProps {\n organizer: Organizer;\n artists: Artist[];\n errors?: Record;\n}\n\ninterface User {\n id: number;\n roles?: string[];\n [key: string]: any;\n}\n\nconst theme = createTheme({\n primaryColor: 'orange',\n colors: {\n orange: [\n '#FEF5ED',\n '#FDE3D1',\n '#FCB693',\n '#FA9D73',\n '#F87F4D',\n '#F66A33',\n '#EA580C',\n '#C44B0A',\n '#9E3D08',\n '#783006',\n ],\n },\n fontFamily: 'Poppins, sans-serif',\n headings: { fontFamily: 'Poppins, sans-serif' },\n});\n\nexport default function EditOrganizer() {\n const { organizer, artists, errors } = usePage().props;\n const [logoImagePreview, setLogoImagePreview] = useState(organizer.organization_image_url);\n const { user } = useUser() as { user: User | null; refreshUser: () => Promise };\n\n // Check permissions for editing\n const isAuthorized =\n user &&\n (user.roles?.includes('SuperAdmin') || user.roles?.includes('Editor') || organizer.users?.includes(user.id));\n\n // Redirect if not authorized\n useEffect(() => {\n if (!isAuthorized) {\n window.location.href = `/o/${organizer.slug}`;\n }\n }, [isAuthorized, organizer.slug]);\n\n const form = useForm({\n initialValues: {\n name: organizer.name,\n slug: organizer.slug,\n description: organizer.description,\n website_url: organizer.website_url || '',\n facebook_url: organizer.facebook_url || '',\n instagram_url: organizer.instagram_url || '',\n artistIds: organizer.artists.map((artist) => artist.id) || [],\n organization_image: null as File | null,\n },\n validate: {\n name: (value) => (value ? null : 'Name is required'),\n slug: (value) => (value ? null : 'Slug is required'),\n description: (value) => (value ? null : 'Description is required'),\n website_url: (value) => {\n if (!value) return null;\n return value.startsWith('http://') || value.startsWith('https://')\n ? null\n : 'URL must start with http:// or https://';\n },\n facebook_url: (value) => {\n if (!value) return null;\n return value.startsWith('http://') || value.startsWith('https://')\n ? null\n : 'URL must start with http:// or https://';\n },\n instagram_url: (value) => {\n if (!value) return null;\n return value.startsWith('http://') || value.startsWith('https://')\n ? null\n : 'URL must start with http:// or https://';\n },\n },\n });\n\n const handleImageChange = (file: File) => {\n // Update the form state with the new file\n form.setFieldValue('organization_image', file);\n setLogoImagePreview(URL.createObjectURL(file));\n // Update the preview with a new URL\n console.log('Image changed - file stored in form:', file.name);\n };\n\n const editor = useEditor({\n extensions: [\n StarterKit,\n Highlight,\n Underline,\n TextAlign.configure({ types: ['heading', 'paragraph'] }),\n Heading.configure({ levels: [1, 2, 3] }),\n Link.configure({ openOnClick: true }),\n ],\n content: organizer.description,\n onUpdate: ({ editor }) => {\n form.setFieldValue('description', editor.getHTML());\n },\n });\n\n const [isLoading, setIsLoading] = useState(false);\n\n const handleSubmit = async (values: typeof form.values) => {\n console.log('📍 Submitting form with values:', values);\n setIsLoading(true);\n const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content;\n\n console.log('🔐 CSRF Token:', csrfToken);\n\n try {\n const formData = new FormData();\n\n // Add all basic organizer fields\n formData.append('organizer[name]', values.name);\n formData.append('organizer[slug]', values.slug);\n formData.append('organizer[description]', values.description);\n formData.append('organizer[website_url]', values.website_url || '');\n formData.append('organizer[facebook_url]', values.facebook_url || '');\n formData.append('organizer[instagram_url]', values.instagram_url || '');\n\n // Add selected artists\n if (values.artistIds && values.artistIds.length > 0) {\n values.artistIds.forEach((artistId) => {\n formData.append('organizer[artist_ids][]', artistId.toString());\n });\n }\n\n console.log('Form state for debugging:', form.values); // Check what's in the form\n\n // Add organization image if selected\n const logoFile: any = form.values.organization_image;\n if (logoFile instanceof File) {\n console.log('✅ Found organization image File object:', logoFile.name, logoFile.size);\n formData.append('organizer[organization_image]', logoFile);\n } else {\n console.log('❌ No new organization image File object found in form state');\n }\n\n // Send PUT request with CSRF token\n const response = await fetch(`/o/${organizer.slug}`, {\n method: 'PUT',\n headers: {\n Accept: 'application/json',\n 'X-CSRF-Token': csrfToken || '',\n },\n credentials: 'include',\n body: formData,\n });\n\n const data = await response.json().catch(() => ({}));\n\n if (response.ok) {\n showNotification({\n color: 'green',\n title: 'Update Successful',\n position: 'top-right',\n message: 'Organizer was successfully updated!',\n icon: ,\n autoClose: 6000,\n });\n\n // Redirect to the updated organizer page after success\n setTimeout(() => {\n // Use the returned slug from the server if available\n const redirectSlug = data.slug || values.slug;\n window.location.href = `/o/${redirectSlug}`;\n }, 1500);\n } else {\n showNotification({\n color: 'red',\n title: 'Update Failed',\n position: 'top-right',\n message: data.error || 'Something went wrong!',\n icon: ,\n autoClose: 5000,\n });\n\n // Show validation errors if available\n if (data.errors) {\n form.setErrors(data.errors);\n }\n }\n } catch (error) {\n showNotification({\n color: 'red',\n title: 'Error',\n position: 'top-right',\n message: 'An unexpected error occurred',\n icon: ,\n autoClose: 5000,\n });\n console.error('Error updating organizer:', error);\n } finally {\n setIsLoading(false);\n }\n };\n\n // Function to generate a slug from the name\n const generateSlugFromName = (name: string) => {\n if (!name) return '';\n return name\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '') // Remove special characters\n .replace(/\\s+/g, '-') // Replace spaces with hyphens\n .replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen\n .trim();\n };\n\n // Set slug automatically when name changes\n useEffect(() => {\n if (form.values.name) {\n form.setFieldValue('slug', generateSlugFromName(form.values.name));\n }\n }, [form.values.name]);\n\n if (!isAuthorized) {\n return null; // Don't render anything if not authorized\n }\n\n return (\n \n \n \n \n \n Edit Organizer: {organizer.name}\n \n
      \n \n\n \n\n \n\n \n Organization Description\n \n {editor && (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n )}\n\n \n ({\n value: artist.id.toString(),\n label: artist.name,\n }))}\n value={(form.values.artistIds || []).map(String)}\n onChange={(values) => {\n const numericValues = Array.isArray(values) ? values.map(Number) : [];\n form.setFieldValue('artistIds', numericValues);\n }}\n searchable\n clearable\n />\n\n {/* Display selected artist avatars below */}\n {form.values.artistIds.length > 0 && (\n \n {form.values.artistIds.map((id) => {\n const artist = artists.find((a) => a.id === id);\n return artist ? (\n \n \n \n ) : null;\n })}\n \n )}\n \n\n \n }\n />\n \n\n \n }\n />\n \n\n \n }\n />\n \n\n \n \n
      \n
      \n
      \n );\n}\n","import React, { useState, useEffect } from 'react';\nimport { Head, usePage } from '@inertiajs/react';\nimport { PageProps } from '@inertiajs/core';\nimport { useForm } from '@mantine/form';\nimport {\n Container,\n TextInput,\n MultiSelect,\n Button,\n MantineProvider,\n createTheme,\n Box,\n Paper,\n Title,\n Text,\n Group,\n Avatar,\n Stack,\n} from '@mantine/core';\nimport { Notifications, showNotification } from '@mantine/notifications';\nimport { router } from '@inertiajs/react';\n\nimport { IconAlertCircle, IconCheck, IconLink } from '@tabler/icons-react';\nimport { RichTextEditor } from '@mantine/tiptap';\nimport { useEditor } from '@tiptap/react';\nimport Highlight from '@tiptap/extension-highlight';\nimport StarterKit from '@tiptap/starter-kit';\nimport Underline from '@tiptap/extension-underline';\nimport TextAlign from '@tiptap/extension-text-align';\nimport Heading from '@tiptap/extension-heading';\nimport Link from '@tiptap/extension-link';\nimport ImageUploadModal from '../../components/ImageUploadModal';\nimport { useUser } from '../../src/context/UserContext';\n\nimport '@mantine/core/styles.css';\nimport '@mantine/notifications/styles.css';\nimport '../../styles/Login-form.css';\nimport '@mantine/tiptap/styles.css';\n\ninterface Artist {\n id: number;\n name: string;\n avatar_url?: string;\n}\n\ninterface User {\n id: number;\n roles?: string[];\n [key: string]: any;\n}\n\ninterface NewOrganizerPageProps extends PageProps {\n artists: Artist[];\n errors?: Record;\n}\n\nconst theme = createTheme({\n primaryColor: 'orange',\n colors: {\n orange: [\n '#FEF5ED',\n '#FDE3D1',\n '#FCB693',\n '#FA9D73',\n '#F87F4D',\n '#F66A33',\n '#EA580C',\n '#C44B0A',\n '#9E3D08',\n '#783006',\n ],\n },\n fontFamily: 'Poppins, sans-serif',\n headings: { fontFamily: 'Poppins, sans-serif' },\n});\n\nexport default function NewOrganizer() {\n const { artists, errors } = usePage().props;\n const [logoImagePreview, setLogoImagePreview] = useState(null);\n const { user } = useUser() as { user: User | null; refreshUser: () => Promise };\n\n const form = useForm({\n initialValues: {\n name: '',\n slug: '',\n description: '',\n website_url: '',\n facebook_url: '',\n instagram_url: '',\n artistIds: [] as number[],\n organization_image: null as File | null,\n },\n validate: {\n name: (value) => (value ? null : 'Name is required'),\n slug: (value) => (value ? null : 'Slug is required'),\n description: (value) => (value ? null : 'Description is required'),\n website_url: (value) => {\n if (!value) return null;\n return value.startsWith('http://') || value.startsWith('https://')\n ? null\n : 'URL must start with http:// or https://';\n },\n facebook_url: (value) => {\n if (!value) return null;\n return value.startsWith('http://') || value.startsWith('https://')\n ? null\n : 'URL must start with http:// or https://';\n },\n instagram_url: (value) => {\n if (!value) return null;\n return value.startsWith('http://') || value.startsWith('https://')\n ? null\n : 'URL must start with http:// or https://';\n },\n },\n });\n\n const handleImageChange = (file: File) => {\n // Update the form state with the new file\n form.setFieldValue('organization_image', file);\n setLogoImagePreview(URL.createObjectURL(file));\n // Update the preview with a new URL\n console.log('Image changed - file stored in form:', file.name);\n };\n\n const editor = useEditor({\n extensions: [\n StarterKit,\n Highlight,\n Underline,\n TextAlign.configure({ types: ['heading', 'paragraph'] }),\n Heading.configure({ levels: [1, 2, 3] }),\n Link.configure({ openOnClick: true }),\n ],\n content: '',\n onUpdate: ({ editor }) => {\n form.setFieldValue('description', editor.getHTML());\n },\n });\n\n const [isLoading, setIsLoading] = useState(false);\n\n const handleSubmit = async (values: typeof form.values) => {\n console.log('📍 Submitting form with values:', values);\n setIsLoading(true);\n const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content;\n\n console.log('🔐 CSRF Token:', csrfToken);\n\n try {\n const formData = new FormData();\n\n // Add all basic organizer fields\n formData.append('organizer[name]', values.name);\n formData.append('organizer[slug]', values.slug);\n formData.append('organizer[description]', values.description);\n formData.append('organizer[website_url]', values.website_url || '');\n formData.append('organizer[facebook_url]', values.facebook_url || '');\n formData.append('organizer[instagram_url]', values.instagram_url || '');\n\n // Add organizer status as pending\n formData.append('organizer[organizer_status_id]', '1'); // Assuming 1 is the ID for 'pending' status\n\n // Add selected artists\n if (values.artistIds && values.artistIds.length > 0) {\n values.artistIds.forEach((artistId) => {\n formData.append('organizer[artist_ids][]', artistId.toString());\n });\n }\n\n // Add organization image if selected\n const logoFile: any = form.values.organization_image;\n if (logoFile instanceof File) {\n console.log('✅ Found organization image File object:', logoFile.name, logoFile.size);\n formData.append('organizer[organization_image]', logoFile);\n } else {\n console.log('❌ No valid organization image File object found in form state');\n }\n\n // Send POST request with CSRF token\n const response = await fetch('/o', {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'X-CSRF-Token': csrfToken || '',\n },\n credentials: 'include',\n body: formData,\n });\n\n if (response.ok) {\n showNotification({\n color: 'green',\n title: 'Success',\n position: 'top-right',\n message: 'Organizer was successfully created!',\n icon: ,\n autoClose: 6000,\n });\n\n // Redirect to the newly created organizer page after success\n setTimeout(() => {\n window.location.href = `/o/${values.slug}`;\n }, 1500);\n } else {\n const data = await response.json().catch(() => ({}));\n showNotification({\n color: 'red',\n title: 'Creation Failed',\n position: 'top-right',\n message: data.error || 'Something went wrong!',\n icon: ,\n autoClose: 5000,\n });\n\n // Show validation errors if available\n if (data.errors) {\n form.setErrors(data.errors);\n }\n }\n } catch (error) {\n showNotification({\n color: 'red',\n title: 'Error',\n position: 'top-right',\n message: 'An unexpected error occurred',\n icon: ,\n autoClose: 5000,\n });\n console.error('Error creating organizer:', error);\n } finally {\n setIsLoading(false);\n }\n };\n\n // Function to generate a slug from the name\n const generateSlugFromName = (name: string) => {\n if (!name) return '';\n return name\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '') // Remove special characters\n .replace(/\\s+/g, '-') // Replace spaces with hyphens\n .replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen\n .trim();\n };\n\n // Set slug automatically when name changes\n useEffect(() => {\n if (form.values.name) {\n form.setFieldValue('slug', generateSlugFromName(form.values.name));\n }\n }, [form.values.name]);\n\n return (\n \n \n \n \n \n Add New Organizer\n \n
      \n \n\n \n\n \n\n \n Organization Description\n \n {editor && (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n )}\n\n \n ({\n value: artist.id.toString(),\n label: artist.name,\n }))}\n value={(form.values.artistIds || []).map(String)}\n onChange={(values) => {\n const numericValues = Array.isArray(values) ? values.map(Number) : [];\n form.setFieldValue('artistIds', numericValues);\n }}\n searchable\n clearable\n />\n\n {/* Display selected artist avatars below */}\n {form.values.artistIds.length > 0 && (\n \n \n {form.values.artistIds.map((id) => {\n const artist = artists.find((a) => a.id === id);\n return artist ? (\n \n ) : null;\n })}\n \n \n )}\n \n\n \n }\n />\n \n\n \n }\n />\n \n\n \n }\n />\n \n\n \n \n
      \n
      \n
      \n );\n}\n","import React, { useState, useMemo } from 'react';\nimport {\n Container,\n Title,\n Button,\n Card,\n Text,\n Group,\n SimpleGrid,\n ActionIcon,\n Stack,\n MantineProvider,\n TextInput,\n Pagination,\n Box,\n} from '@mantine/core';\nimport { Link } from '@inertiajs/react';\nimport {\n IconPlus,\n IconWorld,\n IconBrandFacebook,\n IconBrandInstagram,\n IconArrowRight,\n IconSearch,\n} from '@tabler/icons-react';\n\ninterface Organizer {\n id: number;\n name: string;\n description: string;\n website_url?: string;\n facebook_url?: string;\n instagram_url?: string;\n slug: string;\n created_at: string;\n}\n\ninterface OrganizerIndexProps {\n organizers: Organizer[];\n}\n\nconst OrganizerIndex: React.FC = ({ organizers }) => {\n // State for search and pagination\n const [searchQuery, setSearchQuery] = useState('');\n const [currentPage, setCurrentPage] = useState(1);\n const ITEMS_PER_PAGE = 12; // 3 columns x 3 rows\n\n // Filter and sort organizers\n const filteredAndSortedOrganizers = useMemo(() => {\n return [...organizers]\n .filter(\n (organizer) =>\n organizer.name.toLowerCase().includes(searchQuery.toLowerCase()) ||\n (organizer.description && organizer.description.toLowerCase().includes(searchQuery.toLowerCase())),\n )\n .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());\n }, [organizers, searchQuery]);\n\n // Calculate pagination\n const totalPages = Math.ceil(filteredAndSortedOrganizers.length / ITEMS_PER_PAGE);\n\n // Get current page items\n const currentOrganizers = useMemo(() => {\n const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;\n return filteredAndSortedOrganizers.slice(startIndex, startIndex + ITEMS_PER_PAGE);\n }, [filteredAndSortedOrganizers, currentPage]);\n\n // Reset to first page when search changes\n React.useEffect(() => {\n setCurrentPage(1);\n }, [searchQuery]);\n\n return (\n \n \n \n Organizers\n \n\n \n setSearchQuery(e.currentTarget.value)}\n leftSection={}\n style={{ flexGrow: 1 }}\n styles={{\n input: {\n backgroundColor: '#2c2c2c',\n color: '#f2f2f2',\n borderColor: '#EA580C',\n },\n label: {\n color: '#f2f2f2',\n },\n }}\n className=\"poppins\"\n />\n\n }\n color=\"#EA580C\"\n className=\"poppins\"\n >\n Add New Organizer\n \n \n\n {totalPages > 1 && (\n \n \n \n )}\n\n \n Showing {currentOrganizers.length} of {filteredAndSortedOrganizers.length} organizers\n \n\n \n {currentOrganizers.map((organizer) => (\n \n \n
      \n \n <Link\n href={`/o/${organizer.slug}`}\n style={{\n color: '#f2f2f2',\n textDecoration: 'none',\n }}\n >\n {organizer.name}\n </Link>\n \n\n \n {organizer.description}\n \n
      \n\n
      \n \n {organizer.website_url && (\n \n \n \n )}\n\n {organizer.facebook_url && (\n \n \n \n )}\n\n {organizer.instagram_url && (\n \n \n \n )}\n\n \n \n \n \n
      \n
      \n \n ))}\n
      \n\n {totalPages > 1 && (\n \n \n \n )}\n\n \n Showing {currentOrganizers.length} of {filteredAndSortedOrganizers.length} organizers\n \n
      \n
      \n );\n};\n\nexport default OrganizerIndex;\n","'use strict';\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar React = require('react');\nvar React__default = _interopDefault(React);\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\nfunction withSideEffect(reducePropsToState, handleStateChangeOnClient, mapStateOnServer) {\n if (typeof reducePropsToState !== 'function') {\n throw new Error('Expected reducePropsToState to be a function.');\n }\n\n if (typeof handleStateChangeOnClient !== 'function') {\n throw new Error('Expected handleStateChangeOnClient to be a function.');\n }\n\n if (typeof mapStateOnServer !== 'undefined' && typeof mapStateOnServer !== 'function') {\n throw new Error('Expected mapStateOnServer to either be undefined or a function.');\n }\n\n function getDisplayName(WrappedComponent) {\n return WrappedComponent.displayName || WrappedComponent.name || 'Component';\n }\n\n return function wrap(WrappedComponent) {\n if (typeof WrappedComponent !== 'function') {\n throw new Error('Expected WrappedComponent to be a React component.');\n }\n\n var mountedInstances = [];\n var state;\n\n function emitChange() {\n state = reducePropsToState(mountedInstances.map(function (instance) {\n return instance.props;\n }));\n\n if (SideEffect.canUseDOM) {\n handleStateChangeOnClient(state);\n } else if (mapStateOnServer) {\n state = mapStateOnServer(state);\n }\n }\n\n var SideEffect =\n /*#__PURE__*/\n function (_PureComponent) {\n _inheritsLoose(SideEffect, _PureComponent);\n\n function SideEffect() {\n return _PureComponent.apply(this, arguments) || this;\n }\n\n // Try to use displayName of wrapped component\n // Expose canUseDOM so tests can monkeypatch it\n SideEffect.peek = function peek() {\n return state;\n };\n\n SideEffect.rewind = function rewind() {\n if (SideEffect.canUseDOM) {\n throw new Error('You may only call rewind() on the server. Call peek() to read the current state.');\n }\n\n var recordedState = state;\n state = undefined;\n mountedInstances = [];\n return recordedState;\n };\n\n var _proto = SideEffect.prototype;\n\n _proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() {\n mountedInstances.push(this);\n emitChange();\n };\n\n _proto.componentDidUpdate = function componentDidUpdate() {\n emitChange();\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n var index = mountedInstances.indexOf(this);\n mountedInstances.splice(index, 1);\n emitChange();\n };\n\n _proto.render = function render() {\n return React__default.createElement(WrappedComponent, this.props);\n };\n\n return SideEffect;\n }(React.PureComponent);\n\n _defineProperty(SideEffect, \"displayName\", \"SideEffect(\" + getDisplayName(WrappedComponent) + \")\");\n\n _defineProperty(SideEffect, \"canUseDOM\", canUseDOM);\n\n return SideEffect;\n };\n}\n\nmodule.exports = withSideEffect;\n","/* global Map:readonly, Set:readonly, ArrayBuffer:readonly */\n\nvar hasElementType = typeof Element !== 'undefined';\nvar hasMap = typeof Map === 'function';\nvar hasSet = typeof Set === 'function';\nvar hasArrayBuffer = typeof ArrayBuffer === 'function' && !!ArrayBuffer.isView;\n\n// Note: We **don't** need `envHasBigInt64Array` in fde es6/index.js\n\nfunction equal(a, b) {\n // START: fast-deep-equal es6/index.js 3.1.3\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n // START: Modifications:\n // 1. Extra `has &&` helpers in initial condition allow es6 code\n // to co-exist with es5.\n // 2. Replace `for of` with es5 compliant iteration using `for`.\n // Basically, take:\n //\n // ```js\n // for (i of a.entries())\n // if (!b.has(i[0])) return false;\n // ```\n //\n // ... and convert to:\n //\n // ```js\n // it = a.entries();\n // while (!(i = it.next()).done)\n // if (!b.has(i.value[0])) return false;\n // ```\n //\n // **Note**: `i` access switches to `i.value`.\n var it;\n if (hasMap && (a instanceof Map) && (b instanceof Map)) {\n if (a.size !== b.size) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!b.has(i.value[0])) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!equal(i.value[1], b.get(i.value[0]))) return false;\n return true;\n }\n\n if (hasSet && (a instanceof Set) && (b instanceof Set)) {\n if (a.size !== b.size) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!b.has(i.value[0])) return false;\n return true;\n }\n // END: Modifications\n\n if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (a[i] !== b[i]) return false;\n return true;\n }\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n // START: Modifications:\n // Apply guards for `Object.create(null)` handling. See:\n // - https://github.com/FormidableLabs/react-fast-compare/issues/64\n // - https://github.com/epoberezkin/fast-deep-equal/issues/49\n if (a.valueOf !== Object.prototype.valueOf && typeof a.valueOf === 'function' && typeof b.valueOf === 'function') return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString && typeof a.toString === 'function' && typeof b.toString === 'function') return a.toString() === b.toString();\n // END: Modifications\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n // END: fast-deep-equal\n\n // START: react-fast-compare\n // custom handling for DOM elements\n if (hasElementType && a instanceof Element) return false;\n\n // custom handling for React/Preact\n for (i = length; i-- !== 0;) {\n if ((keys[i] === '_owner' || keys[i] === '__v' || keys[i] === '__o') && a.$$typeof) {\n // React-specific: avoid traversing React elements' _owner\n // Preact-specific: avoid traversing Preact elements' __v and __o\n // __v = $_original / $_vnode\n // __o = $_owner\n // These properties contain circular references and are not needed when\n // comparing the actual elements (and not their owners)\n // .$$typeof and ._store on just reasonable markers of elements\n\n continue;\n }\n\n // all other properties should be traversed as usual\n if (!equal(a[keys[i]], b[keys[i]])) return false;\n }\n // END: react-fast-compare\n\n // START: fast-deep-equal\n return true;\n }\n\n return a !== a && b !== b;\n}\n// end fast-deep-equal\n\nmodule.exports = function isEqual(a, b) {\n try {\n return equal(a, b);\n } catch (error) {\n if (((error.message || '').match(/stack|recursion/i))) {\n // warn on circular references, don't crash\n // browsers give this different errors name and messages:\n // chrome/safari: \"RangeError\", \"Maximum call stack size exceeded\"\n // firefox: \"InternalError\", too much recursion\"\n // edge: \"Error\", \"Out of stack space\"\n console.warn('react-fast-compare cannot handle circular refs');\n return false;\n }\n // some other error. we should definitely know about these\n throw error;\n }\n};\n","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n","import PropTypes from 'prop-types';\nimport withSideEffect from 'react-side-effect';\nimport isEqual from 'react-fast-compare';\nimport React from 'react';\nimport objectAssign from 'object-assign';\n\nvar ATTRIBUTE_NAMES = {\n BODY: \"bodyAttributes\",\n HTML: \"htmlAttributes\",\n TITLE: \"titleAttributes\"\n};\n\nvar TAG_NAMES = {\n BASE: \"base\",\n BODY: \"body\",\n HEAD: \"head\",\n HTML: \"html\",\n LINK: \"link\",\n META: \"meta\",\n NOSCRIPT: \"noscript\",\n SCRIPT: \"script\",\n STYLE: \"style\",\n TITLE: \"title\"\n};\n\nvar VALID_TAG_NAMES = Object.keys(TAG_NAMES).map(function (name) {\n return TAG_NAMES[name];\n});\n\nvar TAG_PROPERTIES = {\n CHARSET: \"charset\",\n CSS_TEXT: \"cssText\",\n HREF: \"href\",\n HTTPEQUIV: \"http-equiv\",\n INNER_HTML: \"innerHTML\",\n ITEM_PROP: \"itemprop\",\n NAME: \"name\",\n PROPERTY: \"property\",\n REL: \"rel\",\n SRC: \"src\",\n TARGET: \"target\"\n};\n\nvar REACT_TAG_MAP = {\n accesskey: \"accessKey\",\n charset: \"charSet\",\n class: \"className\",\n contenteditable: \"contentEditable\",\n contextmenu: \"contextMenu\",\n \"http-equiv\": \"httpEquiv\",\n itemprop: \"itemProp\",\n tabindex: \"tabIndex\"\n};\n\nvar HELMET_PROPS = {\n DEFAULT_TITLE: \"defaultTitle\",\n DEFER: \"defer\",\n ENCODE_SPECIAL_CHARACTERS: \"encodeSpecialCharacters\",\n ON_CHANGE_CLIENT_STATE: \"onChangeClientState\",\n TITLE_TEMPLATE: \"titleTemplate\"\n};\n\nvar HTML_TAG_MAP = Object.keys(REACT_TAG_MAP).reduce(function (obj, key) {\n obj[REACT_TAG_MAP[key]] = key;\n return obj;\n}, {});\n\nvar SELF_CLOSING_TAGS = [TAG_NAMES.NOSCRIPT, TAG_NAMES.SCRIPT, TAG_NAMES.STYLE];\n\nvar HELMET_ATTRIBUTE = \"data-react-helmet\";\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n} : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\nvar classCallCheck = function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n};\n\nvar createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n}();\n\nvar _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nvar inherits = function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n};\n\nvar objectWithoutProperties = function (obj, keys) {\n var target = {};\n\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n\n return target;\n};\n\nvar possibleConstructorReturn = function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n};\n\nvar encodeSpecialCharacters = function encodeSpecialCharacters(str) {\n var encode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\n if (encode === false) {\n return String(str);\n }\n\n return String(str).replace(/&/g, \"&\").replace(//g, \">\").replace(/\"/g, \""\").replace(/'/g, \"'\");\n};\n\nvar getTitleFromPropsList = function getTitleFromPropsList(propsList) {\n var innermostTitle = getInnermostProperty(propsList, TAG_NAMES.TITLE);\n var innermostTemplate = getInnermostProperty(propsList, HELMET_PROPS.TITLE_TEMPLATE);\n\n if (innermostTemplate && innermostTitle) {\n // use function arg to avoid need to escape $ characters\n return innermostTemplate.replace(/%s/g, function () {\n return Array.isArray(innermostTitle) ? innermostTitle.join(\"\") : innermostTitle;\n });\n }\n\n var innermostDefaultTitle = getInnermostProperty(propsList, HELMET_PROPS.DEFAULT_TITLE);\n\n return innermostTitle || innermostDefaultTitle || undefined;\n};\n\nvar getOnChangeClientState = function getOnChangeClientState(propsList) {\n return getInnermostProperty(propsList, HELMET_PROPS.ON_CHANGE_CLIENT_STATE) || function () {};\n};\n\nvar getAttributesFromPropsList = function getAttributesFromPropsList(tagType, propsList) {\n return propsList.filter(function (props) {\n return typeof props[tagType] !== \"undefined\";\n }).map(function (props) {\n return props[tagType];\n }).reduce(function (tagAttrs, current) {\n return _extends({}, tagAttrs, current);\n }, {});\n};\n\nvar getBaseTagFromPropsList = function getBaseTagFromPropsList(primaryAttributes, propsList) {\n return propsList.filter(function (props) {\n return typeof props[TAG_NAMES.BASE] !== \"undefined\";\n }).map(function (props) {\n return props[TAG_NAMES.BASE];\n }).reverse().reduce(function (innermostBaseTag, tag) {\n if (!innermostBaseTag.length) {\n var keys = Object.keys(tag);\n\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var lowerCaseAttributeKey = attributeKey.toLowerCase();\n\n if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && tag[lowerCaseAttributeKey]) {\n return innermostBaseTag.concat(tag);\n }\n }\n }\n\n return innermostBaseTag;\n }, []);\n};\n\nvar getTagsFromPropsList = function getTagsFromPropsList(tagName, primaryAttributes, propsList) {\n // Calculate list of tags, giving priority innermost component (end of the propslist)\n var approvedSeenTags = {};\n\n return propsList.filter(function (props) {\n if (Array.isArray(props[tagName])) {\n return true;\n }\n if (typeof props[tagName] !== \"undefined\") {\n warn(\"Helmet: \" + tagName + \" should be of type \\\"Array\\\". Instead found type \\\"\" + _typeof(props[tagName]) + \"\\\"\");\n }\n return false;\n }).map(function (props) {\n return props[tagName];\n }).reverse().reduce(function (approvedTags, instanceTags) {\n var instanceSeenTags = {};\n\n instanceTags.filter(function (tag) {\n var primaryAttributeKey = void 0;\n var keys = Object.keys(tag);\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var lowerCaseAttributeKey = attributeKey.toLowerCase();\n\n // Special rule with link tags, since rel and href are both primary tags, rel takes priority\n if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && !(primaryAttributeKey === TAG_PROPERTIES.REL && tag[primaryAttributeKey].toLowerCase() === \"canonical\") && !(lowerCaseAttributeKey === TAG_PROPERTIES.REL && tag[lowerCaseAttributeKey].toLowerCase() === \"stylesheet\")) {\n primaryAttributeKey = lowerCaseAttributeKey;\n }\n // Special case for innerHTML which doesn't work lowercased\n if (primaryAttributes.indexOf(attributeKey) !== -1 && (attributeKey === TAG_PROPERTIES.INNER_HTML || attributeKey === TAG_PROPERTIES.CSS_TEXT || attributeKey === TAG_PROPERTIES.ITEM_PROP)) {\n primaryAttributeKey = attributeKey;\n }\n }\n\n if (!primaryAttributeKey || !tag[primaryAttributeKey]) {\n return false;\n }\n\n var value = tag[primaryAttributeKey].toLowerCase();\n\n if (!approvedSeenTags[primaryAttributeKey]) {\n approvedSeenTags[primaryAttributeKey] = {};\n }\n\n if (!instanceSeenTags[primaryAttributeKey]) {\n instanceSeenTags[primaryAttributeKey] = {};\n }\n\n if (!approvedSeenTags[primaryAttributeKey][value]) {\n instanceSeenTags[primaryAttributeKey][value] = true;\n return true;\n }\n\n return false;\n }).reverse().forEach(function (tag) {\n return approvedTags.push(tag);\n });\n\n // Update seen tags with tags from this instance\n var keys = Object.keys(instanceSeenTags);\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var tagUnion = objectAssign({}, approvedSeenTags[attributeKey], instanceSeenTags[attributeKey]);\n\n approvedSeenTags[attributeKey] = tagUnion;\n }\n\n return approvedTags;\n }, []).reverse();\n};\n\nvar getInnermostProperty = function getInnermostProperty(propsList, property) {\n for (var i = propsList.length - 1; i >= 0; i--) {\n var props = propsList[i];\n\n if (props.hasOwnProperty(property)) {\n return props[property];\n }\n }\n\n return null;\n};\n\nvar reducePropsToState = function reducePropsToState(propsList) {\n return {\n baseTag: getBaseTagFromPropsList([TAG_PROPERTIES.HREF, TAG_PROPERTIES.TARGET], propsList),\n bodyAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.BODY, propsList),\n defer: getInnermostProperty(propsList, HELMET_PROPS.DEFER),\n encode: getInnermostProperty(propsList, HELMET_PROPS.ENCODE_SPECIAL_CHARACTERS),\n htmlAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.HTML, propsList),\n linkTags: getTagsFromPropsList(TAG_NAMES.LINK, [TAG_PROPERTIES.REL, TAG_PROPERTIES.HREF], propsList),\n metaTags: getTagsFromPropsList(TAG_NAMES.META, [TAG_PROPERTIES.NAME, TAG_PROPERTIES.CHARSET, TAG_PROPERTIES.HTTPEQUIV, TAG_PROPERTIES.PROPERTY, TAG_PROPERTIES.ITEM_PROP], propsList),\n noscriptTags: getTagsFromPropsList(TAG_NAMES.NOSCRIPT, [TAG_PROPERTIES.INNER_HTML], propsList),\n onChangeClientState: getOnChangeClientState(propsList),\n scriptTags: getTagsFromPropsList(TAG_NAMES.SCRIPT, [TAG_PROPERTIES.SRC, TAG_PROPERTIES.INNER_HTML], propsList),\n styleTags: getTagsFromPropsList(TAG_NAMES.STYLE, [TAG_PROPERTIES.CSS_TEXT], propsList),\n title: getTitleFromPropsList(propsList),\n titleAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.TITLE, propsList)\n };\n};\n\nvar rafPolyfill = function () {\n var clock = Date.now();\n\n return function (callback) {\n var currentTime = Date.now();\n\n if (currentTime - clock > 16) {\n clock = currentTime;\n callback(currentTime);\n } else {\n setTimeout(function () {\n rafPolyfill(callback);\n }, 0);\n }\n };\n}();\n\nvar cafPolyfill = function cafPolyfill(id) {\n return clearTimeout(id);\n};\n\nvar requestAnimationFrame = typeof window !== \"undefined\" ? window.requestAnimationFrame && window.requestAnimationFrame.bind(window) || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || rafPolyfill : global.requestAnimationFrame || rafPolyfill;\n\nvar cancelAnimationFrame = typeof window !== \"undefined\" ? window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || cafPolyfill : global.cancelAnimationFrame || cafPolyfill;\n\nvar warn = function warn(msg) {\n return console && typeof console.warn === \"function\" && console.warn(msg);\n};\n\nvar _helmetCallback = null;\n\nvar handleClientStateChange = function handleClientStateChange(newState) {\n if (_helmetCallback) {\n cancelAnimationFrame(_helmetCallback);\n }\n\n if (newState.defer) {\n _helmetCallback = requestAnimationFrame(function () {\n commitTagChanges(newState, function () {\n _helmetCallback = null;\n });\n });\n } else {\n commitTagChanges(newState);\n _helmetCallback = null;\n }\n};\n\nvar commitTagChanges = function commitTagChanges(newState, cb) {\n var baseTag = newState.baseTag,\n bodyAttributes = newState.bodyAttributes,\n htmlAttributes = newState.htmlAttributes,\n linkTags = newState.linkTags,\n metaTags = newState.metaTags,\n noscriptTags = newState.noscriptTags,\n onChangeClientState = newState.onChangeClientState,\n scriptTags = newState.scriptTags,\n styleTags = newState.styleTags,\n title = newState.title,\n titleAttributes = newState.titleAttributes;\n\n updateAttributes(TAG_NAMES.BODY, bodyAttributes);\n updateAttributes(TAG_NAMES.HTML, htmlAttributes);\n\n updateTitle(title, titleAttributes);\n\n var tagUpdates = {\n baseTag: updateTags(TAG_NAMES.BASE, baseTag),\n linkTags: updateTags(TAG_NAMES.LINK, linkTags),\n metaTags: updateTags(TAG_NAMES.META, metaTags),\n noscriptTags: updateTags(TAG_NAMES.NOSCRIPT, noscriptTags),\n scriptTags: updateTags(TAG_NAMES.SCRIPT, scriptTags),\n styleTags: updateTags(TAG_NAMES.STYLE, styleTags)\n };\n\n var addedTags = {};\n var removedTags = {};\n\n Object.keys(tagUpdates).forEach(function (tagType) {\n var _tagUpdates$tagType = tagUpdates[tagType],\n newTags = _tagUpdates$tagType.newTags,\n oldTags = _tagUpdates$tagType.oldTags;\n\n\n if (newTags.length) {\n addedTags[tagType] = newTags;\n }\n if (oldTags.length) {\n removedTags[tagType] = tagUpdates[tagType].oldTags;\n }\n });\n\n cb && cb();\n\n onChangeClientState(newState, addedTags, removedTags);\n};\n\nvar flattenArray = function flattenArray(possibleArray) {\n return Array.isArray(possibleArray) ? possibleArray.join(\"\") : possibleArray;\n};\n\nvar updateTitle = function updateTitle(title, attributes) {\n if (typeof title !== \"undefined\" && document.title !== title) {\n document.title = flattenArray(title);\n }\n\n updateAttributes(TAG_NAMES.TITLE, attributes);\n};\n\nvar updateAttributes = function updateAttributes(tagName, attributes) {\n var elementTag = document.getElementsByTagName(tagName)[0];\n\n if (!elementTag) {\n return;\n }\n\n var helmetAttributeString = elementTag.getAttribute(HELMET_ATTRIBUTE);\n var helmetAttributes = helmetAttributeString ? helmetAttributeString.split(\",\") : [];\n var attributesToRemove = [].concat(helmetAttributes);\n var attributeKeys = Object.keys(attributes);\n\n for (var i = 0; i < attributeKeys.length; i++) {\n var attribute = attributeKeys[i];\n var value = attributes[attribute] || \"\";\n\n if (elementTag.getAttribute(attribute) !== value) {\n elementTag.setAttribute(attribute, value);\n }\n\n if (helmetAttributes.indexOf(attribute) === -1) {\n helmetAttributes.push(attribute);\n }\n\n var indexToSave = attributesToRemove.indexOf(attribute);\n if (indexToSave !== -1) {\n attributesToRemove.splice(indexToSave, 1);\n }\n }\n\n for (var _i = attributesToRemove.length - 1; _i >= 0; _i--) {\n elementTag.removeAttribute(attributesToRemove[_i]);\n }\n\n if (helmetAttributes.length === attributesToRemove.length) {\n elementTag.removeAttribute(HELMET_ATTRIBUTE);\n } else if (elementTag.getAttribute(HELMET_ATTRIBUTE) !== attributeKeys.join(\",\")) {\n elementTag.setAttribute(HELMET_ATTRIBUTE, attributeKeys.join(\",\"));\n }\n};\n\nvar updateTags = function updateTags(type, tags) {\n var headElement = document.head || document.querySelector(TAG_NAMES.HEAD);\n var tagNodes = headElement.querySelectorAll(type + \"[\" + HELMET_ATTRIBUTE + \"]\");\n var oldTags = Array.prototype.slice.call(tagNodes);\n var newTags = [];\n var indexToDelete = void 0;\n\n if (tags && tags.length) {\n tags.forEach(function (tag) {\n var newElement = document.createElement(type);\n\n for (var attribute in tag) {\n if (tag.hasOwnProperty(attribute)) {\n if (attribute === TAG_PROPERTIES.INNER_HTML) {\n newElement.innerHTML = tag.innerHTML;\n } else if (attribute === TAG_PROPERTIES.CSS_TEXT) {\n if (newElement.styleSheet) {\n newElement.styleSheet.cssText = tag.cssText;\n } else {\n newElement.appendChild(document.createTextNode(tag.cssText));\n }\n } else {\n var value = typeof tag[attribute] === \"undefined\" ? \"\" : tag[attribute];\n newElement.setAttribute(attribute, value);\n }\n }\n }\n\n newElement.setAttribute(HELMET_ATTRIBUTE, \"true\");\n\n // Remove a duplicate tag from domTagstoRemove, so it isn't cleared.\n if (oldTags.some(function (existingTag, index) {\n indexToDelete = index;\n return newElement.isEqualNode(existingTag);\n })) {\n oldTags.splice(indexToDelete, 1);\n } else {\n newTags.push(newElement);\n }\n });\n }\n\n oldTags.forEach(function (tag) {\n return tag.parentNode.removeChild(tag);\n });\n newTags.forEach(function (tag) {\n return headElement.appendChild(tag);\n });\n\n return {\n oldTags: oldTags,\n newTags: newTags\n };\n};\n\nvar generateElementAttributesAsString = function generateElementAttributesAsString(attributes) {\n return Object.keys(attributes).reduce(function (str, key) {\n var attr = typeof attributes[key] !== \"undefined\" ? key + \"=\\\"\" + attributes[key] + \"\\\"\" : \"\" + key;\n return str ? str + \" \" + attr : attr;\n }, \"\");\n};\n\nvar generateTitleAsString = function generateTitleAsString(type, title, attributes, encode) {\n var attributeString = generateElementAttributesAsString(attributes);\n var flattenedTitle = flattenArray(title);\n return attributeString ? \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\" \" + attributeString + \">\" + encodeSpecialCharacters(flattenedTitle, encode) + \"\" : \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\">\" + encodeSpecialCharacters(flattenedTitle, encode) + \"\";\n};\n\nvar generateTagsAsString = function generateTagsAsString(type, tags, encode) {\n return tags.reduce(function (str, tag) {\n var attributeHtml = Object.keys(tag).filter(function (attribute) {\n return !(attribute === TAG_PROPERTIES.INNER_HTML || attribute === TAG_PROPERTIES.CSS_TEXT);\n }).reduce(function (string, attribute) {\n var attr = typeof tag[attribute] === \"undefined\" ? attribute : attribute + \"=\\\"\" + encodeSpecialCharacters(tag[attribute], encode) + \"\\\"\";\n return string ? string + \" \" + attr : attr;\n }, \"\");\n\n var tagContent = tag.innerHTML || tag.cssText || \"\";\n\n var isSelfClosing = SELF_CLOSING_TAGS.indexOf(type) === -1;\n\n return str + \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\" \" + attributeHtml + (isSelfClosing ? \"/>\" : \">\" + tagContent + \"\");\n }, \"\");\n};\n\nvar convertElementAttributestoReactProps = function convertElementAttributestoReactProps(attributes) {\n var initProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n return Object.keys(attributes).reduce(function (obj, key) {\n obj[REACT_TAG_MAP[key] || key] = attributes[key];\n return obj;\n }, initProps);\n};\n\nvar convertReactPropstoHtmlAttributes = function convertReactPropstoHtmlAttributes(props) {\n var initAttributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n return Object.keys(props).reduce(function (obj, key) {\n obj[HTML_TAG_MAP[key] || key] = props[key];\n return obj;\n }, initAttributes);\n};\n\nvar generateTitleAsReactComponent = function generateTitleAsReactComponent(type, title, attributes) {\n var _initProps;\n\n // assigning into an array to define toString function on it\n var initProps = (_initProps = {\n key: title\n }, _initProps[HELMET_ATTRIBUTE] = true, _initProps);\n var props = convertElementAttributestoReactProps(attributes, initProps);\n\n return [React.createElement(TAG_NAMES.TITLE, props, title)];\n};\n\nvar generateTagsAsReactComponent = function generateTagsAsReactComponent(type, tags) {\n return tags.map(function (tag, i) {\n var _mappedTag;\n\n var mappedTag = (_mappedTag = {\n key: i\n }, _mappedTag[HELMET_ATTRIBUTE] = true, _mappedTag);\n\n Object.keys(tag).forEach(function (attribute) {\n var mappedAttribute = REACT_TAG_MAP[attribute] || attribute;\n\n if (mappedAttribute === TAG_PROPERTIES.INNER_HTML || mappedAttribute === TAG_PROPERTIES.CSS_TEXT) {\n var content = tag.innerHTML || tag.cssText;\n mappedTag.dangerouslySetInnerHTML = { __html: content };\n } else {\n mappedTag[mappedAttribute] = tag[attribute];\n }\n });\n\n return React.createElement(type, mappedTag);\n });\n};\n\nvar getMethodsForTag = function getMethodsForTag(type, tags, encode) {\n switch (type) {\n case TAG_NAMES.TITLE:\n return {\n toComponent: function toComponent() {\n return generateTitleAsReactComponent(type, tags.title, tags.titleAttributes, encode);\n },\n toString: function toString() {\n return generateTitleAsString(type, tags.title, tags.titleAttributes, encode);\n }\n };\n case ATTRIBUTE_NAMES.BODY:\n case ATTRIBUTE_NAMES.HTML:\n return {\n toComponent: function toComponent() {\n return convertElementAttributestoReactProps(tags);\n },\n toString: function toString() {\n return generateElementAttributesAsString(tags);\n }\n };\n default:\n return {\n toComponent: function toComponent() {\n return generateTagsAsReactComponent(type, tags);\n },\n toString: function toString() {\n return generateTagsAsString(type, tags, encode);\n }\n };\n }\n};\n\nvar mapStateOnServer = function mapStateOnServer(_ref) {\n var baseTag = _ref.baseTag,\n bodyAttributes = _ref.bodyAttributes,\n encode = _ref.encode,\n htmlAttributes = _ref.htmlAttributes,\n linkTags = _ref.linkTags,\n metaTags = _ref.metaTags,\n noscriptTags = _ref.noscriptTags,\n scriptTags = _ref.scriptTags,\n styleTags = _ref.styleTags,\n _ref$title = _ref.title,\n title = _ref$title === undefined ? \"\" : _ref$title,\n titleAttributes = _ref.titleAttributes;\n return {\n base: getMethodsForTag(TAG_NAMES.BASE, baseTag, encode),\n bodyAttributes: getMethodsForTag(ATTRIBUTE_NAMES.BODY, bodyAttributes, encode),\n htmlAttributes: getMethodsForTag(ATTRIBUTE_NAMES.HTML, htmlAttributes, encode),\n link: getMethodsForTag(TAG_NAMES.LINK, linkTags, encode),\n meta: getMethodsForTag(TAG_NAMES.META, metaTags, encode),\n noscript: getMethodsForTag(TAG_NAMES.NOSCRIPT, noscriptTags, encode),\n script: getMethodsForTag(TAG_NAMES.SCRIPT, scriptTags, encode),\n style: getMethodsForTag(TAG_NAMES.STYLE, styleTags, encode),\n title: getMethodsForTag(TAG_NAMES.TITLE, { title: title, titleAttributes: titleAttributes }, encode)\n };\n};\n\nvar Helmet = function Helmet(Component) {\n var _class, _temp;\n\n return _temp = _class = function (_React$Component) {\n inherits(HelmetWrapper, _React$Component);\n\n function HelmetWrapper() {\n classCallCheck(this, HelmetWrapper);\n return possibleConstructorReturn(this, _React$Component.apply(this, arguments));\n }\n\n HelmetWrapper.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {\n return !isEqual(this.props, nextProps);\n };\n\n HelmetWrapper.prototype.mapNestedChildrenToProps = function mapNestedChildrenToProps(child, nestedChildren) {\n if (!nestedChildren) {\n return null;\n }\n\n switch (child.type) {\n case TAG_NAMES.SCRIPT:\n case TAG_NAMES.NOSCRIPT:\n return {\n innerHTML: nestedChildren\n };\n\n case TAG_NAMES.STYLE:\n return {\n cssText: nestedChildren\n };\n }\n\n throw new Error(\"<\" + child.type + \" /> elements are self-closing and can not contain children. Refer to our API for more information.\");\n };\n\n HelmetWrapper.prototype.flattenArrayTypeChildren = function flattenArrayTypeChildren(_ref) {\n var _babelHelpers$extends;\n\n var child = _ref.child,\n arrayTypeChildren = _ref.arrayTypeChildren,\n newChildProps = _ref.newChildProps,\n nestedChildren = _ref.nestedChildren;\n\n return _extends({}, arrayTypeChildren, (_babelHelpers$extends = {}, _babelHelpers$extends[child.type] = [].concat(arrayTypeChildren[child.type] || [], [_extends({}, newChildProps, this.mapNestedChildrenToProps(child, nestedChildren))]), _babelHelpers$extends));\n };\n\n HelmetWrapper.prototype.mapObjectTypeChildren = function mapObjectTypeChildren(_ref2) {\n var _babelHelpers$extends2, _babelHelpers$extends3;\n\n var child = _ref2.child,\n newProps = _ref2.newProps,\n newChildProps = _ref2.newChildProps,\n nestedChildren = _ref2.nestedChildren;\n\n switch (child.type) {\n case TAG_NAMES.TITLE:\n return _extends({}, newProps, (_babelHelpers$extends2 = {}, _babelHelpers$extends2[child.type] = nestedChildren, _babelHelpers$extends2.titleAttributes = _extends({}, newChildProps), _babelHelpers$extends2));\n\n case TAG_NAMES.BODY:\n return _extends({}, newProps, {\n bodyAttributes: _extends({}, newChildProps)\n });\n\n case TAG_NAMES.HTML:\n return _extends({}, newProps, {\n htmlAttributes: _extends({}, newChildProps)\n });\n }\n\n return _extends({}, newProps, (_babelHelpers$extends3 = {}, _babelHelpers$extends3[child.type] = _extends({}, newChildProps), _babelHelpers$extends3));\n };\n\n HelmetWrapper.prototype.mapArrayTypeChildrenToProps = function mapArrayTypeChildrenToProps(arrayTypeChildren, newProps) {\n var newFlattenedProps = _extends({}, newProps);\n\n Object.keys(arrayTypeChildren).forEach(function (arrayChildName) {\n var _babelHelpers$extends4;\n\n newFlattenedProps = _extends({}, newFlattenedProps, (_babelHelpers$extends4 = {}, _babelHelpers$extends4[arrayChildName] = arrayTypeChildren[arrayChildName], _babelHelpers$extends4));\n });\n\n return newFlattenedProps;\n };\n\n HelmetWrapper.prototype.warnOnInvalidChildren = function warnOnInvalidChildren(child, nestedChildren) {\n if (process.env.NODE_ENV !== \"production\") {\n if (!VALID_TAG_NAMES.some(function (name) {\n return child.type === name;\n })) {\n if (typeof child.type === \"function\") {\n return warn(\"You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.\");\n }\n\n return warn(\"Only elements types \" + VALID_TAG_NAMES.join(\", \") + \" are allowed. Helmet does not support rendering <\" + child.type + \"> elements. Refer to our API for more information.\");\n }\n\n if (nestedChildren && typeof nestedChildren !== \"string\" && (!Array.isArray(nestedChildren) || nestedChildren.some(function (nestedChild) {\n return typeof nestedChild !== \"string\";\n }))) {\n throw new Error(\"Helmet expects a string as a child of <\" + child.type + \">. Did you forget to wrap your children in braces? ( <\" + child.type + \">{``} ) Refer to our API for more information.\");\n }\n }\n\n return true;\n };\n\n HelmetWrapper.prototype.mapChildrenToProps = function mapChildrenToProps(children, newProps) {\n var _this2 = this;\n\n var arrayTypeChildren = {};\n\n React.Children.forEach(children, function (child) {\n if (!child || !child.props) {\n return;\n }\n\n var _child$props = child.props,\n nestedChildren = _child$props.children,\n childProps = objectWithoutProperties(_child$props, [\"children\"]);\n\n var newChildProps = convertReactPropstoHtmlAttributes(childProps);\n\n _this2.warnOnInvalidChildren(child, nestedChildren);\n\n switch (child.type) {\n case TAG_NAMES.LINK:\n case TAG_NAMES.META:\n case TAG_NAMES.NOSCRIPT:\n case TAG_NAMES.SCRIPT:\n case TAG_NAMES.STYLE:\n arrayTypeChildren = _this2.flattenArrayTypeChildren({\n child: child,\n arrayTypeChildren: arrayTypeChildren,\n newChildProps: newChildProps,\n nestedChildren: nestedChildren\n });\n break;\n\n default:\n newProps = _this2.mapObjectTypeChildren({\n child: child,\n newProps: newProps,\n newChildProps: newChildProps,\n nestedChildren: nestedChildren\n });\n break;\n }\n });\n\n newProps = this.mapArrayTypeChildrenToProps(arrayTypeChildren, newProps);\n return newProps;\n };\n\n HelmetWrapper.prototype.render = function render() {\n var _props = this.props,\n children = _props.children,\n props = objectWithoutProperties(_props, [\"children\"]);\n\n var newProps = _extends({}, props);\n\n if (children) {\n newProps = this.mapChildrenToProps(children, newProps);\n }\n\n return React.createElement(Component, newProps);\n };\n\n createClass(HelmetWrapper, null, [{\n key: \"canUseDOM\",\n\n\n // Component.peek comes from react-side-effect:\n // For testing, you may use a static peek() method available on the returned component.\n // It lets you get the current state without resetting the mounted instance stack.\n // Don’t use it for anything other than testing.\n\n /**\n * @param {Object} base: {\"target\": \"_blank\", \"href\": \"http://mysite.com/\"}\n * @param {Object} bodyAttributes: {\"className\": \"root\"}\n * @param {String} defaultTitle: \"Default Title\"\n * @param {Boolean} defer: true\n * @param {Boolean} encodeSpecialCharacters: true\n * @param {Object} htmlAttributes: {\"lang\": \"en\", \"amp\": undefined}\n * @param {Array} link: [{\"rel\": \"canonical\", \"href\": \"http://mysite.com/example\"}]\n * @param {Array} meta: [{\"name\": \"description\", \"content\": \"Test description\"}]\n * @param {Array} noscript: [{\"innerHTML\": \" console.log(newState)\"\n * @param {Array} script: [{\"type\": \"text/javascript\", \"src\": \"http://mysite.com/js/test.js\"}]\n * @param {Array} style: [{\"type\": \"text/css\", \"cssText\": \"div { display: block; color: blue; }\"}]\n * @param {String} title: \"Title\"\n * @param {Object} titleAttributes: {\"itemprop\": \"name\"}\n * @param {String} titleTemplate: \"MySite.com - %s\"\n */\n set: function set$$1(canUseDOM) {\n Component.canUseDOM = canUseDOM;\n }\n }]);\n return HelmetWrapper;\n }(React.Component), _class.propTypes = {\n base: PropTypes.object,\n bodyAttributes: PropTypes.object,\n children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),\n defaultTitle: PropTypes.string,\n defer: PropTypes.bool,\n encodeSpecialCharacters: PropTypes.bool,\n htmlAttributes: PropTypes.object,\n link: PropTypes.arrayOf(PropTypes.object),\n meta: PropTypes.arrayOf(PropTypes.object),\n noscript: PropTypes.arrayOf(PropTypes.object),\n onChangeClientState: PropTypes.func,\n script: PropTypes.arrayOf(PropTypes.object),\n style: PropTypes.arrayOf(PropTypes.object),\n title: PropTypes.string,\n titleAttributes: PropTypes.object,\n titleTemplate: PropTypes.string\n }, _class.defaultProps = {\n defer: true,\n encodeSpecialCharacters: true\n }, _class.peek = Component.peek, _class.rewind = function () {\n var mappedState = Component.rewind();\n if (!mappedState) {\n // provide fallback if mappedState is undefined\n mappedState = mapStateOnServer({\n baseTag: [],\n bodyAttributes: {},\n encodeSpecialCharacters: true,\n htmlAttributes: {},\n linkTags: [],\n metaTags: [],\n noscriptTags: [],\n scriptTags: [],\n styleTags: [],\n title: \"\",\n titleAttributes: {}\n });\n }\n\n return mappedState;\n }, _temp;\n};\n\nvar NullComponent = function NullComponent() {\n return null;\n};\n\nvar HelmetSideEffects = withSideEffect(reducePropsToState, handleClientStateChange, mapStateOnServer)(NullComponent);\n\nvar HelmetExport = Helmet(HelmetSideEffects);\nHelmetExport.renderStatic = HelmetExport.rewind;\n\nexport default HelmetExport;\nexport { HelmetExport as Helmet };\n","var n,l,u,i,t,r,o,f,e,c={},s=[],a=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function h(n,l){for(var u in l)n[u]=l[u];return n}function v(n){var l=n.parentNode;l&&l.removeChild(n)}function y(l,u,i){var t,r,o,f={};for(o in u)\"key\"==o?t=u[o]:\"ref\"==o?r=u[o]:f[o]=u[o];if(arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):i),\"function\"==typeof l&&null!=l.defaultProps)for(o in l.defaultProps)void 0===f[o]&&(f[o]=l.defaultProps[o]);return p(l,f,t,r,null)}function p(n,i,t,r,o){var f={type:n,props:i,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==o?++u:o};return null==o&&null!=l.vnode&&l.vnode(f),f}function d(){return{current:null}}function _(n){return n.children}function k(n,l,u,i,t){var r;for(r in u)\"children\"===r||\"key\"===r||r in l||g(n,r,null,u[r],i);for(r in l)t&&\"function\"!=typeof l[r]||\"children\"===r||\"key\"===r||\"value\"===r||\"checked\"===r||u[r]===l[r]||g(n,r,l[r],u[r],i)}function b(n,l,u){\"-\"===l[0]?n.setProperty(l,null==u?\"\":u):n[l]=null==u?\"\":\"number\"!=typeof u||a.test(l)?u:u+\"px\"}function g(n,l,u,i,t){var r;n:if(\"style\"===l)if(\"string\"==typeof u)n.style.cssText=u;else{if(\"string\"==typeof i&&(n.style.cssText=i=\"\"),i)for(l in i)u&&l in u||b(n.style,l,\"\");if(u)for(l in u)i&&u[l]===i[l]||b(n.style,l,u[l])}else if(\"o\"===l[0]&&\"n\"===l[1])r=l!==(l=l.replace(/Capture$/,\"\")),l=l.toLowerCase()in n?l.toLowerCase().slice(2):l.slice(2),n.l||(n.l={}),n.l[l+r]=u,u?i||n.addEventListener(l,r?w:m,r):n.removeEventListener(l,r?w:m,r);else if(\"dangerouslySetInnerHTML\"!==l){if(t)l=l.replace(/xlink(H|:h)/,\"h\").replace(/sName$/,\"s\");else if(\"width\"!==l&&\"height\"!==l&&\"href\"!==l&&\"list\"!==l&&\"form\"!==l&&\"tabIndex\"!==l&&\"download\"!==l&&l in n)try{n[l]=null==u?\"\":u;break n}catch(n){}\"function\"==typeof u||(null==u||!1===u&&-1==l.indexOf(\"-\")?n.removeAttribute(l):n.setAttribute(l,u))}}function m(n){t=!0;try{return this.l[n.type+!1](l.event?l.event(n):n)}finally{t=!1}}function w(n){t=!0;try{return this.l[n.type+!0](l.event?l.event(n):n)}finally{t=!1}}function x(n,l){this.props=n,this.context=l}function A(n,l){if(null==l)return n.__?A(n.__,n.__.__k.indexOf(n)+1):null;for(var u;ll&&r.sort(function(n,l){return n.__v.__b-l.__v.__b}));$.__r=0}function H(n,l,u,i,t,r,o,f,e,a){var h,v,y,d,k,b,g,m=i&&i.__k||s,w=m.length;for(u.__k=[],h=0;h0?p(d.type,d.props,d.key,d.ref?d.ref:null,d.__v):d)){if(d.__=u,d.__b=u.__b+1,null===(y=m[h])||y&&d.key==y.key&&d.type===y.type)m[h]=void 0;else for(v=0;v=0;l--)if((u=n.__k[l])&&(i=L(u)))return i;return null}function M(n,u,i,t,r,o,f,e,c){var s,a,v,y,p,d,k,b,g,m,w,A,P,C,T,$=u.type;if(void 0!==u.constructor)return null;null!=i.__h&&(c=i.__h,e=u.__e=i.__e,u.__h=null,o=[e]),(s=l.__b)&&s(u);try{n:if(\"function\"==typeof $){if(b=u.props,g=(s=$.contextType)&&t[s.__c],m=s?g?g.props.value:s.__:t,i.__c?k=(a=u.__c=i.__c).__=a.__E:(\"prototype\"in $&&$.prototype.render?u.__c=a=new $(b,m):(u.__c=a=new x(b,m),a.constructor=$,a.render=B),g&&g.sub(a),a.props=b,a.state||(a.state={}),a.context=m,a.__n=t,v=a.__d=!0,a.__h=[],a._sb=[]),null==a.__s&&(a.__s=a.state),null!=$.getDerivedStateFromProps&&(a.__s==a.state&&(a.__s=h({},a.__s)),h(a.__s,$.getDerivedStateFromProps(b,a.__s))),y=a.props,p=a.state,a.__v=u,v)null==$.getDerivedStateFromProps&&null!=a.componentWillMount&&a.componentWillMount(),null!=a.componentDidMount&&a.__h.push(a.componentDidMount);else{if(null==$.getDerivedStateFromProps&&b!==y&&null!=a.componentWillReceiveProps&&a.componentWillReceiveProps(b,m),!a.__e&&null!=a.shouldComponentUpdate&&!1===a.shouldComponentUpdate(b,a.__s,m)||u.__v===i.__v){for(u.__v!==i.__v&&(a.props=b,a.state=a.__s,a.__d=!1),u.__e=i.__e,u.__k=i.__k,u.__k.forEach(function(n){n&&(n.__=u)}),w=0;w2&&(f.children=arguments.length>3?n.call(arguments,2):i),p(l.type,f,t||l.key,r||l.ref,null)}function G(n,l){var u={__c:l=\"__cC\"+e++,__:n,Consumer:function(n,l){return n.children(l)},Provider:function(n){var u,i;return this.getChildContext||(u=[],(i={})[l]=this,this.getChildContext=function(){return i},this.shouldComponentUpdate=function(n){this.props.value!==n.value&&u.some(function(n){n.__e=!0,T(n)})},this.sub=function(n){u.push(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u.splice(u.indexOf(n),1),l&&l.call(n)}}),n.children}};return u.Provider.__=u.Consumer.contextType=u}n=s.slice,l={__e:function(n,l,u,i){for(var t,r,o;l=l.__;)if((t=l.__c)&&!t.__)try{if((r=t.constructor)&&null!=r.getDerivedStateFromError&&(t.setState(r.getDerivedStateFromError(n)),o=t.__d),null!=t.componentDidCatch&&(t.componentDidCatch(n,i||{}),o=t.__d),o)return t.__E=t}catch(l){n=l}throw n}},u=0,i=function(n){return null!=n&&void 0===n.constructor},t=!1,x.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=h({},this.state),\"function\"==typeof n&&(n=n(h({},u),this.props)),n&&h(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),T(this))},x.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),T(this))},x.prototype.render=_,r=[],f=\"function\"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,$.__r=0,e=0;export{x as Component,_ as Fragment,F as cloneElement,G as createContext,y as createElement,d as createRef,y as h,E as hydrate,i as isValidElement,l as options,D as render,j as toChildArray};\n//# sourceMappingURL=preact.module.js.map\n","import{options as n}from\"preact\";var t,r,u,i,o=0,f=[],c=[],e=n.__b,a=n.__r,v=n.diffed,l=n.__c,m=n.unmount;function d(t,u){n.__h&&n.__h(r,t,o||u),o=0;var i=r.__H||(r.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({__V:c}),i.__[t]}function p(n){return o=1,y(B,n)}function y(n,u,i){var o=d(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):B(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}))}],o.__c=r,!r.u)){r.u=!0;var f=r.shouldComponentUpdate;r.shouldComponentUpdate=function(n,t,r){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(n){return n.__c});if(u.every(function(n){return!n.__N}))return!f||f.call(this,n,t,r);var i=!1;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),!(!i&&o.__c.props===n)&&(!f||f.call(this,n,t,r))}}return o.__N||o.__}function h(u,i){var o=d(t++,3);!n.__s&&z(o.__H,i)&&(o.__=u,o.i=i,r.__H.__h.push(o))}function s(u,i){var o=d(t++,4);!n.__s&&z(o.__H,i)&&(o.__=u,o.i=i,r.__h.push(o))}function _(n){return o=5,F(function(){return{current:n}},[])}function A(n,t,r){o=6,s(function(){return\"function\"==typeof n?(n(t()),function(){return n(null)}):n?(n.current=t(),function(){return n.current=null}):void 0},null==r?r:r.concat(n))}function F(n,r){var u=d(t++,7);return z(u.__H,r)?(u.__V=n(),u.i=r,u.__h=n,u.__V):u.__}function T(n,t){return o=8,F(function(){return n},t)}function q(n){var u=r.context[n.__c],i=d(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function x(t,r){n.useDebugValue&&n.useDebugValue(r?r(t):t)}function P(n){var u=d(t++,10),i=p();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function V(){var n=d(t++,11);if(!n.__){for(var u=r.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__=\"P\"+i[0]+\"-\"+i[1]++}return n.__}function b(){for(var t;t=f.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(k),t.__H.__h.forEach(w),t.__H.__h=[]}catch(r){t.__H.__h=[],n.__e(r,t.__v)}}n.__b=function(n){r=null,e&&e(n)},n.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.__V=c,n.__N=n.i=void 0})):(i.__h.forEach(k),i.__h.forEach(w),i.__h=[])),u=r},n.diffed=function(t){v&&v(t);var o=t.__c;o&&o.__H&&(o.__H.__h.length&&(1!==f.push(o)&&i===n.requestAnimationFrame||((i=n.requestAnimationFrame)||j)(b)),o.__H.__.forEach(function(n){n.i&&(n.__H=n.i),n.__V!==c&&(n.__=n.__V),n.i=void 0,n.__V=c})),u=r=null},n.__c=function(t,r){r.some(function(t){try{t.__h.forEach(k),t.__h=t.__h.filter(function(n){return!n.__||w(n)})}catch(u){r.some(function(n){n.__h&&(n.__h=[])}),r=[],n.__e(u,t.__v)}}),l&&l(t,r)},n.unmount=function(t){m&&m(t);var r,u=t.__c;u&&u.__H&&(u.__H.__.forEach(function(n){try{k(n)}catch(n){r=n}}),u.__H=void 0,r&&n.__e(r,u.__v))};var g=\"function\"==typeof requestAnimationFrame;function j(n){var t,r=function(){clearTimeout(u),g&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,100);g&&(t=requestAnimationFrame(r))}function k(n){var t=r,u=n.__c;\"function\"==typeof u&&(n.__c=void 0,u()),r=t}function w(n){var t=r;n.__c=n.__(),r=t}function z(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function B(n,t){return\"function\"==typeof t?t(n):t}export{T as useCallback,q as useContext,x as useDebugValue,h as useEffect,P as useErrorBoundary,V as useId,A as useImperativeHandle,s as useLayoutEffect,F as useMemo,y as useReducer,_ as useRef,p as useState};\n//# sourceMappingURL=hooks.module.js.map\n","import{Component as n,createElement as t,options as e,toChildArray as r,Fragment as u,render as o,hydrate as i,createContext as l,createRef as c,cloneElement as f}from\"preact\";export{Component,Fragment,createContext,createElement,createRef}from\"preact\";import{useState as a,useId as s,useReducer as h,useEffect as v,useLayoutEffect as d,useRef as p,useImperativeHandle as m,useMemo as y,useCallback as _,useContext as b,useDebugValue as S}from\"preact/hooks\";export*from\"preact/hooks\";function g(n,t){for(var e in t)n[e]=t[e];return n}function C(n,t){for(var e in n)if(\"__source\"!==e&&!(e in t))return!0;for(var r in t)if(\"__source\"!==r&&n[r]!==t[r])return!0;return!1}function E(n,t){return n===t&&(0!==n||1/n==1/t)||n!=n&&t!=t}function w(n){this.props=n}function R(n,e){function r(n){var t=this.props.ref,r=t==n.ref;return!r&&t&&(t.call?t(null):t.current=null),e?!e(this.props,n)||!r:C(this.props,n)}function u(e){return this.shouldComponentUpdate=r,t(n,e)}return u.displayName=\"Memo(\"+(n.displayName||n.name)+\")\",u.prototype.isReactComponent=!0,u.__f=!0,u}(w.prototype=new n).isPureReactComponent=!0,w.prototype.shouldComponentUpdate=function(n,t){return C(this.props,n)||C(this.state,t)};var x=e.__b;e.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),x&&x(n)};var N=\"undefined\"!=typeof Symbol&&Symbol.for&&Symbol.for(\"react.forward_ref\")||3911;function k(n){function t(t){var e=g({},t);return delete e.ref,n(e,t.ref||null)}return t.$$typeof=N,t.render=t,t.prototype.isReactComponent=t.__f=!0,t.displayName=\"ForwardRef(\"+(n.displayName||n.name)+\")\",t}var A=function(n,t){return null==n?null:r(r(n).map(t))},O={map:A,forEach:A,count:function(n){return n?r(n).length:0},only:function(n){var t=r(n);if(1!==t.length)throw\"Children.only\";return t[0]},toArray:r},T=e.__e;e.__e=function(n,t,e,r){if(n.then)for(var u,o=t;o=o.__;)if((u=o.__c)&&u.__c)return null==t.__e&&(t.__e=e.__e,t.__k=e.__k),u.__c(n,t);T(n,t,e,r)};var I=e.unmount;function L(n,t,e){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(n){\"function\"==typeof n.__c&&n.__c()}),n.__c.__H=null),null!=(n=g({},n)).__c&&(n.__c.__P===e&&(n.__c.__P=t),n.__c=null),n.__k=n.__k&&n.__k.map(function(n){return L(n,t,e)})),n}function U(n,t,e){return n&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(n){return U(n,t,e)}),n.__c&&n.__c.__P===t&&(n.__e&&e.insertBefore(n.__e,n.__d),n.__c.__e=!0,n.__c.__P=e)),n}function D(){this.__u=0,this.t=null,this.__b=null}function F(n){var t=n.__.__c;return t&&t.__a&&t.__a(n)}function M(n){var e,r,u;function o(o){if(e||(e=n()).then(function(n){r=n.default||n},function(n){u=n}),u)throw u;if(!r)throw e;return t(r,o)}return o.displayName=\"Lazy\",o.__f=!0,o}function V(){this.u=null,this.o=null}e.unmount=function(n){var t=n.__c;t&&t.__R&&t.__R(),t&&!0===n.__h&&(n.type=null),I&&I(n)},(D.prototype=new n).__c=function(n,t){var e=t.__c,r=this;null==r.t&&(r.t=[]),r.t.push(e);var u=F(r.__v),o=!1,i=function(){o||(o=!0,e.__R=null,u?u(l):l())};e.__R=i;var l=function(){if(!--r.__u){if(r.state.__a){var n=r.state.__a;r.__v.__k[0]=U(n,n.__c.__P,n.__c.__O)}var t;for(r.setState({__a:r.__b=null});t=r.t.pop();)t.forceUpdate()}},c=!0===t.__h;r.__u++||c||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(i,i)},D.prototype.componentWillUnmount=function(){this.t=[]},D.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var r=document.createElement(\"div\"),o=this.__v.__k[0].__c;this.__v.__k[0]=L(this.__b,r,o.__O=o.__P)}this.__b=null}var i=e.__a&&t(u,null,n.fallback);return i&&(i.__h=null),[t(u,null,e.__a?null:n.children),i]};var W=function(n,t,e){if(++e[1]===e[0]&&n.o.delete(t),n.props.revealOrder&&(\"t\"!==n.props.revealOrder[0]||!n.o.size))for(e=n.u;e;){for(;e.length>3;)e.pop()();if(e[1]>>1,1),e.i.removeChild(n)}}),o(t(P,{context:e.context},n.__v),e.l)):e.l&&e.componentWillUnmount()}function j(n,e){var r=t($,{__v:n,i:e});return r.containerInfo=e,r}(V.prototype=new n).__a=function(n){var t=this,e=F(t.__v),r=t.o.get(n);return r[0]++,function(u){var o=function(){t.props.revealOrder?(r.push(u),W(t,n,r)):u()};e?e(o):o()}},V.prototype.render=function(n){this.u=null,this.o=new Map;var t=r(n.children);n.revealOrder&&\"b\"===n.revealOrder[0]&&t.reverse();for(var e=t.length;e--;)this.o.set(t[e],this.u=[1,0,this.u]);return n.children},V.prototype.componentDidUpdate=V.prototype.componentDidMount=function(){var n=this;this.o.forEach(function(t,e){W(n,e,t)})};var z=\"undefined\"!=typeof Symbol&&Symbol.for&&Symbol.for(\"react.element\")||60103,B=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,H=\"undefined\"!=typeof document,Z=function(n){return(\"undefined\"!=typeof Symbol&&\"symbol\"==typeof Symbol()?/fil|che|rad/i:/fil|che|ra/i).test(n)};function Y(n,t,e){return null==t.__k&&(t.textContent=\"\"),o(n,t),\"function\"==typeof e&&e(),n?n.__c:null}function q(n,t,e){return i(n,t),\"function\"==typeof e&&e(),n?n.__c:null}n.prototype.isReactComponent={},[\"componentWillMount\",\"componentWillReceiveProps\",\"componentWillUpdate\"].forEach(function(t){Object.defineProperty(n.prototype,t,{configurable:!0,get:function(){return this[\"UNSAFE_\"+t]},set:function(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n})}})});var G=e.event;function J(){}function K(){return this.cancelBubble}function Q(){return this.defaultPrevented}e.event=function(n){return G&&(n=G(n)),n.persist=J,n.isPropagationStopped=K,n.isDefaultPrevented=Q,n.nativeEvent=n};var X,nn={configurable:!0,get:function(){return this.class}},tn=e.vnode;e.vnode=function(n){var t=n.type,e=n.props,u=e;if(\"string\"==typeof t){var o=-1===t.indexOf(\"-\");for(var i in u={},e){var l=e[i];H&&\"children\"===i&&\"noscript\"===t||\"value\"===i&&\"defaultValue\"in e&&null==l||(\"defaultValue\"===i&&\"value\"in e&&null==e.value?i=\"value\":\"download\"===i&&!0===l?l=\"\":/ondoubleclick/i.test(i)?i=\"ondblclick\":/^onchange(textarea|input)/i.test(i+t)&&!Z(e.type)?i=\"oninput\":/^onfocus$/i.test(i)?i=\"onfocusin\":/^onblur$/i.test(i)?i=\"onfocusout\":/^on(Ani|Tra|Tou|BeforeInp|Compo)/.test(i)?i=i.toLowerCase():o&&B.test(i)?i=i.replace(/[A-Z0-9]/g,\"-$&\").toLowerCase():null===l&&(l=void 0),/^oninput$/i.test(i)&&(i=i.toLowerCase(),u[i]&&(i=\"oninputCapture\")),u[i]=l)}\"select\"==t&&u.multiple&&Array.isArray(u.value)&&(u.value=r(e.children).forEach(function(n){n.props.selected=-1!=u.value.indexOf(n.props.value)})),\"select\"==t&&null!=u.defaultValue&&(u.value=r(e.children).forEach(function(n){n.props.selected=u.multiple?-1!=u.defaultValue.indexOf(n.props.value):u.defaultValue==n.props.value})),n.props=u,e.class!=e.className&&(nn.enumerable=\"className\"in e,null!=e.className&&(u.class=e.className),Object.defineProperty(u,\"className\",nn))}n.$$typeof=z,tn&&tn(n)};var en=e.__r;e.__r=function(n){en&&en(n),X=n.__c};var rn={ReactCurrentDispatcher:{current:{readContext:function(n){return X.__n[n.__c].props.value}}}},un=\"17.0.2\";function on(n){return t.bind(null,n)}function ln(n){return!!n&&n.$$typeof===z}function cn(n){return ln(n)?f.apply(null,arguments):n}function fn(n){return!!n.__k&&(o(null,n),!0)}function an(n){return n&&(n.base||1===n.nodeType&&n)||null}var sn=function(n,t){return n(t)},hn=function(n,t){return n(t)},vn=u;function dn(n){n()}function pn(n){return n}function mn(){return[!1,dn]}var yn=d;function _n(n,t){var e=t(),r=a({h:{__:e,v:t}}),u=r[0].h,o=r[1];return d(function(){u.__=e,u.v=t,E(u.__,t())||o({h:u})},[n,e,t]),v(function(){return E(u.__,u.v())||o({h:u}),n(function(){E(u.__,u.v())||o({h:u})})},[n]),e}var bn={useState:a,useId:s,useReducer:h,useEffect:v,useLayoutEffect:d,useInsertionEffect:yn,useTransition:mn,useDeferredValue:pn,useSyncExternalStore:_n,startTransition:dn,useRef:p,useImperativeHandle:m,useMemo:y,useCallback:_,useContext:b,useDebugValue:S,version:\"17.0.2\",Children:O,render:Y,hydrate:q,unmountComponentAtNode:fn,createPortal:j,createElement:t,createContext:l,createFactory:on,cloneElement:cn,createRef:c,Fragment:u,isValidElement:ln,findDOMNode:an,Component:n,PureComponent:w,memo:R,forwardRef:k,flushSync:hn,unstable_batchedUpdates:sn,StrictMode:vn,Suspense:D,SuspenseList:V,lazy:M,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:rn};export{O as Children,w as PureComponent,vn as StrictMode,D as Suspense,V as SuspenseList,rn as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,cn as cloneElement,on as createFactory,j as createPortal,bn as default,an as findDOMNode,hn as flushSync,k as forwardRef,q as hydrate,ln as isValidElement,M as lazy,R as memo,Y as render,dn as startTransition,fn as unmountComponentAtNode,sn as unstable_batchedUpdates,pn as useDeferredValue,yn as useInsertionEffect,_n as useSyncExternalStore,mn as useTransition,un as version};\n//# sourceMappingURL=compat.module.js.map\n","import * as preact from 'preact';\nimport { Component, createElement, isValidElement, Fragment } from 'preact';\nimport { createPortal } from 'preact/compat';\n\nconst styleTexts = [];\nconst styleEls = new Map();\nfunction injectStyles(styleText) {\n styleTexts.push(styleText);\n styleEls.forEach((styleEl) => {\n appendStylesTo(styleEl, styleText);\n });\n}\nfunction ensureElHasStyles(el) {\n if (el.isConnected && // sometimes true if SSR system simulates DOM\n el.getRootNode // sometimes undefined if SSR system simulates DOM\n ) {\n registerStylesRoot(el.getRootNode());\n }\n}\nfunction registerStylesRoot(rootNode) {\n let styleEl = styleEls.get(rootNode);\n if (!styleEl || !styleEl.isConnected) {\n styleEl = rootNode.querySelector('style[data-fullcalendar]');\n if (!styleEl) {\n styleEl = document.createElement('style');\n styleEl.setAttribute('data-fullcalendar', '');\n const nonce = getNonceValue();\n if (nonce) {\n styleEl.nonce = nonce;\n }\n const parentEl = rootNode === document ? document.head : rootNode;\n const insertBefore = rootNode === document\n ? parentEl.querySelector('script,link[rel=stylesheet],link[as=style],style')\n : parentEl.firstChild;\n parentEl.insertBefore(styleEl, insertBefore);\n }\n styleEls.set(rootNode, styleEl);\n hydrateStylesRoot(styleEl);\n }\n}\nfunction hydrateStylesRoot(styleEl) {\n for (const styleText of styleTexts) {\n appendStylesTo(styleEl, styleText);\n }\n}\nfunction appendStylesTo(styleEl, styleText) {\n const { sheet } = styleEl;\n const ruleCnt = sheet.cssRules.length;\n styleText.split('}').forEach((styleStr, i) => {\n styleStr = styleStr.trim();\n if (styleStr) {\n sheet.insertRule(styleStr + '}', ruleCnt + i);\n }\n });\n}\n// nonce\n// -------------------------------------------------------------------------------------------------\nlet queriedNonceValue;\nfunction getNonceValue() {\n if (queriedNonceValue === undefined) {\n queriedNonceValue = queryNonceValue();\n }\n return queriedNonceValue;\n}\n/*\nTODO: discourage meta tag and instead put nonce attribute on placeholder