var _a;
import { schema, defaultMarkdownParser, MarkdownParser } from 'prosemirror-markdown';
import { DOMSerializer, Schema } from 'prosemirror-model';
import { anchorTag } from '../../anchor';
/**
 * Provides markdown parser for rich text components
 */
export class RichTextMarkdownParser {
    /**
     * This function takes a markdown string, parses it using the ProseMirror MarkdownParser, serializes the parsed content into a
     * DOM structure using a DOMSerializer, and returns the serialized result.
     * If the markdown parser returns null, it will clear the viewer component by creating an empty document fragment.
     */
    static parseMarkdownToDOM(value, markdownParserMentionConfig) {
        try {
            _a.setup(markdownParserMentionConfig);
            const parsedMarkdownContent = this.markdownParser.parse(value);
            if (parsedMarkdownContent === null) {
                return {
                    fragment: document.createDocumentFragment(),
                    mentionedHrefs: Array.from(_a.mentionedHrefs)
                };
            }
            return {
                fragment: this.domSerializer.serializeFragment(parsedMarkdownContent.content),
                mentionedHrefs: Array.from(_a.mentionedHrefs)
            };
        }
        finally {
            _a.cleanup();
        }
    }
    static initializeMarkdownParser() {
        /**
         * It configures the tokenizer of the default Markdown parser with the 'zero' preset.
         * The 'zero' preset is a configuration with no rules enabled by default to selectively enable specific rules.
         * https://github.com/markdown-it/markdown-it/blob/2b6cac25823af011ff3bc7628bc9b06e483c5a08/lib/presets/zero.js#L1
         *
         */
        const zeroTokenizerConfiguration = defaultMarkdownParser.tokenizer.configure('zero');
        // The detailed information of the supported rules were provided in the below CommonMark spec document.
        // https://spec.commonmark.org/0.30/
        const supportedTokenizerRules = zeroTokenizerConfiguration.enable([
            'emphasis',
            'list',
            'escape',
            'autolink',
            'newline'
        ]);
        /**
         * In order to display encoded characters, non-ASCII characters, emojis, and other special characters in their original form,
         * we bypass the default normalization of link text in markdown-it. This is done because we support only "AutoLink" feature in CommonMark flavor.
         * "normalizeLinkText" method reference in markdown-it: https://github.com/markdown-it/markdown-it/blob/2b6cac25823af011ff3bc7628bc9b06e483c5a08/lib/index.js#L67C1-L86C2
         *
         * We can use the default normalization once hyperlink support is added.
         * See: https://github.com/ni/nimble/issues/1527
         */
        supportedTokenizerRules.normalizeLinkText = url => url;
        return new MarkdownParser(this.updatedSchema, supportedTokenizerRules, defaultMarkdownParser.tokens);
    }
    static getCustomSchemaConfiguration() {
        return new Schema({
            nodes: schema.spec.nodes,
            marks: {
                link: {
                    attrs: {
                        href: {},
                        rel: { default: 'noopener noreferrer' },
                        // Adding `class` here is a workaround to render two mentions without a whitespace as display names
                        // For more details on this behavior, refer to the issue below:
                        // https://github.com/ni/nimble/issues/1707
                        class: { default: '' }
                    },
                    // Inclusive can be updated when hyperlink support added
                    // See: https://github.com/ni/nimble/issues/1527
                    inclusive: false,
                    // Excludes can be removed/enabled when hyperlink support added
                    // See: https://github.com/ni/nimble/issues/1527
                    excludes: '_',
                    toDOM(node) {
                        const href = node.attrs.href;
                        const currentMention = _a.mentionConfigs?.find(mention => mention.isValidMentionHref(href));
                        const displayName = currentMention?.getDisplayName(href);
                        if (currentMention && displayName) {
                            _a.mentionedHrefs.add(href);
                            return [
                                currentMention.viewElement,
                                {
                                    'mention-href': href,
                                    'mention-label': displayName
                                }
                            ];
                        }
                        return [
                            anchorTag,
                            {
                                /**
                                 * Both mention and absolute link markdown share the autolink format in CommonMark flavor.
                                 * Absolute links with HTTP/HTTPS will be rendered as links. Absolute links that match the
                                 * mention pattern will be rendered as mention view element. Absolute links without HTTP/HTTPS
                                 * scheme and no matching mention pattern will be rendered as plain text (anchor with no href).
                                 * With this, the user can click the links only when the scheme is HTTP/HTTPS
                                 */
                                href: _a.startsWithHttpOrHttps(href)
                                    ? href
                                    : null,
                                rel: node.attrs.rel,
                                // Adding `class` here is a workaround to render two mentions without a whitespace as display names
                                // For more details on this behavior, refer to the issue below:
                                // https://github.com/ni/nimble/issues/1707
                                class: href,
                                'underline-hidden': _a.startsWithHttpOrHttps(href)
                                    ? null
                                    : true
                            }
                        ];
                    }
                },
                em: schema.spec.marks.get('em'),
                strong: schema.spec.marks.get('strong')
            }
        });
    }
    static setup(markdownParserMentionConfig) {
        _a.mentionConfigs = markdownParserMentionConfig;
        _a.mentionedHrefs.clear();
    }
    static cleanup() {
        _a.mentionConfigs = undefined;
        _a.mentionedHrefs.clear();
    }
    static startsWithHttpOrHttps(href) {
        return /^https?:\/\//i.test(href);
    }
}
_a = RichTextMarkdownParser;
RichTextMarkdownParser.mentionedHrefs = new Set();
RichTextMarkdownParser.updatedSchema = _a.getCustomSchemaConfiguration();
RichTextMarkdownParser.markdownParser = _a.initializeMarkdownParser();
RichTextMarkdownParser.domSerializer = DOMSerializer.fromSchema(_a.updatedSchema);
//# sourceMappingURL=markdown-parser.js.map