Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
galaxyproject
GitHub Repository: galaxyproject/training-material
Path: blob/main/_plugins/gtn/images.rb
1677 views
1
# frozen_string_literal: true
2
3
require 'jekyll'
4
# The fastimage gem may not be installed, and that is OK, we will fall back to another method
5
FASTIMAGE_AVAILABLE = true
6
begin
7
require 'fastimage'
8
rescue LoadError
9
Jekyll.logger.info '[GTN/Images] Could not load fastimage gem, disabling feature (probably due to conda)'
10
FASTIMAGE_AVAILABLE = false
11
end
12
13
module Gtn
14
# Module to handle pre-calculating image dimensions
15
# We can then use those dimensions in the HTML to avoid reflow
16
module Images
17
def self.cache
18
@@cache ||= Jekyll::Cache.new('ImageDimensions')
19
end
20
21
def self.html_image_dimensions(tuto_dir, url)
22
return '' if !FASTIMAGE_AVAILABLE || (Jekyll.env == 'development')
23
24
(width, height), path = get_image_dimensions(tuto_dir, url)
25
return unless width && height
26
27
[
28
%(width="#{width}" height=#{height}),
29
path
30
]
31
end
32
33
def self.get_image_dimensions(tuto_dir, url)
34
if (match = url.match(%r{^{{\s*site.baseurl\s*}}/(.*)})) || (match = url.match(/{%\s*link\s*(.*)\s*%}/))
35
_get_image_dimensions(match[1].strip)
36
elsif !url.match(%r{https?://})
37
img_path = File.absolute_path(File.join(tuto_dir, url))
38
_get_image_dimensions(img_path) if File.exist?(img_path)
39
else
40
_get_image_dimensions(img_path)
41
end
42
end
43
44
def self._get_image_dimensions(path)
45
cache.getset(path) do
46
[FastImage.size(path), path]
47
rescue StandardError
48
Jekyll.logger.info "[GTN/Images] Could not resolve size of #{path}"
49
end
50
end
51
end
52
end
53
54