import { PluginKey } from "prosemirror-state";
import { posToDOMRect } from "./../tiptap/index.js";
import { Suggestion } from "./../tiptap/suggestion/index.js";
import { createRicosFunctionalExtension } from "./../tiptap-extensions/index.js";
import { EmojiSuggestionsModal } from "./modals/emoji-suggestions-modal.js";
const loadEmojiData = async () => {
  const { default: data } = await import("@emoji-mart/data");
  return data;
};
const getTipTapExtensions = () => [
  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 [
            Suggestion({
              editor: this.editor,
              pluginKey: new 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 import("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: EmojiSuggestionsModal,
                      componentProps: {
                        ...props,
                        messages
                      },
                      layout: "floating",
                      autoFocus: false,
                      positioning: {
                        referenceElement: {
                          getBoundingClientRect: () => 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 import("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();
                    }
                  }
                };
              }
            })
          ];
        }
      };
    }
  })
];
export {
  getTipTapExtensions,
  loadEmojiData
};
//# sourceMappingURL=extension.js.map
