Files
discourse-math/assets/javascripts/initializers/discourse-math-katex.js
T

86 lines
2.4 KiB
JavaScript
Raw Normal View History

2024-01-16 17:57:10 +01:00
import $ from "jquery";
2019-03-04 21:35:00 +01:00
import loadScript from "discourse/lib/load-script";
2024-01-16 17:57:10 +01:00
import { withPluginApi } from "discourse/lib/plugin-api";
2019-03-04 21:35:00 +01:00
function ensureKaTeX() {
return loadScript("/plugins/discourse-math/katex/katex.min.js").then(() => {
2019-06-14 13:28:18 -04:00
return loadScript("/plugins/discourse-math/katex/katex.min.css", {
2020-09-04 13:22:43 +02:00
css: true,
})
.then(() => {
return loadScript("/plugins/discourse-math/katex/mhchem.min.js");
})
.then(() => {
return loadScript("/plugins/discourse-math/katex/copy-tex.min.js");
});
2019-06-14 12:47:22 -04:00
});
2019-03-04 21:35:00 +01:00
}
function decorate(elem, katexOpts) {
2019-03-04 21:35:00 +01:00
const $elem = $(elem);
katexOpts["displayMode"] = elem.tagName === "DIV";
2019-03-04 21:35:00 +01:00
if ($elem.data("applied-katex")) {
return;
}
$elem.data("applied-katex", true);
if ($elem.hasClass("math")) {
2019-09-10 12:56:59 +08:00
const tag = elem.tagName === "DIV" ? "div" : "span";
const displayClass = tag === "div" ? "block-math" : "inline-math";
2019-03-04 21:35:00 +01:00
const text = $elem.text();
2019-09-10 12:56:59 +08:00
$elem.addClass(`math-container ${displayClass} katex-math`).text("");
window.katex.render(text, elem, katexOpts);
2019-03-04 21:35:00 +01:00
}
}
function katex($elem) {
if (!$elem || !$elem.find) {
return;
}
const mathElems = $elem.find(".math");
if (mathElems.length > 0) {
ensureKaTeX().then(() => {
// enable persistent macros with are disabled by default: https://katex.org/docs/api.html#persistent-macros
// also enable equation labelling and referencing which are disabled by default
// 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));
2019-03-04 21:35:00 +01:00
});
}
}
function initializeMath(api) {
api.decorateCooked(
2020-09-04 13:22:43 +02:00
function (elem) {
katex(elem);
},
{ id: "katex" }
);
2019-03-04 21:35:00 +01:00
}
export default {
name: "apply-math-katex",
initialize(container) {
2024-01-16 17:57:10 +01:00
const siteSettings = container.lookup("service:site-settings");
2019-06-14 13:28:18 -04:00
if (
siteSettings.discourse_math_enabled &&
siteSettings.discourse_math_provider === "katex"
) {
2020-09-04 13:22:43 +02:00
withPluginApi("0.5", function (api) {
2019-03-04 21:35:00 +01:00
initializeMath(api);
});
}
2020-09-04 13:22:43 +02:00
},
2019-03-04 21:35:00 +01:00
};