summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/inline_diff_filter.rb
blob: 9e75edd4d4c46e48cb90e8176fc19a377f6ffdf6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module Banzai
  module Filter
    class InlineDiffFilter < HTML::Pipeline::Filter
      IGNORED_ANCESTOR_TAGS = %w(pre code tt).to_set

      def call
        search_text_nodes(doc).each do |node|
          next if has_ancestor?(node, IGNORED_ANCESTOR_TAGS)

          content = node.to_html
          content = content.gsub(/(?:\[\-(.*?)\-\]|\{\-(.*?)\-\})/, '<span class="idiff left right deletion">\1\2</span>')
          content = content.gsub(/(?:\[\+(.*?)\+\]|\{\+(.*?)\+\})/, '<span class="idiff left right addition">\1\2</span>')

          next if html == content

          node.replace(content)
        end
        doc
      end
    end
  end
end