Module: JekyllAutoThumbnails::Hooks

Defined in:
lib/jekyll-auto-thumbnails/hooks.rb

Overview

Jekyll hook integration

Class Method Summary collapse

Class Method Details

.copy_thumbnails(site) ⇒ Object

Copy thumbnails from cache to _site

Parameters:

  • site (Jekyll::Site)

    Jekyll site



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/jekyll-auto-thumbnails/hooks.rb', line 101

def self.copy_thumbnails(site)
  config = site.data["auto_thumbnails_config"]
  return unless config&.enabled?

  url_map = site.data["auto_thumbnails_url_map"]
  return unless url_map && !url_map.empty?

  Jekyll.logger.info "AutoThumbnails:", "Copying #{url_map.size} thumbnails to _site"

  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  url_map.each_value do |thumb_url|
    thumb_filename = File.basename(thumb_url)
    cached_path = File.join(config.cache_dir, thumb_filename)

    # Build destination path in _site preserving directory structure
    dest_path = File.join(site.dest, thumb_url)
    dest_dir = File.dirname(dest_path)

    FileUtils.mkdir_p(dest_dir)
    FileUtils.cp(cached_path, dest_path)
  end

  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
  Jekyll.logger.info "AutoThumbnails:", "All thumbnails copied #{format_elapsed(elapsed)}"
end

.format_elapsed(seconds) ⇒ String

Format a duration for Jekyll log suffixes.

Parameters:

  • seconds (Numeric)

    elapsed seconds

Returns:

  • (String)

    in Xs under a minute, otherwise in X m Y s



12
13
14
15
16
17
18
# File 'lib/jekyll-auto-thumbnails/hooks.rb', line 12

def self.format_elapsed(seconds)
  total = seconds.round
  return "in #{total}s" if total < 60

  minutes, remainder = total.divmod(60)
  "in #{minutes} m #{remainder} s"
end

.html_document?(doc) ⇒ Boolean

Check if a document outputs HTML (not CSS, JS, etc.)

Parameters:

  • doc (Jekyll::Document, Jekyll::Page)

    the document to check

Returns:

  • (Boolean)

    true if the document outputs HTML



163
164
165
166
# File 'lib/jekyll-auto-thumbnails/hooks.rb', line 163

def self.html_document?(doc)
  ext = File.extname(doc.path || doc.url || "").downcase
  [".html", ".htm", ".md", ".markdown"].include?(ext)
end

.initialize_system(site) ⇒ Object

Initialize optimization system

Parameters:

  • site (Jekyll::Site)

    Jekyll site



23
24
25
26
27
28
29
30
31
32
# File 'lib/jekyll-auto-thumbnails/hooks.rb', line 23

def self.initialize_system(site)
  config = Configuration.new(site)
  return unless config.enabled?

  site.data["auto_thumbnails_config"] = config
  site.data["auto_thumbnails_registry"] = Registry.new
  site.data["auto_thumbnails_generator"] = Generator.new(config, site.source)

  Jekyll.logger.info "AutoThumbnails:", "System initialized"
end

.process_site(site) ⇒ Object

Process site - scan, generate, replace

Parameters:

  • site (Jekyll::Site)

    Jekyll site



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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/jekyll-auto-thumbnails/hooks.rb', line 37

def self.process_site(site)
  config = site.data["auto_thumbnails_config"]
  return unless config&.enabled?

  registry = site.data["auto_thumbnails_registry"]
  generator = site.data["auto_thumbnails_generator"]

  # Check ImageMagick
  unless generator.imagemagick_available?
    Jekyll.logger.warn "AutoThumbnails:", "ImageMagick not found - skipping"
    return
  end

  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  # Scan all documents and pages
  (site.documents + site.pages).each do |doc|
    next unless doc.output
    next unless html_document?(doc)

    Scanner.scan_html(doc.output, registry, config, site.source)
  end

  Jekyll.logger.info "AutoThumbnails:", "Found #{registry.entries.size} images to optimize"

  # Generate thumbnails
  url_map = {}
  registry.entries.each do |url, requirements|
    cached_path = generator.generate(url, requirements[:width], requirements[:height])

    if cached_path
      # Build thumbnail URL (use forward slashes for URLs, not File.join)
      thumb_filename = File.basename(cached_path)
      url_dir = File.dirname(url)
      # Ensure URL uses forward slashes (cross-platform URLs)
      thumb_url = if url_dir == "."
                    "/#{thumb_filename}"
                  else
                    "#{url_dir}/#{thumb_filename}"
                  end
      url_map[url] = thumb_url
    else
      Jekyll.logger.warn "AutoThumbnails:", "Failed to generate thumbnail for #{url}"
    end
  end

  # Store url_map for post_write hook
  site.data["auto_thumbnails_url_map"] = url_map

  # Replace URLs in HTML
  (site.documents + site.pages).each do |doc|
    next unless doc.output
    next unless html_document?(doc)

    doc.output = replace_urls(doc.output, url_map, parser: config.parser)
  end

  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
  Jekyll.logger.info "AutoThumbnails:", "Generated #{url_map.size} thumbnails #{format_elapsed(elapsed)}"
end

.replace_urls(html, url_map, parser: :html5) ⇒ String

Replace image URLs in HTML.

Returns the input string unchanged (object identity) when no replacement was actually made. This is both a perf win for pages with no matching images and a correctness win: the HTML4 path otherwise round-trips every page through libxml2's serializer, which injects a spurious <meta http-equiv="Content-Type"> on HTML5 sites.

Parameters:

  • html (String)

    HTML content

  • url_map (Hash)

    original URL => thumbnail URL

  • parser (Symbol) (defaults to: :html5)

    :html5 (default) or :html4

Returns:

  • (String)

    modified HTML (or the input itself, unchanged)



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/jekyll-auto-thumbnails/hooks.rb', line 140

def self.replace_urls(html, url_map, parser: :html5)
  return html if url_map.empty?
  return html unless html.match?(/<img/i)

  doc = HtmlParser.parse(html, parser)

  modified = false
  doc.css("article img").each do |img|
    src = img["src"]
    thumb_url = url_map[src]
    next unless thumb_url

    img["src"] = thumb_url
    modified = true
  end

  modified ? doc.to_html : html
end