* FEATURE: Add KaTeX in-browser rendering support. * Remove ttf fonts from KaTeX * Update KaTeX to v0.10.1, fix paths to fonts. Font loading was fixed by rebuilding KaTeX and specifiying absolute paths to fonts in CSS: Steps to build KaTeX: 1. `git clone https://github.com/KaTeX/KaTeX.git && cd KaTeX` `git submodule update --init --recursive` 2. Change paths to fonts: `sed -ri 's/@font-folder.+$/@font-folder: "\/plugins\/discourse-math\/katex\/fonts";/' submodules/katex-fonts/fonts.less` 3. Disable TTF fonts: `export USE_TTF=false` Alternatively, we could modify `.browserslistrc` to match what Discourse supports 3. Build KaTeX `yarn && yarn builld` 4. Copy `katex.min.js` and `katex.min.css` from `dist/` to `discourse-math/public/katex/` 5. Update fonts, copy woff and woff2 files from `submodules/katex-fonts/fonts` * Minor copy edit to settings Mark MathKJax only settings * Add Mhchem extension for KaTeX. It is already automatically loaded for MathJaX.
61 lines
1.4 KiB
JavaScript
61 lines
1.4 KiB
JavaScript
import { withPluginApi } from "discourse/lib/plugin-api";
|
|
import loadScript from "discourse/lib/load-script";
|
|
|
|
function ensureKaTeX() {
|
|
return loadScript("/plugins/discourse-math/katex/katex.min.js").then(() => {
|
|
return loadScript("/plugins/discourse-math/katex/katex.min.css", { css: true }).then(() => {
|
|
return loadScript("/plugins/discourse-math/katex/mhchem.min.js")
|
|
})
|
|
})
|
|
}
|
|
|
|
function decorate(elem, isPreview) {
|
|
const $elem = $(elem);
|
|
const displayMode = elem.tagName === 'DIV';
|
|
|
|
if ($elem.data("applied-katex")) {
|
|
return;
|
|
}
|
|
$elem.data("applied-katex", true);
|
|
|
|
if ($elem.hasClass("math")) {
|
|
const text = $elem.text();
|
|
$elem.text('');
|
|
window.katex.render(text, elem, { displayMode });
|
|
}
|
|
}
|
|
|
|
function katex($elem) {
|
|
if (!$elem || !$elem.find) {
|
|
return;
|
|
}
|
|
|
|
const mathElems = $elem.find(".math");
|
|
|
|
if (mathElems.length > 0) {
|
|
const isPreview = $elem.hasClass("d-editor-preview");
|
|
|
|
ensureKaTeX().then(() => {
|
|
mathElems.each((idx, elem) => decorate(elem, isPreview));
|
|
});
|
|
}
|
|
}
|
|
|
|
function initializeMath(api) {
|
|
api.decorateCooked(function(elem) {
|
|
katex(elem);
|
|
});
|
|
}
|
|
|
|
export default {
|
|
name: "apply-math-katex",
|
|
initialize(container) {
|
|
const siteSettings = container.lookup("site-settings:main");
|
|
if (siteSettings.discourse_math_enabled && siteSettings.discourse_math_provider === 'katex') {
|
|
withPluginApi("0.5", function(api) {
|
|
initializeMath(api);
|
|
});
|
|
}
|
|
}
|
|
};
|