summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/image_link_filter.rb
blob: f0fb6084a35e3cea7cd7ae8a24bee854469e1e17 (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
module Banzai
  module Filter
    # HTML filter that wraps links around inline images.
    class ImageLinkFilter < HTML::Pipeline::Filter
      
      # Find every image that isn't already wrapped in an `a` tag, create
      # a new node (a link to the image source), copy the image as a child
      # of the anchor, and then replace the img with the link-wrapped version.
      def call
        doc.xpath('descendant-or-self::img[not(ancestor::a)]').each do |img|
          div = doc.document.create_element(
            'div',
            class: 'image-container'
          )

          link = doc.document.create_element(
            'a',
            class: 'no-attachment-icon',
            href: img['src'],
            target: '_blank'
          )

          link.children = img.clone

          div.children = link

          img.replace(div)
        end

        doc
      end
    end
  end
end