diff options
author | Kamil Trzcinski <ayufan@ayufan.eu> | 2016-12-18 23:39:51 +0100 |
---|---|---|
committer | Kamil Trzcinski <ayufan@ayufan.eu> | 2016-12-18 23:39:51 +0100 |
commit | 14d47884dff6844625c2e65b247fd773d78f5ea2 (patch) | |
tree | 10fba027e61521df236fd6eec7ba829c5fe2c8ec /lib/banzai/filter/math_filter.rb | |
parent | 9fd775def2d89500cf291fe675458b68ead7cd2c (diff) | |
parent | 546fa165ff728bc2d25ed9b55b95dd1d48139d4a (diff) | |
download | gitlab-ce-14d47884dff6844625c2e65b247fd773d78f5ea2.tar.gz |
Merge remote-tracking branch 'origin/master' into dockerfile-templatesdockerfile-templates
Diffstat (limited to 'lib/banzai/filter/math_filter.rb')
-rw-r--r-- | lib/banzai/filter/math_filter.rb | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/lib/banzai/filter/math_filter.rb b/lib/banzai/filter/math_filter.rb new file mode 100644 index 00000000000..cb037f89337 --- /dev/null +++ b/lib/banzai/filter/math_filter.rb @@ -0,0 +1,51 @@ +require 'uri' + +module Banzai + module Filter + # HTML filter that adds class="code math" and removes the dollar sign in $`2+2`$. + # + class MathFilter < HTML::Pipeline::Filter + # This picks out <code>...</code>. + INLINE_MATH = 'descendant-or-self::code'.freeze + + # Pick out a code block which is declared math + DISPLAY_MATH = "descendant-or-self::pre[contains(@class, 'math') and contains(@class, 'code')]".freeze + + # Attribute indicating inline or display math. + STYLE_ATTRIBUTE = 'data-math-style'.freeze + + # Class used for tagging elements that should be rendered + TAG_CLASS = 'js-render-math'.freeze + + INLINE_CLASSES = "code math #{TAG_CLASS}".freeze + + DOLLAR_SIGN = '$'.freeze + + def call + doc.xpath(INLINE_MATH).each do |code| + closing = code.next + opening = code.previous + + # We need a sibling before and after. + # They should end and start with $ respectively. + if closing && opening && + closing.content.first == DOLLAR_SIGN && + opening.content.last == DOLLAR_SIGN + + code[:class] = INLINE_CLASSES + code[STYLE_ATTRIBUTE] = 'inline' + closing.content = closing.content[1..-1] + opening.content = opening.content[0..-2] + end + end + + doc.xpath(DISPLAY_MATH).each do |el| + el[STYLE_ATTRIBUTE] = 'display' + el[:class] += " #{TAG_CLASS}" + end + + doc + end + end + end +end |