_plugins/responsive_images.rb (2608B) - raw
1 require 'cgi'
2 require 'open3'
3
4 def run_command *args
5 out, err, status = Open3.capture3 *args
6 raise "#{args.first} failed: #{err}" unless status.success?
7 out
8 end
9
10 class ResizedImage < Jekyll::StaticFile
11 def initialize site, dir, name, source, width
12 super site, site.source, dir, name
13 @source = source
14 @width = width
15 end
16
17 def path
18 @source
19 end
20
21 def write dest
22 dest_path = destination dest
23 Jekyll.logger.info "Resizing:", dest_path
24 FileUtils.mkdir_p File.dirname(dest_path)
25 run_command "magick", @source, "-resize", "#{@width}x", dest_path
26 run_command "pngquant", "--nofs", "--strip", "--force", "--output", dest_path, "32", dest_path
27 run_command "oxipng", "--quiet", "--opt", "2", "--strip", "all", dest_path
28 true
29 end
30 end
31
32 $responsive_images = {}
33 Jekyll::Hooks.register :site, :after_reset do |site|
34 $responsive_images = {}
35 end
36
37 class ResponsiveImageTag < Liquid::Tag
38 def initialize tag_name, markup, tokens
39 super
40 @src = markup.split.first
41 @attributes = {}
42 markup.scan(Liquid::TagAttributes) do |key, value|
43 @attributes[key] = Liquid::Expression.parse value
44 end
45 end
46
47 def render context
48 site = context.registers[:site]
49 page = context.registers[:page]
50 site_path = @src.start_with?("/") ? @src : File.join(page["dir"], @src)
51 image = $responsive_images[site_path] ||= add_image site, site_path
52
53 ext = File.extname @src
54 base = @src.delete_suffix ext
55 srcset = image[:widths].map { |w| "#{base}-#{w}w#{ext} #{w}w" }
56 srcset << "#{@src} #{image[:width]}w"
57 attrs = %(src="#{@src}" width="#{image[:width]}" height="#{image[:height]}" srcset="#{srcset.join(", ")}")
58 alt = context.evaluate @attributes["alt"]
59 attrs << %( alt="#{CGI.escapeHTML alt.to_s}") unless alt.nil?
60 attrs << (context.evaluate(@attributes["lazy"]) ? %( loading="lazy" sizes="auto, 100vw") : %( sizes="100vw"))
61 "<img #{attrs}>"
62 end
63
64 private
65
66 def add_image site, site_path
67 source = File.join site.source, site_path
68 raise "responsive_img: #{source} not found" unless File.exist? source
69 width, height = run_command("magick", "identify", "-format", "%w %h", source).split.map(&:to_i)
70 dir = File.dirname site_path
71 ext = File.extname site_path
72 basename = File.basename site_path, ext
73 widths = [2, 4].map { |d| width / d }
74 widths.each do |w|
75 site.static_files << ResizedImage.new(site, dir, "#{basename}-#{w}w#{ext}", source, w)
76 end
77 { width: width, height: height, widths: widths }
78 end
79 end
80
81 Liquid::Template.register_tag("responsive_img", ResponsiveImageTag)