"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmojiInput = void 0;
const prosemirror_inputrules_1 = require("prosemirror-inputrules");
const ecapeRegexp_1 = require("../../../../utils/ecapeRegexp.js");
const inputrules_1 = require("../../../../utils/inputrules.js");
const EmojiSpecs_1 = require("../EmojiSpecs/index.js");
const EmojiInput = (builder, opts) => {
    const { defs, shortcuts } = opts;
    if (defs && shortcuts) {
        const allPatternsForRegexp = [];
        const mapPatternToMarkup = {};
        for (const [markup, patterns] of Object.entries(shortcuts)) {
            if (!patterns)
                continue;
            const markupPatterns = [].concat(patterns);
            for (const pattern of markupPatterns) {
                allPatternsForRegexp.push((0, ecapeRegexp_1.escapeRegExp)(pattern));
                mapPatternToMarkup[pattern] = markup;
            }
        }
        if (allPatternsForRegexp.length) {
            const regex = new RegExp(`(?:^|\\s)(${allPatternsForRegexp.join('|')})\\s$`, 'g');
            builder.addInputRules(() => ({
                rules: [
                    new prosemirror_inputrules_1.InputRule(regex, (state, match, start, end) => {
                        if ((0, inputrules_1.hasCodeMark)(state, match, start, end))
                            return null;
                        const pattern = match[1];
                        const markup = mapPatternToMarkup[pattern];
                        const content = defs[markup];
                        if (content) {
                            const { tr, schema } = state;
                            const whitespaceAtStart = /^\s/.test(match[0]);
                            const from = start + (whitespaceAtStart ? 1 : 0);
                            const to = end;
                            return tr.replaceWith(from, to, [
                                EmojiSpecs_1.EmojiConsts.nodeType(schema).create({ [EmojiSpecs_1.EmojiConsts.NodeAttrs.Markup]: markup }, schema.text(content)),
                                schema.text(' '),
                            ]);
                        }
                        return null;
                    }),
                ],
            }));
        }
    }
};
exports.EmojiInput = EmojiInput;
//# sourceMappingURL=EmojiInput.js.map
