"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 ricos_orchestrator_exports = {};
__export(ricos_orchestrator_exports, {
  RicosOrchestrator: () => RicosOrchestrator
});
module.exports = __toCommonJS(ricos_orchestrator_exports);
var A = __toESM(require("fp-ts-esm/Array"));
var import_function = require("fp-ts-esm/function");
var import_lodash = __toESM(require("lodash"));
var import_collect = require("./../pm-converters/collect.js");
var import_ricos_common_plugins = require("./../ricos-common-plugins/index.js");
var import_ricos_content_query = require("./../ricos-content-query/index.js");
var import_is_editor_plugin = require("./../ricos-editor/utils/is-editor-plugin.js");
var import_ricos_events = require("./../ricos-events/index.js");
var import_ricos_plugins = require("./../ricos-plugins/index.js");
var import_ricos_shortcuts = require("./../ricos-shortcuts/index.js");
var import_ricos_styles = require("./../ricos-styles/index.js");
var import_log_invariant = require("./../_shared/log-invariant.js");
var import_update_service = require("./../_shared/upload/update-service.js");
var import_upload_service = require("./../_shared/upload/upload-service.js");
var import_wix_rich_content_common = require("./../wix-rich-content-common/index.js");
var import_toolbars_v3 = require("./../toolbars-v3/index.js");
var import_helpers_config = require("./helpers-config.js");
var import_map_bi_callbacks_to_events = require("./map-bi-callbacks-to-events.js");
var import_orchestrate_events = require("./orchestrate-events.js");
var import_ricos_editor = require("./ricos-editor.js");
var import_ricos_schema = require("./ricos-schema.js");
class RicosOrchestrator {
  constructor({
    editorProps,
    t,
    platform,
    modalService,
    devService,
    wixInstance,
    makeRequestService,
    pluginsMap
  }) {
    /** Mutable ref updated by FullRicosEditor when BI helpers load asynchronously. */
    this.biHelpersRef = { current: {} };
    this.inlineAiService = {};
    this.inlineAiStateSelectorContextValue = void 0;
    this.toolbarStateSelectorContextValue = void 0;
    this.selectionSelectorContextValue = void 0;
    this.modalStateSelectorContextValue = void 0;
    this.pmContentSelectorContextValue = void 0;
    this.t = t;
    this.editorProps = editorProps;
    this.devService = devService;
    this.wixInstance = wixInstance;
    this.makeRequestService = makeRequestService;
    this.pluginsMap = pluginsMap;
    this.styles = new import_ricos_styles.RicosStyles();
    const getEditorQuery = () => {
      return this.editorQuery;
    };
    this.converters = (0, import_collect.collectPmConverters)(collectAllPlugins(this.editorProps, pluginsMap));
    this.content = import_toolbars_v3.Content.create([], {
      styles: this.styles,
      converters: this.converters,
      getEditorQuery,
      editor: null,
      modals: modalService
    });
    const isMobile = editorProps.isMobile || false;
    this.context = {
      t,
      debugMode: editorProps.debugMode || [],
      isMobile,
      languageDir: (0, import_wix_rich_content_common.getLangDir)(editorProps.locale),
      locale: editorProps.locale || "en",
      localeContent: editorProps.localeContent || editorProps.locale || "en",
      experiments: editorProps.experiments || {},
      platform: platform || "macOs",
      content: this.content,
      jsdomMode: editorProps.jsdomMode ?? false,
      environment: editorProps.environment || "liveSite",
      tabIndex: -1,
      portal: null,
      lastInteraction: null,
      tabFocusBehavior: editorProps.tabFocusBehavior || "edit"
    };
    this.updateService = (0, import_update_service.createUpdateService)();
    this.events = new import_ricos_events.RicosEvents(
      (editorProps.debugMode?.includes("events") || editorProps.debugMode?.includes("all")) ?? false
    );
    this.uploadService = new import_upload_service.UploadService(this.updateService);
    this.modals = modalService;
    this.shortcuts = new import_ricos_shortcuts.EditorKeyboardShortcuts(this.modals, {
      isDebugMode: (editorProps.debugMode?.includes("shortcuts") || editorProps.debugMode?.includes("all")) ?? false
    });
    this.pluginsEvents = new import_ricos_plugins.PluginsEvents();
    this.schema = new import_ricos_schema.RicosSchema(
      editorProps.content,
      this.converters,
      editorProps.shouldNormalizeRichContent ?? true
    );
    const focusShortcut = {
      name: "EnterToolbar",
      description: "ShortcutsSheet_ToolbarNavigation_EnterToolbar",
      group: "ShortcutsSheet_Section_ToolbarNavigation",
      keys: { macOs: "Ctrl+T", windows: "Alt+T" },
      command: ({ event }) => {
        event?.preventDefault();
        const focusFirstFocusableElement = (toolbarDataHook) => {
          const portalElement = this.context.portal || document;
          const toolbarElement = portalElement.querySelector(
            `[data-hook~=${toolbarDataHook}] [data-hook~=${import_toolbars_v3.TOOLBAR_VISIBLE}]`
          );
          const firstFocusableElement = toolbarElement?.querySelector(
            'a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), details, [tabindex]:not([tabindex="-1"]):not([disabled])'
          );
          firstFocusableElement?.focus();
        };
        focusFirstFocusableElement(import_toolbars_v3.FLOATING_FORMATTING_TOOLBAR);
        focusFirstFocusableElement(import_toolbars_v3.STATIC_TOOLBAR_DATA_HOOK);
        focusFirstFocusableElement(import_toolbars_v3.FLOATING_PLUGIN_TOOLBAR);
        return "continue";
      },
      enabled: true,
      showInShortcutSheet: true
    };
    this.shortcuts.register(focusShortcut);
    this.plugins = new import_ricos_plugins.EditorPlugins({
      modals: this.modals,
      uploadService: this.uploadService,
      updateService: this.updateService,
      shortcuts: this.shortcuts,
      t: this.t,
      content: this.content,
      styles: this.styles,
      pluginsEvents: this.pluginsEvents,
      context: this.context,
      schema: this.schema,
      converters: this.converters,
      devService,
      editorProps: this.editorProps,
      wixInstance,
      makeRequestService
    });
    this.registerAllPlugins(import_ricos_common_plugins.commonPluginConfig);
    if (editorProps.keyboardShortcuts) {
      editorProps.keyboardShortcuts.map(
        (shortcut) => this.shortcuts.mergeKeyboadShortcutProp(shortcut)
      );
    }
    this.editor = new import_ricos_editor.RicosEditor(
      this.editorProps,
      {
        styles: this.styles,
        plugins: this.plugins,
        updateService: this.updateService,
        uploadService: this.uploadService,
        t: this.t,
        content: this.content,
        shortcuts: this.shortcuts,
        modals: this.modals,
        pluginsEvents: this.pluginsEvents,
        context: this.context,
        schema: this.schema,
        getEditorQuery,
        converters: this.converters,
        devService,
        editorProps: this.editorProps,
        wixInstance,
        makeRequestService,
        inlineAi: this.inlineAiService
      },
      this.editorProps.debugMode?.includes("prosemirror") || editorProps.debugMode?.includes("all"),
      () => {
        if (!this.toolbarStateSelectorContextValue) {
          throw new Error("toolbarStateSelectorContextValue is not set");
        }
        return this.toolbarStateSelectorContextValue;
      },
      () => {
        if (!this.selectionSelectorContextValue) {
          throw new Error("selectionSelectorContextValue is not set");
        }
        return this.selectionSelectorContextValue;
      },
      () => {
        if (!this.modalStateSelectorContextValue) {
          throw new Error("modalStateSelectorContextValue is not set");
        }
        return this.modalStateSelectorContextValue;
      },
      () => {
        if (!this.pmContentSelectorContextValue) {
          throw new Error("pmContentSelectorContextValue is not set");
        }
        return this.pmContentSelectorContextValue;
      },
      () => {
        if (!this.inlineAiStateSelectorContextValue) {
          throw new Error("inlineAiStateSelectorContextValue is not set");
        }
        return this.inlineAiStateSelectorContextValue;
      }
    );
    this.plugins.setPublicCommands(this.editor.getPublicCommands());
    this.schema.setEditor(this.editor);
    this.content.update([], this.editor.adapter.tiptapEditor);
    this.updateService.setEditorCommands(this.editor.getPublicCommands());
    this.editorQuery = (0, import_ricos_content_query.editorQueryCreator)(
      this.editor.adapter.tiptapEditor,
      this.styles,
      this.converters
    );
    this.pluginExports = this.plugins.getExports();
    this.zIndexService = new import_ricos_styles.ZIndexService(
      !!editorProps.isMobile,
      editorProps.theme?.settingsStyles
    );
    if (!(0, import_wix_rich_content_common.isSSR)()) {
      window.editorQuery = this.editorQuery;
      window.ricosOrchestrator = this;
    }
    this.orchestrateEvents();
  }
  // NOTE: it is crucual to keep the event registration/subsciption order to ensure their correct workflow
  orchestrateEvents() {
    (0, import_orchestrate_events.registerEventSources)(this.events, [
      this.shortcuts,
      this.modals,
      this.editor,
      this.uploadService,
      this.pluginsEvents,
      this.styles
    ]);
    (0, import_orchestrate_events.registerEventSubscribers)(this.events, [this.modals]);
    (0, import_orchestrate_events.registerEventSubscribers)(this.events, [
      this.modals,
      this.editor,
      this.styles,
      this.pluginsEvents
    ]);
    (0, import_map_bi_callbacks_to_events.mapBiCallbacksToSubscriptions)(this.biHelpersRef, this.events, this.schema);
  }
  setUpdateServiceDom(setErrorNotifier, setFileInput) {
    this.uploadService.setErrorNotifier(setErrorNotifier);
    this.uploadService.setHiddenInputElement(setFileInput);
  }
  getServices() {
    return {
      styles: this.styles,
      plugins: this.plugins,
      uploadService: this.uploadService,
      updateService: this.updateService,
      t: this.t,
      shortcuts: this.shortcuts,
      content: this.content,
      modals: this.modals,
      editor: this.editor,
      pluginsEvents: this.pluginsEvents,
      context: this.context,
      schema: this.schema,
      zIndexService: this.zIndexService,
      getEditorQuery: () => this.editorQuery,
      converters: this.converters,
      devService: this.devService,
      editorProps: this.editorProps,
      wixInstance: this.wixInstance,
      makeRequestService: this.makeRequestService,
      inlineAi: this.inlineAiService
    };
  }
  getPluginExports() {
    return this.pluginExports;
  }
  registerAllPlugins(commonPluginConfig2) {
    const helpersConfig = (0, import_helpers_config.getHelpersConfig)(this.editorProps);
    (0, import_function.pipe)(
      collectAllPlugins(this.editorProps, this.pluginsMap),
      import_ricos_plugins.EditorPlugins.mergeConfig(this.editorProps.pluginConfig),
      import_ricos_plugins.EditorPlugins.mergeConfig(commonPluginConfig2),
      import_ricos_plugins.EditorPlugins.mergeConfig(helpersConfig),
      A.map((plugin) => this.plugins.register(plugin))
    );
  }
  setPortalRef(portal) {
    this.context.portal = portal;
  }
}
const collectAllPlugins = (editorProps, pluginsMap) => {
  const { plugins } = editorProps;
  const collectPluginsWithDependencies = (plugins2) => plugins2.flatMap((plugin) => [
    plugin,
    ...plugin.dependencies ? collectPluginsWithDependencies(plugin.dependencies) : []
  ]);
  const allOptions = plugins || [];
  const commonOptions = allOptions.filter(import_is_editor_plugin.isCommonPluginOptions);
  const pluginOptions = allOptions.filter((opt) => !(0, import_is_editor_plugin.isCommonPluginOptions)(opt));
  const resolvedPlugins = pluginOptions.map((options) => {
    if ("tiptapExtensions" in options) {
      return options;
    }
    const creator = pluginsMap[options.type];
    if (!creator) {
      (0, import_log_invariant.logInvariant)(new Error(`Unknown plugin type: ${options.type}. No resolver registered.`));
      return void 0;
    }
    return creator(options);
  });
  const collectedPlugins = collectPluginsWithDependencies([
    ...(0, import_ricos_common_plugins.commonPlugins)(editorProps, commonOptions),
    ...resolvedPlugins.filter((p) => !!p)
  ]);
  return import_lodash.default.uniq(collectedPlugins);
};
//# sourceMappingURL=ricos-orchestrator.js.map
