summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/math_filter.rb
blob: cb037f89337c860515dfa358c44317772078676e (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
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