forked from Shopify/theme-check
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrip_liquid_in_text_html.rb
58 lines (47 loc) · 2.02 KB
/
strip_liquid_in_text_html.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
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true
module ThemeCheck
# Ensure that the body of certain text tags like span and p, if they are liquid variables, are left and right stripped.
class StripLiquidInTextHtml < HtmlCheck
include RegexHelpers
severity :suggestion
category :html
doc docs_url(__FILE__)
LEFT_LIQUID = /\A\s+(#{LIQUID_SINGLE_CONSTRUCT})/om
RIGHT_LIQUID = /(#{LIQUID_SINGLE_CONSTRUCT})\s+\z/om
DEFAULT_ELEMENTS = %w[h1 h2 h3 h4 h5 h6 span small p b strong i em a q blockquote code pre ul ol li].freeze
def initialize(elements: [])
@elements = elements.empty? ? DEFAULT_ELEMENTS : elements
end
def on_element(node)
return unless @elements.include?(node.name) && single_text_body?(node)
lint_text_node_left(node.children[0])
lint_text_node_right(node.children[0])
end
private
def lint_text_node_left(node)
return unless (match = node.markup.match(LEFT_LIQUID))
return if match[1].start_with?("{%-") || match[1].start_with?("{{-")
add_offense("Left strip liquid as html text",
node: node, markup: match[1], node_markup_offset: match.begin(1)) do |corrector|
ms = node.markup.scan(match[1])
next unless ms.size == 1
escaped_match = match[1].sub(/\A{{/, '{{-').sub(/\A{%/, '{%-')
corrector.replace(node, node.markup.sub(match[1], escaped_match))
end
end
def lint_text_node_right(node)
return unless (match = node.markup.match(RIGHT_LIQUID))
return if match[1].end_with?("-%}") || match[1].end_with?("-}}")
add_offense("Right strip liquid as html text",
node: node, markup: match[1], node_markup_offset: match.begin(1)) do |corrector|
ms = node.markup.scan(match[1])
next unless ms.size == 1
escaped_match = match[1].sub(/}}\z/, '-}}').sub(/%}\z/, '-%}')
corrector.replace(node, node.markup.sub(match[1], escaped_match))
end
end
def single_text_body?(node)
node.children.size == 1 && node.children[0].name == "text"
end
end
end