summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/render_math.js
blob: 73b6aafdd12e1addbbc1ad938ff595f3fe84cabc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* global katex */

// Renders math using KaTeX in any element with the
// `js-render-math` class
//
// ### Example Markup
//
//   <code class="js-render-math"></div>
//

import { __ } from './locale';
import axios from './lib/utils/axios_utils';
import flash from './flash';

// Only load once
let katexLoaded = false;

// Loop over all math elements and render math
function renderWithKaTeX(elements) {
  elements.each(function katexElementsLoop() {
    const mathNode = $('<span></span>');
    const $this = $(this);

    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;
    }
  });
}

export default function renderMath($els) {
  if (!$els.length) return;

  if (katexLoaded) {
    renderWithKaTeX($els);
  } else {
    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(() => {
        katexLoaded = true;
        renderWithKaTeX($els); // Run KaTeX
      })
      .catch(() => flash(__('An error occurred while rendering KaTeX')));
  }
}