Module: TailwindMerge::ParseClassName

Included in:
Merger
Defined in:
lib/tailwind_merge/parse_class_name.rb

Constant Summary collapse

IMPORTANT_MODIFIER =
"!"
MODIFIER_SEPARATOR =
":"
MODIFIER_SEPARATOR_LENGTH =
MODIFIER_SEPARATOR.length

Instance Method Summary collapse

Instance Method Details

#parse_class_name(class_name, prefix: nil) ⇒ Object

Parse class name into parts.

Inspired by ‘splitAtTopLevelOnly` used in Tailwind CSS



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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/tailwind_merge/parse_class_name.rb', line 17

def parse_class_name(class_name, prefix: nil)
  unless prefix.nil?
    full_prefix = "#{prefix}#{MODIFIER_SEPARATOR}"
    if class_name.start_with?(full_prefix)
      return parse_class_name(class_name[full_prefix.length..])
    else
      return TailwindClass.new(
        is_external: true,
        modifiers: [],
        has_important_modifier: false,
        base_class_name: class_name,
        maybe_postfix_modifier_position: nil,
      )
    end
  end

  modifiers = []

  bracket_depth = 0
  paren_depth = 0
  modifier_start = 0
  postfix_modifier_position = nil

  class_name.each_char.with_index do |char, index|
    if bracket_depth.zero? && paren_depth.zero?
      if char == MODIFIER_SEPARATOR
        modifiers << class_name[modifier_start...index]
        modifier_start = index + MODIFIER_SEPARATOR_LENGTH
        next
      elsif char == "/"
        postfix_modifier_position = index
        next
      end
    end

    bracket_depth += 1 if char == "["
    bracket_depth -= 1 if char == "]"
    paren_depth += 1 if char == "("
    paren_depth -= 1 if char == ")"
  end

  base_class_name_with_important_modifier = modifiers.empty? ? class_name : class_name[modifier_start..]

  base_class_name, has_important_modifier = strip_important_modifier(base_class_name_with_important_modifier)

  maybe_postfix_modifier_position = if postfix_modifier_position && postfix_modifier_position > modifier_start
    postfix_modifier_position - modifier_start
  end

  TailwindClass.new(
    is_external: false,
    modifiers:,
    has_important_modifier:,
    base_class_name: base_class_name,
    maybe_postfix_modifier_position:,
  )
end

#strip_important_modifier(base_class_name) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/tailwind_merge/parse_class_name.rb', line 75

def strip_important_modifier(base_class_name)
  if base_class_name.end_with?(IMPORTANT_MODIFIER)
    return [base_class_name[0...-IMPORTANT_MODIFIER.length], true]
  end

  # In Tailwind CSS v3 the important modifier was at the start of the base class name. This is still supported for legacy reasons.
  # @see https://github.com/dcastil/tailwind-merge/issues/513#issuecomment-2614029864
  if base_class_name.start_with?(IMPORTANT_MODIFIER)
    return [base_class_name[1..], true]
  end

  [base_class_name, false]
end