import { Node_Type } from "./../../../ricos-types/index.js";
import { getIsEditorEmpty } from "./../../../_shared/get-is-editor-empty.js";
import { PmNodeType } from "./../../../_shared/pm-node-types.js";
import { quickActionsPluginKey } from "./../../../_shared/quick-actions-plugin-key.js";
import { TOP_LEVEL_NODES } from "./../../../_shared/top-level-nodes.js";
import { callOrReturn, findParentNodeClosestToPos, getExtensionField, posToDOMRect } from "./../../../tiptap/index.js";
import { Suggestion } from "./../../../tiptap/suggestion/index.js";
import { createRicosFunctionalExtension } from "./../../../tiptap-extensions/index.js";
import { QuickActionsModal } from "../modal/modal.js";
import { QUICK_ACTIONS_MODAL_ID } from "../types.js";
const getSupportedPluginsFromContext = (editor) => {
  const { selection } = editor.state;
  const $from = selection.$from;
  const foundNode = findParentNodeClosestToPos(
    $from,
    (node) => !!node.type.spec.supportedQuickActions
  );
  if (!foundNode) {
    return void 0;
  }
  return foundNode.node.type.spec.supportedQuickActions;
};
const getTipTapExtensions = (config) => [
  createRicosFunctionalExtension({
    name: "quick-actions",
    type: "extension",
    groups: [],
    placeholder: {
      priority: 100,
      predicate: ({ doc, selection, node, pos, editor, isMobile }) => {
        if (isMobile) {
          return false;
        }
        const $pos = doc.resolve(pos);
        const isEditorEmpty = getIsEditorEmpty(doc);
        if (isEditorEmpty && !editor.isFocused) {
          return false;
        }
        const isEmptyTopLevelParagraph = TOP_LEVEL_NODES.includes($pos.parent.type.name) && !selection.$head.nodeBefore && !selection.$head.nodeAfter && node.type.name === Node_Type.PARAGRAPH;
        const isEmpty = !node.isLeaf && !node.childCount;
        const isSelected = selection.from - 1 === pos && selection.to + 1 === pos + node.nodeSize;
        return isEmptyTopLevelParagraph && isEmpty && isSelected;
      },
      content: config?.customPlaceholder ?? "QuickActionsPlugin_EditorPlaceholder"
    },
    reconfigure: (config2, _extensions, _ricosProps, _settings, services) => {
      return {
        ...config2,
        addOptions: () => {
          return { services };
        }
      };
    },
    createExtensionConfig() {
      return {
        name: "quick-actions",
        priority: 110,
        extendNodeSchema(extension) {
          const context = {
            name: extension.name,
            options: extension.options,
            storage: extension.storage
          };
          const supportedQuickActions = callOrReturn(
            getExtensionField(extension, "supportedQuickActions", context)
          );
          return supportedQuickActions ? { supportedQuickActions } : {};
        },
        addProseMirrorPlugins() {
          return this.options.services.context.isMobile ? [] : [
            Suggestion({
              editor: this.editor,
              pluginKey: quickActionsPluginKey,
              char: "/",
              allowSpaces: true,
              command: ({
                editor,
                props
              }) => {
                const { text } = props;
                const query = text ? text : "/";
                const { dispatch, state } = editor.view;
                const { tr } = state;
                const { $from } = tr.selection;
                const range = $from.blockRange();
                if (!range) {
                  return;
                }
                if (!$from.nodeBefore || $from.nodeBefore?.type.name.toUpperCase() !== "TEXT" || !$from.nodeBefore.text?.endsWith(query)) {
                  return;
                }
                if (!dispatch) {
                  return;
                }
                editor.view.dispatch(tr.delete($from.pos - query.length, $from.pos));
              },
              allow: ({ range, state }) => {
                const { doc } = state;
                const { from } = range;
                const $from = doc.resolve(from);
                const pluginsToDisableIn = [PmNodeType.CAPTION];
                const disableQuickActions = !!findParentNodeClosestToPos(
                  $from,
                  (node) => pluginsToDisableIn.includes(node.type.name)
                );
                return !disableQuickActions;
              },
              render: () => {
                const { modals: modalService } = this.options.services;
                let updateProps;
                let closeModal;
                let quickActionsModalRef;
                const handleModalState = (props) => {
                  const isCurrentlyOpen = modalService.isModalOpen(QUICK_ACTIONS_MODAL_ID);
                  const supportedPlugins = getSupportedPluginsFromContext(props.editor);
                  if (!isCurrentlyOpen) {
                    const { modalRef, patchProps, close } = modalService.openModal({
                      id: QUICK_ACTIONS_MODAL_ID,
                      Component: QuickActionsModal,
                      componentProps: { ...props, supportedPlugins },
                      layout: "floating",
                      positioning: {
                        referenceElement: {
                          getBoundingClientRect: () => posToDOMRect(
                            props.editor.view,
                            props.editor.state.selection.from,
                            props.editor.state.selection.to
                          )
                        },
                        placement: "bottom-start"
                      },
                      autoFocus: false,
                      type: "exclusive",
                      sticky: true
                    });
                    updateProps = patchProps;
                    closeModal = close;
                    quickActionsModalRef = modalRef;
                    props.editor.view.focus();
                  } else if (isCurrentlyOpen) {
                    updateProps({ ...props, supportedPlugins });
                  }
                };
                return {
                  onStart: (props) => {
                    handleModalState(props);
                  },
                  onUpdate(props) {
                    handleModalState(props);
                  },
                  onKeyDown(props) {
                    if (!modalService.isModalOpen(QUICK_ACTIONS_MODAL_ID)) {
                      return false;
                    }
                    if (props.event.key === "Escape") {
                      closeModal();
                      props.view.focus();
                      return true;
                    }
                    if (["ArrowUp", "ArrowDown"].includes(props.event.key)) {
                      return !!quickActionsModalRef?.current?.onKeyDown?.(props);
                    }
                    if (["Enter", "Tab"].includes(props.event.key)) {
                      const result = quickActionsModalRef?.current?.onKeyDown?.(props);
                      closeModal();
                      props.view.focus();
                      return !!result;
                    }
                    props.view.focus();
                    return false;
                  },
                  onExit(props) {
                    if (closeModal) {
                      closeModal();
                    }
                    props.editor.view.focus();
                  }
                };
              }
            })
          ];
        }
      };
    }
  })
];
export {
  getTipTapExtensions
};
//# sourceMappingURL=extensions.js.map
