Class: Banzai::Filter::FootnoteFilter

Inherits:
HTML::Pipeline::Filter
  • Object
show all
Defined in:
lib/banzai/filter/footnote_filter.rb

Overview

This filter adds a random number to each footnote (the same number can be used for a single render). So you get `id=fn-1-4335` and `id=fn-foot-4335`.

Constant Summary collapse

FOOTNOTE_ID_PREFIX =
'fn-'
'fnref-'
FOOTNOTE_LI_REFERENCE_PATTERN =
/\A#{FOOTNOTE_ID_PREFIX}.+\z/.freeze
/\A#{FOOTNOTE_LINK_ID_PREFIX}.+\z/.freeze
CSS_SECTION =
"section[data-footnotes]"
XPATH_SECTION =
Gitlab::Utils::Nokogiri.css_to_xpath(CSS_SECTION).freeze
CSS_FOOTNOTE =
'sup > a[data-footnote-ref]'
XPATH_FOOTNOTE =
Gitlab::Utils::Nokogiri.css_to_xpath(CSS_FOOTNOTE).freeze

Instance Method Summary collapse

Instance Method Details

#callObject


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
64
65
66
67
68
69
# File 'lib/banzai/filter/footnote_filter.rb', line 30

def call
  # Sanitization stripped off the section class - add it back in
  return doc unless section_node = doc.at_xpath(XPATH_SECTION)

  section_node.append_class('footnotes')

  rand_suffix = "-#{random_number}"
  modified_footnotes = {}

  doc.xpath(XPATH_FOOTNOTE).each do |link_node|
    ref_num = link_node[:id].delete_prefix(FOOTNOTE_LINK_ID_PREFIX)
    ref_num.gsub!(/[[:punct:]]/, '\\\\\&')

    css = "section[data-footnotes] li[id=#{fn_id(ref_num)}]"
    node_xpath = Gitlab::Utils::Nokogiri.css_to_xpath(css)
    footnote_node = doc.at_xpath(node_xpath)

    if footnote_node || modified_footnotes[ref_num]
      link_node[:href] += rand_suffix
      link_node[:id]   += rand_suffix

      # Sanitization stripped off class - add it back in
      link_node.parent.append_class('footnote-ref')

      unless modified_footnotes[ref_num]
        footnote_node[:id] += rand_suffix
        backref_node        = footnote_node.at_css("a[href=\"##{fnref_id(ref_num)}\"]")

        if backref_node
          backref_node[:href] += rand_suffix
          backref_node.append_class('footnote-backref')
        end

        modified_footnotes[ref_num] = true
      end
    end
  end

  doc
end