forked from Shopify/theme-check
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimg_width_and_height.rb
48 lines (39 loc) · 1.42 KB
/
img_width_and_height.rb
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true
module ThemeCheck
# Reports errors when trying to use parser-blocking script tags
class ImgWidthAndHeight < HtmlCheck
severity :error
categories :html, :performance
doc docs_url(__FILE__)
ENDS_IN_CSS_UNIT = /(cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)$/i
def initialize(whitelist: [])
@whitelist = whitelist || []
end
def on_img(node)
width = node.attributes["width"]
height = node.attributes["height"]
record_units_in_field_offenses("width", width, node: node)
record_units_in_field_offenses("height", height, node: node)
return if node.attributes["src"].nil? || (width && height) || @whitelist.any? { |word| node.value.include?(word) }
missing_width = width.nil?
missing_height = height.nil?
error_message = if missing_width && missing_height
"Missing width and height attributes"
elsif missing_width
"Missing width attribute"
elsif missing_height
"Missing height attribute"
end
add_offense(error_message, node: node)
end
private
def record_units_in_field_offenses(attribute, value, node:)
return unless value =~ ENDS_IN_CSS_UNIT
value_without_units = value.gsub(ENDS_IN_CSS_UNIT, '')
add_offense(
"The #{attribute} attribute does not take units. Replace with \"#{value_without_units}\"",
node: node,
)
end
end
end