"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.codeBlockLangsPluginKey = void 0;
exports.getCodeBlockLangsState = getCodeBlockLangsState;
exports.codeBlockLangsPlugin = codeBlockLangsPlugin;
const state_1 = require("../../../../../pm/state.js");
const lodash_1 = require("../../../../../lodash.js");
const logger_1 = require("../../../../../logger.js");
const const_1 = require("../const.js");
exports.codeBlockLangsPluginKey = new state_1.PluginKey('code_block_langs');
const defaultState = {
    langItems: [],
    aliasMapping: {},
    lowlight: null,
    loaded: false,
};
function getCodeBlockLangsState(state) {
    return exports.codeBlockLangsPluginKey.getState(state) ?? defaultState;
}
function codeBlockLangsPlugin(langsConfig, logger) {
    return new state_1.Plugin({
        key: exports.codeBlockLangsPluginKey,
        state: {
            init: (_config, _state) => {
                return defaultState;
            },
            apply: (tr, state) => {
                const meta = tr.getMeta(exports.codeBlockLangsPluginKey);
                if (meta)
                    return meta;
                return state;
            },
        },
        view: (view) => {
            loadAndInit(view, langsConfig, logger);
            return {};
        },
    });
}
async function loadAndInit(view, langsConfig, logger) {
    try {
        const [{ default: hljs }, low] = await Promise.all([
            import('highlight.js/lib/core'),
            import('lowlight'),
        ]);
        const all = low.all;
        const create = low.createLowlight;
        const langs = { ...all, ...langsConfig };
        const lowlight = create(langs);
        const langItems = [];
        const aliasMapping = {};
        for (const lang of Object.keys(langs)) {
            const defs = langs[lang](hljs);
            langItems.push({
                value: lang,
                content: defs.name || (0, lodash_1.capitalize)(lang),
            });
            if (defs.aliases) {
                for (const alias of defs.aliases) {
                    aliasMapping[alias] = lang;
                }
            }
        }
        langItems.sort(sortLangs);
        if (!view.isDestroyed) {
            const newState = {
                langItems,
                aliasMapping,
                lowlight,
                loaded: true,
            };
            view.dispatch(view.state.tr.setMeta(exports.codeBlockLangsPluginKey, newState));
        }
    }
    catch (e) {
        logger_1.globalLogger.info('Skip code_block highlighting');
        logger.log('Skip code_block highlighting');
    }
}
function sortLangs(a, b) {
    // plaintext always goes first
    if (a.value === const_1.PlainTextLang)
        return -1;
    if (b.value === const_1.PlainTextLang)
        return 1;
    return 0;
}
//# sourceMappingURL=codeBlockLangsPlugin.js.map
