"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 extension_exports = {};
__export(extension_exports, {
  getTipTapExtensions: () => getTipTapExtensions,
  loadEmojiData: () => loadEmojiData
});
module.exports = __toCommonJS(extension_exports);
var import_prosemirror_state = require("prosemirror-state");
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_emoji_suggestions_modal = require("./modals/emoji-suggestions-modal.js");
const loadEmojiData = async () => {
  const { default: data } = await Promise.resolve().then(() => __toESM(require("@emoji-mart/data")));
  return data;
};
const getTipTapExtensions = () => [
  (0, import_tiptap_extensions.createRicosFunctionalExtension)({
    name: "emoji-suggestions",
    type: "extension",
    groups: [],
    reconfigure: (config, _extensions, _props, settings, services) => {
      return {
        ...config,
        addOptions() {
          return {
            services,
            ...settings
          };
        }
      };
    },
    createExtensionConfig: () => {
      return {
        name: "emoji-suggestions",
        priority: 110,
        addProseMirrorPlugins() {
          return [
            (0, import_suggestion.Suggestion)({
              editor: this.editor,
              pluginKey: new import_prosemirror_state.PluginKey("emojiSuggestions"),
              char: ":",
              allowedPrefixes: null,
              command: ({
                editor,
                props,
                range
              }) => {
                const { emoji, query } = props;
                const emojiQuery = `:${query}`;
                const { dispatch, state } = editor.view;
                const { tr } = state;
                const { $from } = tr.selection;
                if (!range) {
                  return;
                }
                if (!$from.nodeBefore || $from.nodeBefore?.type.name.toUpperCase() !== "TEXT" || !$from.nodeBefore.text?.endsWith(emojiQuery)) {
                  return;
                }
                if (!dispatch) {
                  return;
                }
                editor.view.dispatch(
                  tr.replaceWith($from.pos - emojiQuery.length, $from.pos, state.schema.text(emoji))
                );
              },
              items: async ({ query }) => {
                if (query.length < 2) {
                  return [];
                }
                const emojiMart = await Promise.resolve().then(() => __toESM(require("emoji-mart")));
                const emojis = await emojiMart.SearchIndex.search(query);
                if (!emojis?.length) {
                  return [];
                }
                return await Promise.all(
                  emojis.slice(0, 15).map((emoji) => emojiMart.getEmojiDataFromNative(emoji.skins[0].native))
                );
              },
              render: () => {
                const modalId = "emojiSuggestions";
                const { modals: modalService } = this.options.services;
                const messages = /* @__PURE__ */ (() => {
                  let subscribers = [];
                  return {
                    dispatch: (msg) => {
                      subscribers.forEach((cb) => cb(msg));
                    },
                    // oxlint-disable-next-line @typescript-oxlint/no-unsafe-function-type
                    subscribe: (cb) => {
                      subscribers.push(cb);
                    },
                    // oxlint-disable-next-line @typescript-oxlint/no-unsafe-function-type
                    unsubscribe: (cb) => {
                      subscribers = subscribers.filter((sub) => sub !== cb);
                    }
                  };
                })();
                let updateProps;
                let closeModal;
                const handleModalState = (props) => {
                  const shouldShowModal = props.items.length > 0 && props.query.length >= 2;
                  const isCurrentlyOpen = modalService.isModalOpen(modalId);
                  if (shouldShowModal && !isCurrentlyOpen) {
                    const { patchProps, close } = modalService.openModal({
                      id: modalId,
                      Component: import_emoji_suggestions_modal.EmojiSuggestionsModal,
                      componentProps: {
                        ...props,
                        messages
                      },
                      layout: "floating",
                      autoFocus: false,
                      positioning: {
                        referenceElement: {
                          getBoundingClientRect: () => (0, import_tiptap.posToDOMRect)(
                            props.editor.view,
                            props.editor.state.selection.from,
                            props.editor.state.selection.to
                          )
                        },
                        placement: "bottom-start"
                      }
                    });
                    updateProps = patchProps;
                    closeModal = close;
                    props.editor.view.focus();
                  } else if (shouldShowModal && isCurrentlyOpen) {
                    updateProps({ ...props, messages });
                  } else if (!shouldShowModal && isCurrentlyOpen) {
                    closeModal();
                  }
                };
                return {
                  onStart: async (props) => {
                    const emojiMart = await Promise.resolve().then(() => __toESM(require("emoji-mart")));
                    const data = await loadEmojiData();
                    await emojiMart.init({ data });
                    handleModalState(props);
                  },
                  onUpdate(props) {
                    handleModalState(props);
                  },
                  onKeyDown: (props) => {
                    if (!modalService.isModalOpen(modalId)) {
                      return false;
                    }
                    if (props.event.key === "Escape") {
                      closeModal();
                      props.view.focus();
                      return true;
                    }
                    if (["ArrowUp", "ArrowDown", "Enter", "Tab"].includes(props.event.key)) {
                      messages.dispatch({ type: "onKeyDown", payload: props });
                      return true;
                    }
                    return false;
                  },
                  onExit() {
                    if (closeModal) {
                      closeModal();
                    }
                  }
                };
              }
            })
          ];
        }
      };
    }
  })
];
//# sourceMappingURL=extension.js.map
