2017-03-17 13:21:25 -04:00
|
|
|
/* global katex */
|
|
|
|
|
2016-12-08 19:15:08 -05:00
|
|
|
// Renders math using KaTeX in any element with the
|
|
|
|
// `js-render-math` class
|
|
|
|
//
|
|
|
|
// ### Example Markup
|
|
|
|
//
|
|
|
|
// <code class="js-render-math"></div>
|
|
|
|
//
|
2018-01-30 15:54:23 -05:00
|
|
|
|
|
|
|
import { __ } from './locale';
|
|
|
|
import axios from './lib/utils/axios_utils';
|
|
|
|
import flash from './flash';
|
|
|
|
|
|
|
|
// Only load once
|
2017-11-22 13:40:11 -05:00
|
|
|
let katexLoaded = false;
|
2016-12-08 19:15:08 -05:00
|
|
|
|
2017-11-22 13:40:11 -05:00
|
|
|
// Loop over all math elements and render math
|
|
|
|
function renderWithKaTeX(elements) {
|
|
|
|
elements.each(function katexElementsLoop() {
|
|
|
|
const mathNode = $('<span></span>');
|
|
|
|
const $this = $(this);
|
2016-12-08 19:15:08 -05:00
|
|
|
|
2017-11-22 13:40:11 -05:00
|
|
|
const display = $this.attr('data-math-style') === 'display';
|
|
|
|
try {
|
2018-01-24 13:02:40 -05:00
|
|
|
katex.render($this.text(), mathNode.get(0), { displayMode: display, throwOnError: false });
|
2017-11-22 13:40:11 -05:00
|
|
|
mathNode.insertAfter($this);
|
|
|
|
$this.remove();
|
|
|
|
} catch (err) {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2016-12-08 19:15:08 -05:00
|
|
|
|
2017-11-22 13:40:11 -05:00
|
|
|
export default function renderMath($els) {
|
|
|
|
if (!$els.length) return;
|
2016-12-08 19:15:08 -05:00
|
|
|
|
2017-11-22 13:40:11 -05:00
|
|
|
if (katexLoaded) {
|
|
|
|
renderWithKaTeX($els);
|
|
|
|
} else {
|
2018-01-30 15:54:23 -05:00
|
|
|
axios.get(gon.katex_css_url)
|
|
|
|
.then(() => {
|
|
|
|
const css = $('<link>', {
|
|
|
|
rel: 'stylesheet',
|
|
|
|
type: 'text/css',
|
|
|
|
href: gon.katex_css_url,
|
|
|
|
});
|
|
|
|
css.appendTo('head');
|
|
|
|
})
|
|
|
|
.then(() => axios.get(gon.katex_js_url, {
|
|
|
|
responseType: 'text',
|
|
|
|
}))
|
|
|
|
.then(({ data }) => {
|
|
|
|
// Add katex js to our document
|
|
|
|
$.globalEval(data);
|
|
|
|
})
|
|
|
|
.then(() => {
|
2017-11-22 13:40:11 -05:00
|
|
|
katexLoaded = true;
|
|
|
|
renderWithKaTeX($els); // Run KaTeX
|
2018-01-30 15:54:23 -05:00
|
|
|
})
|
|
|
|
.catch(() => flash(__('An error occurred while rendering KaTeX')));
|
2017-11-22 13:40:11 -05:00
|
|
|
}
|
|
|
|
}
|