Class: Proscenium::Phlex::CssModuleRewriter::Processor

Inherits:
Prism::Visitor
  • Object
show all
Defined in:
lib/proscenium/phlex/css_module_rewriter.rb

Constant Summary collapse

PREFIX =
'@'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeProcessor



41
42
43
# File 'lib/proscenium/phlex/css_module_rewriter.rb', line 41

def initialize
  @annotations = []
end

Instance Attribute Details

#annotationsObject (readonly)

Returns the value of attribute annotations.



47
48
49
# File 'lib/proscenium/phlex/css_module_rewriter.rb', line 47

def annotations
  @annotations
end

Class Method Details

.call(source) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/proscenium/phlex/css_module_rewriter.rb', line 19

def self.call(source)
  visitor = new
  visitor.visit(Prism.parse(source).value)

  buffer = source.dup
  annotations = visitor.annotations
  annotations.sort_by!(&:first)

  annotations.reverse_each do |offset, action|
    case action
    when :start
      buffer.insert(offset, 'class_names(*')
    when :end
      buffer.insert(offset, ')')
    else
      raise 'Invalid annotation'
    end
  end

  buffer
end

Instance Method Details

#build_annotation(value) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/proscenium/phlex/css_module_rewriter.rb', line 65

def build_annotation(value)
  location = value.location

  @annotations <<
    [location.start_character_offset, :start] <<
    [location.end_character_offset, :end]
end

#visit_assoc_node(node) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/proscenium/phlex/css_module_rewriter.rb', line 49

def visit_assoc_node(node)
  # Skip if the key is not a symbol or string
  return if i[symbol_node string_node].exclude?(node.key.type)

  return if node.key.type == :symbol_node && node.key.value != 'class'
  return if node.key.type == :string_node && node.key.content != 'class'

  value = node.value
  type = value.type

  if (type == :symbol_node && value.value.start_with?(PREFIX)) ||
     (type == :array_node && value.elements.any? { it.value.start_with?(PREFIX) })
    build_annotation value
  end
end