debian-mirror-gitlab/app/assets/javascripts/render_math.js

38 lines
1 KiB
JavaScript
Raw Normal View History

2018-03-17 18:26:18 +05:30
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'),
import(/* webpackChunkName: 'katex' */ 'katex/dist/katex.css'),
]).then(([katex]) => {
renderWithKaTeX($els, katex);
}).catch(() => flash(__('An error occurred while rendering KaTeX')));
}