import {reactive, watch} from 'vue'
import {createGlobalState} from "@vueuse/core";
import config from "@/config";

export const useMathJaxService = createGlobalState(() => {
    const MathJax = {
        tex: {
            inlineMath: [["$", "$"], ["\\(", "\\)"]], //行内公式选择符
            displayMath: [["$$", "$$"], ["\\[", "\\]"]], //段内公式选择符
            // autoload: {color: [], colorv2: ['color']}, // 3.0开始已经不支持此选项了
            packages: {'[+]': ['noerrors', 'mathtools', 'ams']}
        },
        options: {
            skipHtmlTags: ["script", "noscript", "style", "textarea", "pre", "code", "a"], //避开某些标签
            ignoreHtmlClass: 'tex2jax_ignore',
            processHtmlClass: 'tex2jax_process'
        },
        loader: {
            load: ['input/asciimath', '[tex]/noerrors', '[tex]/mathtools', '[tex]/ams']
        }
    }
    // NOTE：mathjax库在加载完毕后会用新对象直接覆盖window.MathJax, 所以后续都需要使用window.MathJax
    window.MathJax = MathJax
    const updateMathJax = function (el) {
        // 指定了HTML元素即更新指定元素，否则全部更新
        const elements = []
        if (el instanceof HTMLElement) elements.push(el)
        const mathjax = window.MathJax
        if (!mathjax.version) return
        mathjax.startup.promise.then(_ => mathjax.typesetPromise(elements))
    }

    const script = document.createElement('script')
    script.src = config.mathJaxCDN
    script.onload = () => updateMathJax()
    document.head.appendChild(script)

    return {
        MathJax,
        updateMathJax
    }
})