FEATURE: support equation labelling and referencing in KaTeX (more mathjax compatibility) (#53)

This commit is contained in:
qnxor 2022-06-15 15:25:24 +01:00 committed by GitHub
parent 4b4ad9d532
commit dbd7c1c84b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 16 additions and 6 deletions

View File

@ -11,9 +11,9 @@ function ensureKaTeX() {
}); });
} }
function decorate(elem, macros) { function decorate(elem, katexOpts) {
const $elem = $(elem); const $elem = $(elem);
const displayMode = elem.tagName === "DIV"; katexOpts["displayMode"] = elem.tagName === "DIV";
if ($elem.data("applied-katex")) { if ($elem.data("applied-katex")) {
return; return;
@ -25,7 +25,7 @@ function decorate(elem, macros) {
const displayClass = tag === "div" ? "block-math" : "inline-math"; const displayClass = tag === "div" ? "block-math" : "inline-math";
const text = $elem.text(); const text = $elem.text();
$elem.addClass(`math-container ${displayClass} katex-math`).text(""); $elem.addClass(`math-container ${displayClass} katex-math`).text("");
window.katex.render(text, elem, { displayMode, macros }); window.katex.render(text, elem, katexOpts);
} }
} }
@ -38,9 +38,19 @@ function katex($elem) {
if (mathElems.length > 0) { if (mathElems.length > 0) {
ensureKaTeX().then(() => { ensureKaTeX().then(() => {
// enable persistent macros: https://katex.org/docs/api.html#persistent-macros // enable persistent macros with are disabled by default: https://katex.org/docs/api.html#persistent-macros
const macros = {}; // also enable equation labelling and referencing which are disabled by default
mathElems.each((idx, elem) => decorate(elem, macros)); // both of these are enabled in mathjax by default, so now the katex implementation is (more) mathjax compatible
const katexOpts = {
trust: (context) => ["\\htmlId", "\\href"].includes(context.command),
macros: {
"\\eqref": "\\href{###1}{(\\text{#1})}",
"\\ref": "\\href{###1}{\\text{#1}}",
"\\label": "\\htmlId{#1}{}",
},
displayMode: false,
};
mathElems.each((idx, elem) => decorate(elem, katexOpts));
}); });
} }
} }