diff options
Diffstat (limited to 'app/assets/javascripts/syntax_highlight.js.erb')
-rw-r--r-- | app/assets/javascripts/syntax_highlight.js.erb | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/app/assets/javascripts/syntax_highlight.js.erb b/app/assets/javascripts/syntax_highlight.js.erb new file mode 100644 index 00000000000..5664c32d7b6 --- /dev/null +++ b/app/assets/javascripts/syntax_highlight.js.erb @@ -0,0 +1,75 @@ +/* eslint-disable func-names, space-before-function-paren, consistent-return, no-var, no-undef, no-else-return, prefer-arrow-callback, padded-blocks, max-len */ +// Syntax Highlighter +// +// Applies a syntax highlighting color scheme CSS class to any element with the +// `js-syntax-highlight` class +// +// ### Example Markup +// +// <div class="js-syntax-highlight"></div> +// +(function() { + // CSS and JS for KaTeX + CSS_PATH = "<%= asset_path('katex.css') %>"; + JS_PATH = "<%= asset_path('katex.js') %>"; + + // Only load once + var katexLoaded = false; + + // Loop over all math elements and render math + var renderWithKaTeX = function (elements) { + elements.each(function () { + $(this).hide(); + var mathNode = $( "<math>Test</math>" ); + mathNode.insertAfter($(this)); + + katex.render($(this).text(), mathNode.get(0), { displayMode: false }) + }) + }; + var handleMath = function () { + var mathElements = $('.code.math'); + + if (mathElements.length == 0) return; + + if (katexLoaded) renderWithKaTeX(mathElements); + else { + // Request CSS file so it is in the cache + $.get(CSS_PATH, function(){ + var css = $('<link>', + {rel:'stylesheet', + type:'text/css', + href: CSS_PATH + }); + css.appendTo('head'); + + // Load KaTeX js + $.getScript(JS_PATH, function() { + katexLoaded = true; + renderWithKaTeX(mathElements); // Run KaTeX + }) + }); + } + }; + + $.fn.syntaxHighlight = function() { + var $children; + + handleMath(); + + if ($(this).hasClass('js-syntax-highlight')) { + // Given the element itself, apply highlighting + return $(this).addClass(gon.user_color_scheme); + } else { + // Given a parent element, recurse to any of its applicable children + $children = $(this).find('.js-syntax-highlight'); + if ($children.length) { + return $children.syntaxHighlight(); + } + } + }; + + $(document).on('ready page:load', function() { + return $('.js-syntax-highlight').syntaxHighlight(); + }); + +}).call(this); |