Class: Bridgetown::ImagePipeline::Inspector

Inherits:
Object
  • Object
show all
Defined in:
lib/bridgetown/image_pipeline/inspector.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(manifest:, config:) ⇒ Inspector

Returns a new instance of Inspector.



8
9
10
11
# File 'lib/bridgetown/image_pipeline/inspector.rb', line 8

def initialize(manifest:, config:)
  @manifest = manifest
  @config   = config
end

Class Method Details

.find_imgs(doc) ⇒ Object

Nokogiri 1.19 + HTML5 docs translate ‘css(“img”)` to the xpath `//*:img`, which libxml on Linux CI rejects with “Invalid expression”. Use local-name() to bypass the HTML5 namespace handling entirely.



25
26
27
# File 'lib/bridgetown/image_pipeline/inspector.rb', line 25

def self.find_imgs(doc)
  doc.xpath(".//*[local-name()='img']")
end

Instance Method Details

#process_img(img, doc) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/bridgetown/image_pipeline/inspector.rb', line 29

def process_img(img, doc)
  return if img.parent && img.parent.name == "picture"
  return if img.has_attribute?("data-no-pipeline")

  entry = @manifest.find_by_src(img["src"])
  return unless entry

  ensure_dimensions(img, entry)
  ensure_img_srcset(img, entry)

  picture = Nokogiri::XML::Node.new("picture", doc)
  @config.formats.each do |fmt|
    variants = entry[:variants].select { |v| v[:format] == fmt }
    next if variants.empty?

    source = Nokogiri::XML::Node.new("source", doc)
    source["type"]   = "image/#{fmt}"
    source["srcset"] = variants.map { |v| "#{v[:path]} #{v[:width]}w" }.join(", ")
    source["sizes"]  = img["sizes"] if img["sizes"]
    picture.add_child(source)
  end

  img.replace(picture).tap { picture.add_child(img) }
end

#rewrite(html) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/bridgetown/image_pipeline/inspector.rb', line 13

def rewrite(html)
  return html unless @config.auto_rewrite

  doc = Nokogiri::HTML5.parse(html)
  Inspector.find_imgs(doc).each { |img| process_img(img, doc) }
  doc.to_html
end