2018-05-09 12:01:36 +05:30
|
|
|
import $ from 'jquery';
|
|
|
|
import { __ } from '~/locale';
|
|
|
|
import flash from '~/flash';
|
2017-08-17 22:00:37 +05:30
|
|
|
|
|
|
|
// Renders math using KaTeX in any element with the
|
|
|
|
// `js-render-math` class
|
|
|
|
//
|
|
|
|
// ### Example Markup
|
|
|
|
//
|
|
|
|
// <code class="js-render-math"></div>
|
|
|
|
//
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
// Loop over all math elements and render math
|
|
|
|
function renderWithKaTeX(elements, katex) {
|
|
|
|
elements.each(function katexElementsLoop() {
|
|
|
|
const mathNode = $('<span></span>');
|
|
|
|
const $this = $(this);
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
const display = $this.attr('data-math-style') === 'display';
|
|
|
|
try {
|
|
|
|
katex.render($this.text(), mathNode.get(0), { displayMode: display, throwOnError: false });
|
|
|
|
mathNode.insertAfter($this);
|
|
|
|
$this.remove();
|
|
|
|
} catch (err) {
|
|
|
|
throw err;
|
2017-08-17 22:00:37 +05:30
|
|
|
}
|
2018-03-17 18:26:18 +05:30
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function renderMath($els) {
|
|
|
|
if (!$els.length) return;
|
|
|
|
Promise.all([
|
|
|
|
import(/* webpackChunkName: 'katex' */ 'katex'),
|
2018-05-09 12:01:36 +05:30
|
|
|
import(/* webpackChunkName: 'katex' */ 'katex/dist/katex.min.css'),
|
2018-12-13 13:39:08 +05:30
|
|
|
])
|
|
|
|
.then(([katex]) => {
|
|
|
|
renderWithKaTeX($els, katex);
|
|
|
|
})
|
|
|
|
.catch(() => flash(__('An error occurred while rendering KaTeX')));
|
2018-03-17 18:26:18 +05:30
|
|
|
}
|