"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var rich_content_adapter_exports = {};
__export(rich_content_adapter_exports, {
  RichContentAdapter: () => RichContentAdapter
});
module.exports = __toCommonJS(rich_content_adapter_exports);
var import_lodash = __toESM(require("lodash"));
var import_ricos_content = require("./../../ricos-content/index.js");
var import_utils = require("./../../ricos-content/lib/utils.js");
var import_shortcuts_dialog = require("./../../ricos-editor/shortcuts/shortcuts-dialog.js");
var import_default_text_formatting_buttons = require("./../../ricos-plugins/toolbar-utils/default-text-formatting-buttons.js");
var import_get_buttons_list_from_config = require("./../../ricos-plugins/toolbar-utils/get-buttons-list-from-config.js");
var import_merge_toolbar_settings = require("./../../ricos-plugins/toolbar-utils/merge-toolbar-settings.js");
var import_v1 = require("./../../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_next_schema = require("./../../ricos-schema/next-schema/index.js");
var import_ricos_types = require("./../../ricos-types/index.js");
var import_get_alignment_in_selection = require("./../../_shared/resolvers/get-alignment-in-selection.js");
var import_get_font_family_in_selection = require("./../../_shared/resolvers/get-font-family-in-selection.js");
var import_get_font_size_in_selection = require("./../../_shared/resolvers/get-font-size-in-selection.js");
var import_get_heading_in_selection = require("./../../_shared/resolvers/get-heading-in-selection.js");
var import_get_highligh_color_in_selection = require("./../../_shared/resolvers/get-highligh-color-in-selection.js");
var import_get_line_spacing_after_selection = require("./../../_shared/resolvers/get-line-spacing-after-selection.js");
var import_get_line_spacing_before_selection = require("./../../_shared/resolvers/get-line-spacing-before-selection.js");
var import_get_line_spacing_in_selection = require("./../../_shared/resolvers/get-line-spacing-in-selection.js");
var import_get_text_color_in_selection = require("./../../_shared/resolvers/get-text-color-in-selection.js");
var import_is_bold_in_text = require("./../../_shared/resolvers/is-bold-in-text.js");
var import_is_italic_in_text = require("./../../_shared/resolvers/is-italic-in-text.js");
var import_is_redo_stack_empty = require("./../../_shared/resolvers/is-redo-stack-empty.js");
var import_is_spoiler_in_text = require("./../../_shared/resolvers/is-spoiler-in-text.js");
var import_is_striketrough_in_text = require("./../../_shared/resolvers/is-striketrough-in-text.js");
var import_is_superscript_in_text = require("./../../_shared/resolvers/is-superscript-in-text.js");
var import_is_underline_in_text = require("./../../_shared/resolvers/is-underline-in-text.js");
var import_is_undo_stack_empty = require("./../../_shared/resolvers/is-undo-stack-empty.js");
var import_uncreachable = require("./../../_shared/uncreachable.js");
var import_use_context_selector = require("./../../_shared/use-context-selector.js");
var import_tiptap = require("./../../tiptap/index.js");
var import_state = require("./../../tiptap/pm/state.js");
var import_editor_common = require("./../../editor-common/index.js");
var import_inline_ai_context_provider = require("./../../plugin-inline-ai/inline-ai-context-provider.js");
var import_default_toolbar_settings = require("./../../toolbars-v3/default-toolbar-settings.js");
var import_map_buttons_from_config = require("./../../toolbars-v3/map-buttons-from-config.js");
var import_to_resolved_attributes = require("./../../toolbars-v3/to-resolved-attributes.js");
var import_to_schema_base_id = require("./../../toolbars-v3/to-schema-base-id.js");
var import_consts = require("../consts.js");
var import_convert_inline_styles_to_css = require("../helpers/convert-inline-styles-to-css.js");
var import_helpers = require("../helpers/index.js");
class RichContentAdapter {
  constructor(tiptapEditor, services, toolbarSettings, getToolbarStateSelectorContextValue, getSelectionSelectorContextValue, getModalStateSelectorContextValue, pmContentSelectorContextValue, getInlineAiStateSelectorContextValue) {
    this.tiptapEditor = tiptapEditor;
    this.useWixelToolbarProps = ({
      selection,
      resolvedToolbarSettings
    }) => {
      const pluginToolbar = this.services.plugins.getVisibleToolbar(
        this.tiptapEditor.state.selection,
        {
          adapter: { tiptapEditor: this.tiptapEditor },
          getPublicCommands: this.getEditorCommands
        }
      );
      if (pluginToolbar && (selection?.to === selection?.from || selection instanceof import_state.NodeSelection || selection?.toJSON()?.type === "cell")) {
        return {
          toolbarType: import_ricos_types.ToolbarType.PLUGIN,
          buttons: toExternalPluginToolbarButtons({
            buttons: pluginToolbar.getButtons(),
            editor: this.tiptapEditor,
            publicCommands: this.getEditorCommands(),
            modals: this.services.modals
          })
        };
      }
      const toolbarType = import_ricos_types.ToolbarType.FORMATTING;
      const toolbarSettingsFunctions = resolvedToolbarSettings.find(
        (toolbar) => toolbar?.name === toolbarType
      );
      const textButtons = this.services.plugins.getTextButtons();
      return {
        toolbarType,
        buttons: toExternalTextButtonsToolbarConfigs({
          textButtons,
          services: this.services,
          toolbarSettingsFunctions,
          toolbarType,
          publicCommands: this.getEditorCommands(),
          editor: this.tiptapEditor,
          isMobile: this.services.context.isMobile,
          editorQuery: this.services.getEditorQuery()
        })
      };
    };
    this.openModal = (options) => {
      if (options.type === "SHORTCUTS_SHEET") {
        this.services.modals.openModal({
          id: import_shortcuts_dialog.SHORTCUT_SHEET_MODAL_ID,
          Component: import_shortcuts_dialog.ShortcutsDialog,
          componentProps: {},
          dragHandleSelector: "[data-drag-handler]",
          enableDrag: true,
          layout: "floating",
          positioning: {
            referenceElement: this.tiptapEditor.view.dom,
            placement: "right-start"
          }
        });
        return;
      }
      const openFn = this.services.plugins.getExports().modals?.[options.type];
      if (!openFn) {
        console.error(
          `No such modal type ${options.type}, are you sure you added appropriate plugin?`
        );
        return;
      }
      openFn(this.tiptapEditor, { ...this.services, publicCommands: this.getEditorCommands() });
    };
    this.getContainer = () => {
      return this.tiptapEditor?.options?.element;
    };
    this.getDocumentStyle = () => this.tiptapEditor?.getJSON()?.attrs?.documentStyle || {};
    this.editorMocks = {
      getAnchorableBlocks: () => ({
        anchorableBlocks: [],
        pluginsIncluded: []
      }),
      getTextAlignment: () => this.services.content.resolve(import_get_alignment_in_selection.getAlignmentInSelection),
      isBlockTypeSelected: () => false,
      isUndoStackEmpty: () => this.services.content.resolve(import_is_undo_stack_empty.isUndoStackEmpty),
      isRedoStackEmpty: () => this.services.content.resolve(import_is_redo_stack_empty.isRedoStackEmpty),
      getSelectedData: () => "blah",
      getPluginsList: () => {
        return this.services.editorProps.plugins?.map(
          (p) => import_next_schema.legacyPluginToNextMap[p.type] ?? import_next_schema.legacyPluginToNextMap[import_lodash.default.camelCase(p.type)]
        ) ?? [];
      },
      scrollToBlock: (_nodeId) => {
      },
      isBlockInContent: (_nodeId) => false,
      toggleBlockOverlay: (_nodeId) => false,
      getBlockSpacing: () => {
        const lineHeight = this.services.content.resolve(import_get_line_spacing_in_selection.getLineSpacingInSelection);
        const paddingTop = this.services.content.resolve(import_get_line_spacing_before_selection.getLineSpacingBeforeSelection);
        const paddingBottom = this.services.content.resolve(import_get_line_spacing_after_selection.getLineSpacingAfterSelection);
        return {
          "line-height": lineHeight,
          "padding-top": paddingTop,
          "padding-bottom": paddingBottom
        };
      },
      saveEditorState: () => {
      },
      loadEditorState: () => {
      },
      saveSelectionState: () => {
      },
      loadSelectionState: () => {
      },
      setBlockType: () => {
      },
      _setSelection: () => {
      },
      getAnchorBlockInlineStyles: () => {
        return {};
      },
      getInlineStylesInSelection: () => {
        const {
          state: {
            doc,
            selection: { from, to }
          }
        } = this.tiptapEditor;
        let node;
        doc.nodesBetween(from, to, (currNode) => {
          if ([import_v1.Node_Type.PARAGRAPH, import_v1.Node_Type.HEADING].includes(
            currNode?.type?.name
          )) {
            node = this.services.converters.fromPmNode({
              ...currNode.toJSON(),
              type: currNode?.type?.name
            });
            return false;
          }
        });
        return node ? (0, import_convert_inline_styles_to_css.convertInlineStylesToCSS)(node) : {};
      },
      getWiredFontStyles: () => {
        const container = this.getContainer();
        const styles = window.getComputedStyle(container);
        return Object.entries(import_ricos_types.DOC_STYLE_TYPES).reduce((acc, [key, docType]) => {
          const toPropertyValue = (property) => ({
            [property]: styles.getPropertyValue(`--ricos-custom-${key.toLowerCase()}-${property}`)
          });
          return {
            ...acc,
            [docType]: {
              ...toPropertyValue("font-size"),
              ...toPropertyValue("font-family"),
              ...toPropertyValue("color"),
              ...toPropertyValue("background-color")
            }
          };
        }, {});
      },
      isAtomicBlockInSelection: () => false,
      isTextBlockInSelection: () => true,
      getAnchorBlockType: () => "paragraph",
      focus: (focusPosition) => this.focus(focusPosition)
    };
    this.tiptapEditor = tiptapEditor;
    this.getEditorCommands = this.getEditorCommands.bind(this);
    this.getToolbarProps = (type) => {
      if (type === import_ricos_types.ToolbarType.INSERT_PLUGIN) {
        const addButtons = services.plugins.getAddButtons();
        const toolbarSettingsFunctions2 = getToolbarConfig(toolbarSettings, type);
        return {
          buttons: toExternalAddButtonsToolbarConfigs(
            addButtons,
            toolbarSettingsFunctions2,
            type,
            services.t,
            services.pluginsEvents,
            this.getEditorCommands(),
            services.context.isMobile
          )
        };
      }
      const toolbarType = import_editor_common.TOOLBARS.FORMATTING;
      const textButtons = services.plugins.getTextButtons();
      const toolbarSettingsFunctions = getToolbarConfig(toolbarSettings, toolbarType);
      return {
        buttons: toExternalTextButtonsToolbarConfigs({
          textButtons,
          services: this.services,
          toolbarSettingsFunctions,
          toolbarType,
          publicCommands: this.getEditorCommands(),
          editor: this.tiptapEditor,
          isMobile: services.context.isMobile,
          editorQuery: services.getEditorQuery()
        })
      };
    };
    this.services = services;
    this.useUndoState = () => {
      (0, import_use_context_selector.useContextSelectorWithValue)(pmContentSelectorContextValue(), (v) => v, Object.is);
      return {
        isUndoStackEmpty: !this.tiptapEditor.can().undo(),
        isRedoStackEmpty: !this.tiptapEditor.can().redo()
      };
    };
    this.useInlineAiState = (invocationId) => {
      return (0, import_inline_ai_context_provider.useInlineAiStateWithSelectorContextValue)(
        getInlineAiStateSelectorContextValue(),
        invocationId,
        void 0
      );
    };
    this.useToolbarProps = (type) => {
      const resolvedToolbarSettings = (0, import_use_context_selector.useContextSelectorWithValue)(
        getToolbarStateSelectorContextValue(),
        (v) => v.resolvedToolbarSettings,
        Object.is
      );
      (0, import_use_context_selector.useContextSelectorWithValue)(getModalStateSelectorContextValue(), (v) => v, Object.is);
      (0, import_use_context_selector.useContextSelectorWithValue)(pmContentSelectorContextValue(), (v) => v, Object.is);
      const selection = (0, import_use_context_selector.useContextSelectorWithValue)(
        getSelectionSelectorContextValue(),
        (v) => v.selection,
        Object.is
      );
      const toolbarSettingsFunctions = resolvedToolbarSettings.find(
        (toolbar) => toolbar?.name === type
      );
      if (type === "WIXEL") {
        return this.useWixelToolbarProps({ selection, resolvedToolbarSettings });
      }
      if (type === import_editor_common.TOOLBARS.INSERT_PLUGIN) {
        const addButtons = services.plugins.getAddButtons();
        return {
          buttons: toExternalAddButtonsToolbarConfigs(
            addButtons,
            toolbarSettingsFunctions,
            type,
            services.t,
            services.pluginsEvents,
            this.getEditorCommands(),
            services.context.isMobile
          )
        };
      }
      if (type === import_editor_common.TOOLBARS.QUICK_ACTIONS) {
        return {
          buttons: Object.fromEntries(
            services.plugins.getQuickActions().map((quickAction) => [
              quickAction.id,
              {
                name: quickAction.id,
                getIcon: () => quickAction.icon,
                getLabel: () => quickAction.title,
                onClick: ({ referenceElement }) => quickAction.command({
                  editor: this.tiptapEditor,
                  publicCommands: this.getEditorCommands(),
                  modalService: this.services.modals,
                  referenceElement
                }),
                tags: quickAction.tags,
                dataHook: quickAction.id
              }
            ])
          )
        };
      }
      if (type === import_editor_common.TOOLBARS.PLUGIN) {
        const pluginToolbar = services.plugins.getVisibleToolbar(
          this.tiptapEditor.state.selection,
          {
            adapter: { tiptapEditor: this.tiptapEditor },
            getPublicCommands: this.getEditorCommands
          }
        );
        const isVisible = isPluginToolbarVisible(selection, this.tiptapEditor.state.doc);
        if (!pluginToolbar || isVisible) {
          return { buttons: {} };
        }
        return {
          buttons: toExternalPluginToolbarButtons({
            buttons: pluginToolbar.getButtons(),
            editor: this.tiptapEditor,
            publicCommands: this.getEditorCommands(),
            modals: this.services.modals
          })
        };
      }
      const textButtons = this.services.plugins.getTextButtons();
      return {
        buttons: toExternalTextButtonsToolbarConfigs({
          textButtons,
          services: this.services,
          toolbarSettingsFunctions,
          toolbarType: type,
          publicCommands: this.getEditorCommands(),
          editor: this.tiptapEditor,
          isMobile: services.context.isMobile,
          editorQuery: services.getEditorQuery()
        })
      };
    };
    this.useToolbarWixelProps = () => {
      const resolvedToolbarSettings = (0, import_use_context_selector.useContextSelectorWithValue)(
        getToolbarStateSelectorContextValue(),
        (v) => v.resolvedToolbarSettings,
        Object.is
      );
      (0, import_use_context_selector.useContextSelectorWithValue)(getModalStateSelectorContextValue(), (v) => v, Object.is);
      (0, import_use_context_selector.useContextSelectorWithValue)(pmContentSelectorContextValue(), (v) => v, Object.is);
      const selection = (0, import_use_context_selector.useContextSelectorWithValue)(
        getSelectionSelectorContextValue(),
        (v) => v.selection,
        Object.is
      );
      const { buttons, toolbarType } = this.useWixelToolbarProps({
        selection,
        resolvedToolbarSettings
      });
      return {
        buttons,
        toolbarType,
        isEditorOrPortalFocused: () => {
          if (this.tiptapEditor.isFocused) {
            return true;
          }
          const activeElement = document.activeElement;
          const ricosPortal = this.services.context.portal;
          if (!activeElement || !ricosPortal) {
            return false;
          }
          return ricosPortal.contains(activeElement);
        }
      };
    };
  }
  focus(focusPosition) {
    this.tiptapEditor.commands.focus(focusPosition);
  }
  blur() {
    this.tiptapEditor.commands.blur();
  }
  setTiptapContent(content) {
    this.tiptapEditor.commands.setContent(content);
  }
  getEditorCommands() {
    const hasInlineStyle = (style) => {
      const resolvedStyles = {
        bold: this.services.content.resolve(import_is_bold_in_text.isBoldInText),
        italic: this.services.content.resolve(import_is_italic_in_text.isItalicInText),
        underline: this.services.content.resolve(import_is_underline_in_text.isUnderlineInText),
        spoiler: this.services.content.resolve(import_is_spoiler_in_text.isSpoilerInText),
        strikethrough: this.services.content.resolve(import_is_striketrough_in_text.isStrikethroughInText),
        superscript: this.services.content.resolve(import_is_superscript_in_text.isSuperscriptInText)
      };
      return resolvedStyles[style];
    };
    return {
      ...this.editorMocks,
      getContent: this.services.schema.getContent,
      getDocumentStyle: this.getDocumentStyle,
      toggleInlineStyle: (inlineStyle) => {
        const editorCommand = this.tiptapEditor.chain();
        switch (inlineStyle) {
          case "bold":
            editorCommand.toggleBold().run();
            return;
          case "underline":
            editorCommand.toggleUnderline().run();
            return;
          case "italic":
            editorCommand.toggleItalic().run();
            return;
          case "spoiler":
            editorCommand.toggleSpoiler().run();
            return;
          case "strikethrough":
            editorCommand.toggleStrikethrough().run();
            return;
          case "superscript":
            editorCommand.toggleSuperscript().run();
            return;
          case "subscript":
            editorCommand.toggleSubscript().run();
            return;
          case "not_superscript":
          case "not_bold":
          case "not_italic":
          case "not_underline":
          case "not_strikethrough":
          case "not_subscript":
            return;
          default:
            console.error((0, import_uncreachable.unreachable)(inlineStyle));
            return;
        }
      },
      hasInlineStyle,
      insertBlock: (pluginType, data = {}) => {
        const type = import_consts.TO_TIPTAP_TYPE[pluginType];
        let id = "";
        if (!type) {
          console.error(`No such plugin type ${pluginType}`);
          return id;
        }
        let { content, ..._attrs } = data;
        id = data.id || (0, import_ricos_content.generateId)();
        let attrs = { id, ...flatComponentState(_attrs) };
        if (type === import_ricos_content.TIPTAP_FIGURE_TYPE && !content) {
          const normalizedData = normalizeFigureData(pluginType, data, id);
          content = normalizedData.content;
          attrs = normalizedData.attrs;
        }
        this.tiptapEditor.chain().focus().command(adjustSelectionForValidInsertion).insertContent([{ type, attrs, content }]).run();
        return id;
      },
      insertBlockWithBlankLines: (pluginType, data = {}, settings = {}) => {
        const defaultSettings = {
          updateSelection: true,
          skipBlankLineBefore: true,
          skipBlankLineAfter: true
        };
        const mergedSettings = { ...defaultSettings, ...settings };
        const type = import_consts.TO_TIPTAP_TYPE[pluginType];
        let id = "";
        if (!type) {
          console.error(`No such plugin type ${pluginType}`);
          return id;
        }
        id = data.id || (0, import_ricos_content.generateId)();
        let { content, ..._attrs } = data;
        let attrs = { id, ...flatComponentState(_attrs) };
        if (type === import_ricos_content.TIPTAP_FIGURE_TYPE && !content) {
          const normalizedData = normalizeFigureData(pluginType, data, id);
          content = normalizedData.content;
          attrs = normalizedData.attrs;
        }
        const { updateSelection } = mergedSettings;
        this.tiptapEditor.chain().focus().command(adjustSelectionForValidInsertion).command(({ commands, dispatch, tr }) => {
          if (!dispatch) {
            return true;
          }
          const selectionRange = { from: tr.selection.from, to: tr.selection.to };
          const insertPos = mergedSettings.pos ?? getLayoutInsertPos(tr, pluginType) ?? selectionRange;
          const cmd = commands.insertContentAt(insertPos, [
            ...mergedSettings.skipBlankLineBefore ? [] : [{ type: import_v1.Node_Type.PARAGRAPH, attrs: { id: (0, import_ricos_content.generateId)() } }],
            { type, attrs, content },
            ...mergedSettings.skipBlankLineAfter ? [] : [{ type: import_v1.Node_Type.PARAGRAPH, attrs: { id: (0, import_ricos_content.generateId)() } }]
          ]);
          return dispatch(cmd);
        }).command(({ commands, dispatch, tr }) => {
          if (!updateSelection || !dispatch) {
            return false;
          }
          const nodeWithPos = (0, import_helpers.findNodeById)(tr, id)[0];
          if (!nodeWithPos) {
            return false;
          }
          const selectCommand = updateSelection === "text" ? commands.setTextSelection(nodeWithPos.pos) : commands.setNodeSelection(nodeWithPos.pos);
          return dispatch(selectCommand);
        }).run();
        return id;
      },
      deleteBlock: (nodeId) => {
        const nodesWithPos = (0, import_helpers.findNodeById)(this.tiptapEditor.state.tr, nodeId);
        if (nodesWithPos[0].node.type.name === import_ricos_content.TIPTAP_IMAGE_TYPE) {
          const figures = this.tiptapEditor.$nodes(import_ricos_content.TIPTAP_FIGURE_TYPE);
          const selectedFigure = figures?.find((f) => {
            return f.firstChild?.node.attrs.id === nodeId;
          });
          if (selectedFigure) {
            return this.tiptapEditor.commands.deleteNode(selectedFigure.attributes.id);
          }
          return this.tiptapEditor.commands.deleteNode(nodeId);
        }
        return this.tiptapEditor.commands.deleteNode(nodeId);
      },
      setBlock: (nodeId, _, data) => {
        return this.tiptapEditor.commands.setNodeAttrsById(nodeId, flatComponentState(data));
      },
      updateBlock: (nodeId, _, data) => {
        return this.tiptapEditor.commands.updateNodeAttrsById(nodeId, flatComponentState(data));
      },
      getColor: (colorType) => this.services.content.resolve(
        colorType === "ricos-text-color" ? import_get_text_color_in_selection.getTextColorInSelection : import_get_highligh_color_in_selection.getHighlightColorInSelection
      ),
      getSelection: () => {
        const {
          state: {
            doc,
            selection: { from, to }
          }
        } = this.tiptapEditor;
        const selectedNodes = [];
        doc.nodesBetween(from, to, (node) => {
          selectedNodes.push(node);
        });
        const hasSelectionNodes = selectedNodes.length > 0;
        return {
          isFocused: this.tiptapEditor.isFocused,
          isCollapsed: this.tiptapEditor.state.selection.empty,
          startKey: hasSelectionNodes ? selectedNodes[0].attrs.id : "",
          endKey: hasSelectionNodes ? selectedNodes[selectedNodes.length - 1].attrs.id : "",
          textContent: doc.cut(from, to).textContent,
          selectedNodes,
          isEditorOrPortalFocused: () => {
            if (this.tiptapEditor.isFocused) {
              return true;
            }
            const activeElement = document.activeElement;
            const ricosPortal = this.services.context.portal;
            if (!activeElement || !ricosPortal) {
              return false;
            }
            return ricosPortal.contains(activeElement);
          }
        };
      },
      getSelectionSlice: () => {
        const state = this.tiptapEditor.state;
        if (this.tiptapEditor.state.selection.empty) {
          return void 0;
        }
        const content = state.selection.content();
        if ([import_ricos_content.TIPTAP_IMAGE_TYPE, import_ricos_content.TIPTAP_GIF_TYPE, import_ricos_content.TIPTAP_VIDEO_TYPE].includes(
          content.content.firstChild?.type.name
        )) {
          const figureContent = import_state.NodeSelection.create(state.doc, state.selection.from - 1).content().toJSON();
          return this.services.converters.fromPmNodeChildren(figureContent);
        }
        return this.services.converters.fromPmNodeChildren(content.toJSON());
      },
      insertDecoration: (type, data, settings) => {
        const decorationCommandMap = {
          [import_ricos_content.RICOS_LINK_TYPE]: (data2) => ({
            command: "setLink",
            args: { link: data2 }
          }),
          [import_ricos_content.RICOS_ANCHOR_TYPE]: (data2) => ({
            command: "setAnchor",
            args: data2
          }),
          [import_ricos_content.RICOS_TEXT_COLOR_TYPE]: (data2) => ({
            command: "setColor",
            args: data2.color
          }),
          [import_ricos_content.RICOS_TEXT_HIGHLIGHT_TYPE]: (data2) => ({
            command: "setHighlight",
            args: data2.color
          }),
          [import_ricos_content.RICOS_MENTION_TYPE]: (data2) => ({
            command: "insertMention",
            args: data2.mention
          }),
          [import_ricos_content.RICOS_INDENT_TYPE]: () => ({ command: "indent", args: void 0 }),
          [import_ricos_content.RICOS_FONT_SIZE_TYPE]: (data2) => ({
            command: "setFontSize",
            args: parseInt(data2.fontSize, 10)
          }),
          FONT_FAMILY: (data2) => {
            return {
              command: "setFontFamily",
              args: data2.value
            };
          },
          [import_ricos_content.RICOS_LINE_SPACING_TYPE]: (data2) => ({
            command: "setLineSpacings",
            args: data2.data
          })
        };
        const decorationCommand = decorationCommandMap[type];
        if (decorationCommand) {
          const { command, args } = decorationCommand(data);
          const editorCommand = settings?.shouldFocus ? this.tiptapEditor.chain().focus() : this.tiptapEditor.chain();
          editorCommand[command](args).run();
        } else {
          console.error(`${type} decoration not supported`);
        }
      },
      insertMultipleAnchors: (anchors) => {
        const content = anchors.map((anchor) => {
          return this.tiptapEditor.schema.nodes.PARAGRAPH.create(
            null,
            this.tiptapEditor.schema.text(anchor.defaultName || "", [
              this.tiptapEditor.schema.marks.ANCHOR.create(anchor),
              this.tiptapEditor.schema.mark(import_ricos_types.Mark_Type.UNDERLINE)
            ])
          ).toJSON();
        });
        return this.tiptapEditor.commands.insertContent(content);
      },
      getFontSize: () => {
        return this.services.content.resolve(import_get_font_size_in_selection.getFontSizeInSelection);
      },
      getFontFamily: () => {
        return this.services.content.resolve(import_get_font_family_in_selection.getFontFamilyInSelection);
      },
      hasLinkInSelection: (options) => {
        const {
          state: {
            doc,
            selection: { from, to }
          }
        } = this.tiptapEditor;
        const selectionFrom = options?.inclusive ? from - 1 : from;
        const marks = {};
        doc.nodesBetween(selectionFrom, to, (node) => {
          node.marks.forEach(({ type: { name } }) => {
            marks[name] = true;
          });
        });
        return !!(marks[import_v1.Decoration_Type.LINK] || marks[import_v1.Decoration_Type.ANCHOR]);
      },
      selectLinkDecoration: (decoration, options) => {
        const decorationTypeMap = {
          [import_ricos_content.RICOS_LINK_TYPE]: import_v1.Decoration_Type.LINK,
          [import_ricos_content.RICOS_ANCHOR_TYPE]: import_v1.Decoration_Type.ANCHOR
        };
        const decorationMarkType = decorationTypeMap[decoration];
        if (!decorationMarkType) {
          console.error(`${decoration} decoration not supported`);
        }
        const {
          state: {
            doc,
            selection: { from, to }
          }
        } = this.tiptapEditor;
        const selectionFrom = options?.inclusive ? from - 1 : from;
        const decoratedNodes = (0, import_tiptap.findChildrenInRange)(doc, { from: selectionFrom, to }, (child) => {
          return !!child.marks?.find((mark) => mark.type.name === decorationMarkType);
        });
        const nodeWithPos = decoratedNodes[0];
        if (nodeWithPos) {
          nodeWithPos && this.tiptapEditor.commands.setNodeSelection(nodeWithPos.pos);
        } else {
          console.error(`${decoration} node with decoration not found`);
        }
      },
      getLinkDataInSelection: (options) => {
        const {
          state: {
            doc,
            selection: { from, to }
          }
        } = this.tiptapEditor;
        const selectionFrom = options?.inclusive ? from - 1 : from;
        let link;
        doc.nodesBetween(selectionFrom, to, (node) => {
          node.marks.forEach((mark) => {
            const {
              type: { name }
            } = mark;
            if (name === import_v1.Decoration_Type.LINK) {
              link = mark.attrs.link;
            } else if (name === import_v1.Decoration_Type.ANCHOR) {
              link = { anchor: mark.attrs.anchor };
            }
          });
        });
        return link;
      },
      setBlockType: (type) => {
        const blockTypeCommandMap = {
          // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
          // @ts-ignore
          [import_ricos_content.UNSTYLED]: () => this.tiptapEditor.chain().focus().setParagraph().run(),
          [import_ricos_content.HEADER_BLOCK.ONE]: () => (
            // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
            // @ts-ignore
            this.tiptapEditor.chain().focus().toggleHeading({ level: 1 }).run()
          ),
          [import_ricos_content.HEADER_BLOCK.TWO]: () => (
            // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
            // @ts-ignore
            this.tiptapEditor.chain().focus().toggleHeading({ level: 2 }).run()
          ),
          [import_ricos_content.HEADER_BLOCK.THREE]: () => (
            // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
            // @ts-ignore
            this.tiptapEditor.chain().focus().toggleHeading({ level: 3 }).run()
          ),
          [import_ricos_content.HEADER_BLOCK.FOUR]: () => (
            // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
            // @ts-ignore
            this.tiptapEditor.chain().focus().toggleHeading({ level: 4 }).run()
          ),
          [import_ricos_content.HEADER_BLOCK.FIVE]: () => (
            // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
            // @ts-ignore
            this.tiptapEditor.chain().focus().toggleHeading({ level: 5 }).run()
          ),
          [import_ricos_content.HEADER_BLOCK.SIX]: () => (
            // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
            // @ts-ignore
            this.tiptapEditor.chain().focus().toggleHeading({ level: 6 }).run()
          ),
          // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
          // @ts-ignore
          [import_ricos_content.BLOCKQUOTE]: () => this.tiptapEditor.commands.toggleBlockquote(),
          // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
          // @ts-ignore
          [import_ricos_content.CODE_BLOCK_TYPE]: () => this.tiptapEditor.commands.toggleCodeBlock(),
          // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
          // @ts-ignore
          [import_ricos_content.BULLET_LIST_TYPE]: () => this.tiptapEditor.commands.toggleBulletList(),
          [import_ricos_content.CHECKBOX_LIST_TYPE]: () => this.tiptapEditor.commands.toggleCheckboxList(),
          // oxlint-disable-next-line @typescript-oxlint/ban-ts-comment
          // @ts-ignore
          [import_ricos_content.NUMBERED_LIST_TYPE]: () => this.tiptapEditor.commands.toggleOrderedList()
        };
        const currentSetBlockTypeCommand = blockTypeCommandMap[type];
        if (currentSetBlockTypeCommand) {
          currentSetBlockTypeCommand();
        } else {
          throw new Error(`${type} block type not supported`);
        }
      },
      // What the hell is block type lol. Is like, collapsible list not a block type?
      isBlockTypeSelected: (type) => {
        const blockTypeActiveCommandMap = {
          [import_ricos_content.UNSTYLED]: () => this.tiptapEditor.isActive("unstyled"),
          // This is the ONLY correct way to check if a node/mark is active
          // Node_Type shouldn't be used BUT its better than nothing
          [import_ricos_content.HEADER_BLOCK.ONE]: () => this.tiptapEditor.isActive(import_v1.Node_Type.HEADING, { level: 1 }),
          [import_ricos_content.HEADER_BLOCK.TWO]: () => this.tiptapEditor.isActive(import_v1.Node_Type.HEADING, { level: 2 }),
          [import_ricos_content.HEADER_BLOCK.THREE]: () => this.tiptapEditor.isActive(import_v1.Node_Type.HEADING, { level: 3 }),
          [import_ricos_content.HEADER_BLOCK.FOUR]: () => this.tiptapEditor.isActive(import_v1.Node_Type.HEADING, { level: 4 }),
          [import_ricos_content.HEADER_BLOCK.FIVE]: () => this.tiptapEditor.isActive(import_v1.Node_Type.HEADING, { level: 5 }),
          [import_ricos_content.HEADER_BLOCK.SIX]: () => this.tiptapEditor.isActive(import_v1.Node_Type.HEADING, { level: 6 }),
          [import_ricos_content.CODE_BLOCK_TYPE]: () => this.tiptapEditor.isActive(import_v1.Node_Type.CODE_BLOCK),
          [import_ricos_content.BLOCKQUOTE]: () => this.tiptapEditor.isActive(import_v1.Node_Type.BLOCKQUOTE),
          [import_ricos_content.NUMBERED_LIST_TYPE]: () => this.tiptapEditor.isActive(import_v1.Node_Type.ORDERED_LIST),
          [import_ricos_content.BULLET_LIST_TYPE]: () => this.tiptapEditor.isActive(import_v1.Node_Type.BULLETED_LIST),
          [import_ricos_content.CHECKBOX_LIST_TYPE]: () => this.tiptapEditor.isActive(import_v1.Node_Type.CHECKBOX_LIST)
        };
        const currentBlockTypeActiveCommand = blockTypeActiveCommandMap[type];
        if (currentBlockTypeActiveCommand) {
          return currentBlockTypeActiveCommand();
        } else {
          throw new Error(`${type} block type not supported`);
        }
      },
      deleteDecoration: (type) => {
        switch (type) {
          case import_ricos_content.RICOS_LINK_TYPE:
            this.tiptapEditor.commands.unsetLink();
            return;
          case import_ricos_content.RICOS_ANCHOR_TYPE:
            this.tiptapEditor.commands.unsetAnchor();
            return;
          case import_ricos_content.RICOS_INDENT_TYPE:
            this.tiptapEditor.commands.outdent();
            return;
          case import_ricos_content.RICOS_TEXT_COLOR_TYPE:
            this.tiptapEditor.commands.unsetColor();
            return;
          case import_ricos_content.RICOS_TEXT_HIGHLIGHT_TYPE:
            this.tiptapEditor.commands.unsetHighlight();
            return;
          default:
            console.error(`delete ${type} decoration type not supported`);
        }
      },
      setTextAlignment: (alignment) => {
        this.tiptapEditor.chain().focus().setTextAlign(alignment).run();
      },
      undo: () => this.tiptapEditor.chain().focus().undo().run(),
      redo: () => this.tiptapEditor.chain().focus().redo().run(),
      insertText: (text, options = { preventAutolink: false }) => this.tiptapEditor.chain().focus().command(({ tr }) => {
        tr.insertText(text).setMeta("preventAutolink", options.preventAutolink);
        return true;
      }).run(),
      getAllBlocksKeys: () => {
        const keys = [];
        this.tiptapEditor.state.doc.descendants((node) => {
          keys.push(node.attrs.id);
        });
        return keys;
      },
      getBlockComponentData: (id) => {
        const nodesWithPos = (0, import_helpers.findNodeById)(this.tiptapEditor.state.tr, id);
        if (nodesWithPos[0]) {
          const { node } = nodesWithPos[0];
          return node.attrs;
        } else {
          console.error("Failed to find node and return its data");
        }
      },
      resetDocumentStyleByNodeType: (nodeType) => {
        this.tiptapEditor.chain().focus().unsetAllMarks().resetDocumentStyleByNodeType(nodeType).run();
      },
      updateDocumentStyle: (_documentStyles) => {
        this.tiptapEditor.commands.updateDocumentStyleBySelectedNode();
      },
      clearSelectedBlocksInlineStyles: () => {
        this.tiptapEditor.commands.unsetAllMarks();
      },
      getCurrentHeading: () => {
        return this.services.content.resolve(import_get_heading_in_selection.getHeadingInSelection);
      },
      triggerDecoration: (type) => {
        const triggerDecorationsMap = {
          [import_ricos_content.RICOS_MENTION_TYPE]: () => this.tiptapEditor.chain().focus().command(({ tr }) => {
            tr.insertText(" @");
            return true;
          }).run()
        };
        triggerDecorationsMap[type]?.();
      },
      softNewLine: () => {
        this.tiptapEditor.commands.setHardBreak();
      },
      clearEditorContent: (triggerUpdate = false) => {
        this.tiptapEditor.commands.clearContent(triggerUpdate);
      },
      setSpotlight: (list) => {
        this.tiptapEditor.commands.setSpotlightList(list);
      },
      // applies changes and returns reverse changes
      injectNodes: (args) => {
        const reverts = {};
        this.tiptapEditor.commands.injectNodes(args, reverts);
        return reverts.changes || [];
      },
      triggerInlineAi: (args) => {
        this.tiptapEditor.commands.triggerInlineAi({
          ...args,
          selection: this.getEditorCommands().getSelectionSlice() ?? []
        });
      },
      toggleAiSuggestions: (visible) => {
        this.tiptapEditor.commands.toggleSuggestions(visible);
      },
      setContent: (content, options) => {
        const nodes = [
          { nodes: content.nodes, position: { type: "range" } }
        ];
        if (options?.skipHistory) {
          return this.tiptapEditor.chain().command(({ tr }) => {
            tr.setMeta("addToHistory", false);
            return true;
          }).injectNodes(nodes, {}).run();
        }
        return this.tiptapEditor.commands.injectNodes(nodes, {});
      }
    };
  }
}
const flatComponentState = (data) => {
  const { componentState, ...rest } = data;
  return { ...rest || {}, ...componentState || {} };
};
const normalizeFigureData = (pluginType, data, mediaId) => {
  const isImage = [import_ricos_content.RICOS_IMAGE_TYPE, import_ricos_content.IMAGE_TYPE].includes(pluginType);
  const isGif = [import_ricos_content.RICOS_GIPHY_TYPE, import_ricos_content.GIPHY_TYPE].includes(pluginType);
  return {
    content: [
      {
        type: isImage ? import_ricos_content.TIPTAP_IMAGE_TYPE : isGif ? import_ricos_content.TIPTAP_GIF_TYPE : import_ricos_content.TIPTAP_VIDEO_TYPE,
        attrs: {
          id: mediaId,
          ...data
        }
      },
      {
        type: import_ricos_content.TIPTAP_CAPTION_TYPE
      }
    ],
    attrs: {
      id: (0, import_ricos_content.generateId)()
    }
  };
};
const getLayoutInsertPos = (tr, pluginType) => {
  if (pluginType !== import_ricos_content.RICOS_LAYOUT_TYPE) {
    return void 0;
  }
  const $from = tr.doc.resolve(tr.selection.from);
  const parentLayout = (0, import_tiptap.findParentNodeClosestToPos)(
    $from,
    (node) => node.type.name === import_ricos_content.TIPTAP_LAYOUT_TYPE
  );
  return parentLayout ? parentLayout.pos + parentLayout.node.nodeSize : void 0;
};
const adjustSelectionForValidInsertion = ({ dispatch, tr }) => {
  if (dispatch === void 0) {
    return true;
  }
  const { selection } = tr;
  const { from, to } = selection;
  const resolvedFrom = tr.doc.resolve(from);
  const resolvedTo = tr.doc.resolve(to);
  const isFigureChildSelected = resolvedFrom.nodeAfter?.type.spec.group?.includes("figureFirstChildContent");
  if (isFigureChildSelected && from === to - 1) {
    tr.setSelection(import_state.NodeSelection.create(tr.doc, from - 1));
    dispatch(tr);
    return true;
  }
  const isFromCaption = resolvedFrom.parent.type.name === import_ricos_content.TIPTAP_CAPTION_TYPE;
  const isToCaption = resolvedTo.parent.type.name === import_ricos_content.TIPTAP_CAPTION_TYPE;
  if (!isFromCaption && !isToCaption) {
    return true;
  }
  if (from === to || resolvedFrom.parent.attrs.id === resolvedTo.parent.attrs.id) {
    const nodeAfter = tr.doc.resolve(resolvedFrom.after());
    tr.setSelection(import_state.TextSelection.create(tr.doc, nodeAfter.pos, nodeAfter.pos));
    dispatch(tr);
    return true;
  }
  const posFrom = isFromCaption ? tr.doc.resolve(resolvedFrom.after()).pos : from;
  const posTo = isToCaption ? tr.doc.resolve(resolvedTo.before()).pos - 1 : to;
  tr.setSelection(import_state.TextSelection.create(tr.doc, posFrom, posTo));
  dispatch(tr);
  return true;
};
const toExternalAddButtonsToolbarConfigs = (addButtons, toolbarSettingsFunctions, toolbarType, t, pluginsEvents, publicCommands, isMobile) => {
  const buttonsType = isMobile ? "mobile" : "desktop";
  const externalAddPluginToolbarItemsConfig = toExternalAddPluginToolbarItemsConfig(
    toolbarSettingsFunctions,
    addButtons,
    toolbarType,
    buttonsType
  );
  return externalAddPluginToolbarItemsConfig.reduce((acc, b) => {
    const buttonConfig = toExternalToolbarAddButtonConfig(b, t, pluginsEvents, publicCommands);
    return {
      ...acc,
      [buttonConfig.name || ""]: buttonConfig
    };
  }, {});
};
const pluginButtonNames = Object.values(import_editor_common.INSERT_PLUGIN_BUTTONS);
const initToolbarSettings = (toolbarSettings) => {
  const textButtons = {
    mobile: import_default_text_formatting_buttons.mobileTextButtonList,
    desktop: import_default_text_formatting_buttons.desktopTextButtonList
  };
  const defaultSettings = (0, import_default_toolbar_settings.getDefaultToolbarSettings)({ textButtons, pluginButtonNames });
  if (!toolbarSettings?.getToolbarSettings) {
    return defaultSettings;
  }
  const customSettings = toolbarSettings.getToolbarSettings({
    textButtons,
    pluginButtonNames
  });
  return (0, import_merge_toolbar_settings.mergeToolbarSettings)({ defaultSettings, customSettings });
};
const toExternalAddPluginToolbarItemsConfig = (toolbarConfig, addButtons, toolbarType, buttonsType) => {
  if (!toolbarConfig) {
    console.error(`${toolbarType} doesn't exists`);
    return [];
  }
  const buttonsListFromConfig = (0, import_get_buttons_list_from_config.getButtonsListFromConfig)(toolbarConfig, buttonsType);
  const externalToolbarItemsConfig = [];
  buttonsListFromConfig.map(fromConfigToSchemaBasedId).forEach((button) => {
    const buttonConfig = addButtons.find((b) => b.id === button);
    if (buttonConfig) {
      externalToolbarItemsConfig.push(buttonConfig);
    }
  });
  return externalToolbarItemsConfig;
};
const fromConfigToSchemaBasedId = (insertButtonId) => {
  const specificMapping = {
    [import_editor_common.INSERT_PLUGIN_BUTTONS.IMAGE]: import_v1.Node_Type.IMAGE,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.SHAPE]: import_v1.Node_Type.SHAPE,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.GALLERY]: import_v1.Node_Type.GALLERY,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.POLLS]: import_v1.Node_Type.POLL,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.DIVIDER]: import_v1.Node_Type.DIVIDER,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.HTML]: `${import_v1.Node_Type.HTML}.html`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.VIDEO]: `${import_v1.Node_Type.VIDEO}.video`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.INSTAGRAM]: `${import_v1.Node_Type.LINK_PREVIEW}.instagram`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.YOUTUBE]: `${import_v1.Node_Type.VIDEO}.youTube`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.TIKTOK]: `${import_v1.Node_Type.LINK_PREVIEW}.tiktok`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.TWITTER]: `${import_v1.Node_Type.LINK_PREVIEW}.twitter`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.PINTEREST]: `${import_v1.Node_Type.LINK_PREVIEW}.pinterest`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.FACEBOOK]: `${import_v1.Node_Type.LINK_PREVIEW}.facebook`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.STORES]: `${import_v1.Node_Type.APP_EMBED}.product`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.EVENTS]: `${import_v1.Node_Type.APP_EMBED}.event`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.BOOKINGS]: `${import_v1.Node_Type.APP_EMBED}.booking`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.BUTTON]: import_v1.Node_Type.BUTTON,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.CODE_BLOCK]: import_v1.Node_Type.CODE_BLOCK,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.SOUND_CLOUD]: `${import_v1.Node_Type.AUDIO}.soundCloud`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.GIF]: import_v1.Node_Type.GIF,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.FILE]: import_v1.Node_Type.FILE,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.EMOJI]: "wix-draft-plugin-emoji",
    [import_editor_common.INSERT_PLUGIN_BUTTONS.UNDO]: "UNDO",
    [import_editor_common.INSERT_PLUGIN_BUTTONS.REDO]: "REDO",
    [import_editor_common.INSERT_PLUGIN_BUTTONS.TABLE]: import_v1.Node_Type.TABLE,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.COLLAPSIBLE_LIST]: import_v1.Node_Type.COLLAPSIBLE_LIST,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.ADSENSE]: `${import_v1.Node_Type.HTML}.adsense`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.AUDIO]: `${import_v1.Node_Type.AUDIO}.audio`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.SPOTIFY]: `${import_v1.Node_Type.AUDIO}.spotify`,
    [import_editor_common.INSERT_PLUGIN_BUTTONS.LAYOUT]: `${import_v1.Node_Type.LAYOUT}.insert`
  };
  const id = specificMapping[insertButtonId];
  if (!id) {
    console.error(`toSchemaBasedId: unknown insertButtonId: ${insertButtonId}`);
  }
  return id;
};
const toExternalToolbarAddButtonConfig = (button, t, pluginsEvents, publicCommands) => {
  return {
    type: "button",
    tooltip: t(button.tooltip),
    toolbars: button.toolbars,
    getIcon: () => button.icon,
    getLabel: () => t(button.label),
    onClick: (_e) => {
      pluginsEvents.publishers.byTopic("ricos.toolbars.functionality.buttonClick").publish({
        toolbarType: import_editor_common.TOOLBARS.EXTERNAL,
        buttonId: button.id
      });
      pluginsEvents.publishPluginAdd({
        pluginId: button.id,
        entryPoint: import_editor_common.TOOLBARS.EXTERNAL
      });
      return button.command({
        publicCommands,
        // @ts-ignore
        referenceElement: {
          getBoundingClientRect: () => {
            const x = window.innerWidth / 2;
            const y = window.innerHeight / 2;
            return new DOMRect(x, y, 0, 0);
          }
        }
      });
    },
    isActive: () => false,
    isDisabled: () => false,
    dataHook: button.dataHook,
    name: button.label
  };
};
const toExternalTextButtonsToolbarConfigs = ({
  textButtons,
  services,
  toolbarSettingsFunctions,
  toolbarType,
  publicCommands,
  editor,
  isMobile,
  editorQuery
}) => {
  const buttonsType = isMobile ? "mobile" : "desktop";
  const externalToolbarItemsConfig = toExternalTextButtonsToolbarItemsConfig(
    toolbarSettingsFunctions,
    textButtons,
    toolbarType,
    buttonsType
  );
  return externalToolbarItemsConfig.reduce((acc, b) => {
    const buttonConfig = toExternalToolbarTextButtonConfig(
      b,
      publicCommands,
      editor,
      editorQuery,
      services
    );
    return {
      ...acc,
      [buttonConfig.name || ""]: buttonConfig
    };
  }, {});
};
const toExternalPluginToolbarButtons = ({
  buttons,
  editor,
  publicCommands,
  modals
}) => {
  return buttons.reduce((acc, toolbarButton) => {
    const { button, services } = toolbarButton;
    const { content } = services;
    const attributes = (0, import_utils.fromEntries)(
      Object.entries(button.attributes || {}).map(([key, value]) => {
        return value ? [key, content.resolve(value)] : [key, void 0];
      })
    );
    if (attributes.visible === false) {
      return acc;
    }
    return {
      ...acc,
      [button.id]: button.type === "separator" ? {
        type: "separator",
        getIcon: () => button.icon,
        getLabel: () => {
        },
        onClick: () => {
        },
        isActive: () => false,
        isDisabled: () => false
      } : {
        type: button.type,
        tooltip: services.t(
          (typeof button.tooltip === "function" ? button.tooltip({ isActive: !!attributes.active }) : button.tooltip) || ""
        ),
        toolbars: [],
        getIcon: () => "getIcon" in button ? button.getIcon?.({ services, attributes }) : "icon" in button ? button.icon : void 0,
        getLabel: () => "label" in button && button.label ? services.t(button.label) : void 0,
        onClick: (e) => {
          const returnValue = button?.command?.({
            referenceElement: e?.referenceElement ?? e?.target,
            tiptapEditor: editor,
            publicCommands,
            attributes,
            modals,
            isMobile: services.context.isMobile,
            getComponentProps: "getComponentProps" in button ? button.getComponentProps : void 0
          });
          const node = attributes.selectedNode;
          services.pluginsEvents.publishPluginToolbarClick({
            pluginId: node?.type?.name,
            nodeId: node?.attrs?.id,
            buttonName: button?.id,
            value: e?.value
          });
          return returnValue;
        },
        componentProps: "getComponentProps" in button ? button.getComponentProps?.({
          tiptapEditor: editor,
          attributes,
          publicCommands,
          t: services.t,
          modals,
          languageDir: services.context.languageDir
        }) : void 0,
        isActive: () => !!attributes.active,
        isDisabled: () => !!attributes.disabled,
        dataHook: button.dataHook,
        name: button.id
      }
    };
  }, {});
};
const getToolbarConfig = (toolbarSettings, toolbarType) => {
  const finalToolbarSettings = initToolbarSettings(toolbarSettings);
  const toolbarConfig = finalToolbarSettings.find((setting) => setting.name === toolbarType);
  return toolbarConfig;
};
const toExternalTextButtonsToolbarItemsConfig = (toolbarConfig, textButtons, toolbarType, buttonsType) => {
  if (!toolbarConfig) {
    console.error(`${toolbarType} doesn't exists`);
    return [];
  }
  const buttonsListFromConfig = (0, import_get_buttons_list_from_config.getButtonsListFromConfig)(toolbarConfig, buttonsType);
  const buttonsList = buttonsListFromConfig.map(handleDeprecatedButtons).map(import_map_buttons_from_config.mapButtonsFromConfig).map(import_to_schema_base_id.toSchemaBasedId);
  const externalToolbarItemsConfig = buttonsList.flatMap((button) => {
    const buttonConfig = textButtons.find((b) => b.id === button);
    if (buttonConfig) {
      return [buttonConfig];
    }
    return [];
  });
  return externalToolbarItemsConfig;
};
const handleDeprecatedButtons = (configButtonId) => {
  if (typeof configButtonId === "string") {
    return configButtonId;
  }
  if (configButtonId.name === "Alignment") {
    return import_editor_common.FORMATTING_BUTTONS.ALIGNMENT;
  }
};
const toExternalToolbarTextButtonConfig = (button, publicCommands, editor, editorQuery, services, tooltipHint) => {
  const attributes = (0, import_to_resolved_attributes.toResolvedAttributes)(button);
  const { modals, content, context, t, pluginsEvents, styles } = services;
  const name = button.id in toExternalType ? toExternalType[button.id] : button.id;
  if (button.type === "separator") {
    return {
      type: "separator",
      getIcon: () => button.presentation.icon
    };
  }
  return {
    type: button.type,
    tooltip: `${t(button.presentation.tooltip)} ${tooltipHint ? `(${tooltipHint})` : ""}`,
    toolbars: [],
    componentProps: button.type === "dropdown" ? button.presentation.getComponentProps?.({
      publicCommands,
      t,
      modals,
      styles,
      editor
    }) : void 0,
    getIcon: () => "getIcon" in button.presentation ? button.presentation.getIcon({ publicCommands, t }) : button.presentation.icon,
    getLabel: () => t(name),
    onClick: (e) => {
      pluginsEvents.publishers.byTopic("ricos.toolbars.functionality.buttonClick").publish({
        toolbarType: import_ricos_types.ToolbarType.EXTERNAL,
        buttonId: button.id
      });
      const referenceElement = e?.referenceElement ?? e?.target;
      return button.command?.({
        publicCommands,
        modalService: modals,
        editor,
        editorQuery,
        referenceElement,
        isMobile: context.isMobile,
        componentProps: "getComponentProps" in button.presentation ? button.presentation.getComponentProps({
          publicCommands,
          t,
          modals,
          editor,
          styles
        }) : void 0
      })({});
    },
    isActive: () => !!attributes.active && !!content.resolve(attributes.active),
    isDisabled: () => !!attributes.disabled && !!content.resolve(attributes.disabled),
    dataHook: button.presentation?.dataHook,
    name
  };
};
const toExternalType = {
  [import_v1.Decoration_Type.BOLD]: import_editor_common.FORMATTING_BUTTONS.BOLD,
  [import_v1.Decoration_Type.ITALIC]: import_editor_common.FORMATTING_BUTTONS.ITALIC,
  [import_v1.Decoration_Type.UNDERLINE]: import_editor_common.FORMATTING_BUTTONS.UNDERLINE,
  [import_v1.Decoration_Type.STRIKETHROUGH]: import_editor_common.FORMATTING_BUTTONS.STRIKETHROUGH,
  [`${import_v1.Node_Type.HEADING}.title`]: import_editor_common.FORMATTING_BUTTONS.TITLE,
  [import_v1.Node_Type.BLOCKQUOTE]: import_editor_common.FORMATTING_BUTTONS.BLOCKQUOTE,
  "TextAlignment.ALIGNMENT": import_editor_common.FORMATTING_BUTTONS.ALIGNMENT,
  "TextAlignment.LEFT": import_editor_common.FORMATTING_BUTTONS.ALIGN_LEFT,
  "TextAlignment.CENTER": import_editor_common.FORMATTING_BUTTONS.ALIGN_CENTER,
  "TextAlignment.RIGHT": import_editor_common.FORMATTING_BUTTONS.ALIGN_RIGHT,
  "TextAlignment.JUSTIFY": import_editor_common.FORMATTING_BUTTONS.ALIGN_JUSTIFY,
  [import_v1.Node_Type.ORDERED_LIST]: import_editor_common.FORMATTING_BUTTONS.ORDERED_LIST,
  [import_v1.Node_Type.BULLETED_LIST]: import_editor_common.FORMATTING_BUTTONS.UNORDERED_LIST,
  [import_v1.Node_Type.CHECKBOX_LIST]: import_editor_common.FORMATTING_BUTTONS.CHECKBOX_LIST,
  [import_v1.Decoration_Type.FONT_SIZE]: import_editor_common.FORMATTING_BUTTONS.FONT_SIZE,
  [import_v1.Decoration_Type.SPOILER]: import_editor_common.FORMATTING_BUTTONS.SPOILER,
  [import_v1.Decoration_Type.LINK]: import_editor_common.FORMATTING_BUTTONS.LINK,
  [`${import_v1.Node_Type.HEADING}.dropdown`]: import_editor_common.FORMATTING_BUTTONS.HEADINGS,
  [`${import_v1.Decoration_Type.COLOR}.foreground`]: import_editor_common.FORMATTING_BUTTONS.TEXT_COLOR,
  [`${import_v1.Decoration_Type.COLOR}.background`]: import_editor_common.FORMATTING_BUTTONS.TEXT_HIGHLIGHT,
  [import_v1.Node_Type.CODE_BLOCK]: import_editor_common.FORMATTING_BUTTONS.CODE_BLOCK,
  LINE_SPACING: import_editor_common.FORMATTING_BUTTONS.LINE_SPACING,
  [`INDENT.increase`]: import_editor_common.FORMATTING_BUTTONS.INCREASE_INDENT,
  [`INDENT.decrease`]: import_editor_common.FORMATTING_BUTTONS.DECREASE_INDENT
};
const isPluginToolbarVisible = (selection, doc) => {
  if (!selection || selection.empty || !(selection instanceof import_state.NodeSelection)) {
    return false;
  }
  try {
    let hasNonEmptyParagraph = false;
    doc.nodesBetween(selection.from, selection.to, (node) => {
      if (node.type.name === "text" && node.text !== "") {
        hasNonEmptyParagraph = true;
        return false;
      }
    });
    return hasNonEmptyParagraph && (0, import_editor_common.isTextSelection)(selection);
  } catch (error) {
    console.error("Error checking if plugin toolbar is visible", error);
    return false;
  }
};
//# sourceMappingURL=rich-content-adapter.js.map
