BigW Consortium Gitlab

render_math.js 1.14 KB
Newer Older
1 2
/* global katex */

3 4 5 6 7 8 9 10
// Renders math using KaTeX in any element with the
// `js-render-math` class
//
// ### Example Markup
//
//   <code class="js-render-math"></div>
//
  // Only load once
Phil Hughes committed
11
let katexLoaded = false;
12

Phil Hughes committed
13 14 15 16 17
// Loop over all math elements and render math
function renderWithKaTeX(elements) {
  elements.each(function katexElementsLoop() {
    const mathNode = $('<span></span>');
    const $this = $(this);
18

Phil Hughes committed
19 20 21 22 23 24 25 26 27 28
    const display = $this.attr('data-math-style') === 'display';
    try {
      katex.render($this.text(), mathNode.get(0), { displayMode: display });
      mathNode.insertAfter($this);
      $this.remove();
    } catch (err) {
      throw err;
    }
  });
}
29

Phil Hughes committed
30 31
export default function renderMath($els) {
  if (!$els.length) return;
32

Phil Hughes committed
33 34 35 36 37 38 39 40 41 42
  if (katexLoaded) {
    renderWithKaTeX($els);
  } else {
    $.get(gon.katex_css_url, () => {
      const css = $('<link>', {
        rel: 'stylesheet',
        type: 'text/css',
        href: gon.katex_css_url,
      });
      css.appendTo('head');
43

Phil Hughes committed
44 45 46 47
      // Load KaTeX js
      $.getScript(gon.katex_js_url, () => {
        katexLoaded = true;
        renderWithKaTeX($els); // Run KaTeX
48
      });
Phil Hughes committed
49 50 51
    });
  }
}