// Render math markup in Markdown documents.
//
// When a Markdown document contains $...$ or $$...$$ math syntax,
// Prince automatically loads this script as a user script (so it runs
// even when author scripts are disabled). It finds all elements with
// a data-math-style attribute and uses KaTeX to render the LaTeX
// source into formatted math.

document.addEventListener("DOMContentLoaded", function() {
    if (typeof katex === "undefined") {
        console.log("math.js: katex is not loaded");
        return;
    }

    var elems = document.querySelectorAll("[data-math-style]");
    for (var i = 0; i < elems.length; i++) {
        var elem = elems[i];
        var displayMode = elem.getAttribute("data-math-style") === "display";
        var latex = elem.textContent;
        try {
            var html = katex.renderToString(latex, {
                displayMode: displayMode,
                throwOnError: false
            });

            // A ```math code block produces <pre><code data-math-style>.
            // Replace the <pre> with a <div> so KaTeX styles apply cleanly.
            var pre = elem.parentNode;
            if (elem.nodeName === "CODE" && pre && pre.nodeName === "PRE") {
                var div = document.createElement("div");
                div.innerHTML = html;
                pre.parentNode.replaceChild(div, pre);
            } else {
                elem.innerHTML = html;
            }
        } catch (e) {
            console.log("math.js: " + e.message);
        }
    }
});
