"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var extensions_exports = {};
__export(extensions_exports, {
  getTipTapExtensions: () => getTipTapExtensions
});
module.exports = __toCommonJS(extensions_exports);
var import_ricos_types = require("./../../../ricos-types/index.js");
var import_get_is_editor_empty = require("./../../../_shared/get-is-editor-empty.js");
var import_pm_node_types = require("./../../../_shared/pm-node-types.js");
var import_quick_actions_plugin_key = require("./../../../_shared/quick-actions-plugin-key.js");
var import_top_level_nodes = require("./../../../_shared/top-level-nodes.js");
var import_tiptap = require("./../../../tiptap/index.js");
var import_suggestion = require("./../../../tiptap/suggestion/index.js");
var import_tiptap_extensions = require("./../../../tiptap-extensions/index.js");
var import_modal = require("../modal/modal.js");
var import_types = require("../types.js");
const getSupportedPluginsFromContext = (editor) => {
  const { selection } = editor.state;
  const $from = selection.$from;
  const foundNode = (0, import_tiptap.findParentNodeClosestToPos)(
    $from,
    (node) => !!node.type.spec.supportedQuickActions
  );
  if (!foundNode) {
    return void 0;
  }
  return foundNode.node.type.spec.supportedQuickActions;
};
const getTipTapExtensions = (config) => [
  (0, import_tiptap_extensions.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 = (0, import_get_is_editor_empty.getIsEditorEmpty)(doc);
        if (isEditorEmpty && !editor.isFocused) {
          return false;
        }
        const isEmptyTopLevelParagraph = import_top_level_nodes.TOP_LEVEL_NODES.includes($pos.parent.type.name) && !selection.$head.nodeBefore && !selection.$head.nodeAfter && node.type.name === import_ricos_types.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 = (0, import_tiptap.callOrReturn)(
            (0, import_tiptap.getExtensionField)(extension, "supportedQuickActions", context)
          );
          return supportedQuickActions ? { supportedQuickActions } : {};
        },
        addProseMirrorPlugins() {
          return this.options.services.context.isMobile ? [] : [
            (0, import_suggestion.Suggestion)({
              editor: this.editor,
              pluginKey: import_quick_actions_plugin_key.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 = [import_pm_node_types.PmNodeType.CAPTION];
                const disableQuickActions = !!(0, import_tiptap.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(import_types.QUICK_ACTIONS_MODAL_ID);
                  const supportedPlugins = getSupportedPluginsFromContext(props.editor);
                  if (!isCurrentlyOpen) {
                    const { modalRef, patchProps, close } = modalService.openModal({
                      id: import_types.QUICK_ACTIONS_MODAL_ID,
                      Component: import_modal.QuickActionsModal,
                      componentProps: { ...props, supportedPlugins },
                      layout: "floating",
                      positioning: {
                        referenceElement: {
                          getBoundingClientRect: () => (0, import_tiptap.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(import_types.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();
                  }
                };
              }
            })
          ];
        }
      };
    }
  })
];
//# sourceMappingURL=extensions.js.map
