summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/render_math.js
blob: 8b3fee49cb9fffbcb39b4c74a5af0194d49287bd (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
/* eslint-disable func-names, space-before-function-paren, consistent-return, no-var, no-else-return, prefer-arrow-callback, max-len, no-console */
/* global katex */

// Renders math using KaTeX in any element with the
// `js-render-math` class
//
// ### Example Markup
//
//   <code class="js-render-math"></div>
//
(function() {
  // Only load once
  var katexLoaded = false;

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

      var display = $this.attr('data-math-style') === 'display';
      try {
        katex.render($this.text(), mathNode.get(0), { displayMode: display });
        mathNode.insertAfter($this);
        $this.remove();
      } catch (err) {
        // What can we do??
        console.log(err.message);
      }
    });
  };

  $.fn.renderMath = function() {
    var $this = this;
    if ($this.length === 0) return;

    if (katexLoaded) renderWithKaTeX($this);
    else {
      // Request CSS file so it is in the cache
      $.get(gon.katex_css_url, function() {
        var css = $('<link>',
          { rel: 'stylesheet',
            type: 'text/css',
            href: gon.katex_css_url,
          });
        css.appendTo('head');

        // Load KaTeX js
        $.getScript(gon.katex_js_url, function() {
          katexLoaded = true;
          renderWithKaTeX($this); // Run KaTeX
        });
      });
    }
  };
}).call(window);