Class: Less::Engine

Inherits:
String
  • Object
show all
Defined in:
lib/less/engine.rb

Constant Summary collapse

REGEXP =
{
  :path     => /([#.][->#.\w ]+)?( ?> ?)?@([-\w]+)/,     # #header > .title > @var
  :selector => /[-\w #.>*:]/,                            # .cow .milk > a
  :variable => /@([-\w]+)/,                              # @milk-white
  :property => /@[-\w]+|[-a-z]+/                         # font-size
}

Instance Method Summary collapse

Constructor Details

#initialize(s) ⇒ Engine

Returns a new instance of Engine.



10
11
12
13
# File 'lib/less/engine.rb', line 10

def initialize s
  super
  @tree = Tree.new self.hashify
end

Instance Method Details

#compileObject Also known as: render



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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/less/engine.rb', line 15

def compile     
  #
  # Parse the variables and mixins
  #
  # We use symbolic keys, such as :mixins, to store LESS-only data,
  # each branch has its own :mixins => [], and :variables => {}
  # Once a declaration has been recognised as LESS-specific, it is copied 
  # in the appropriate data structure in that branch. The declaration itself
  # can then be deleted.
  #
  @tree = @tree.traverse :leaf do |key, value, path, node|
    matched = if match = key.match( REGEXP[:variable] )          
      node[:variables] ||= Tree.new
      node[:variables][ match.captures.first ] = value
    elsif value == :mixin
      node[:mixins] ||= []          
      node[:mixins] << key
    end
    node.delete key if matched # Delete the property if it's LESS-specific
  end
  
  #
  # Evaluate mixins
  #
  @tree = @tree.traverse :branch do |path, node|
    if node.include? :mixins
      node[:mixins].each do |m|
        @tree.find( :mixin, m.delete(' ').split('>') ).each {|k, v| node[ k ] = v }
      end
    end
  end
  
  # Call `evaluate` on variables, such as '@dark: @light / 2'
  @tree = @tree.traverse :branch do |path, node|
    node.vars.each do |key, value|
      evaluate key, value, node.vars
    end if node.vars?
  end
  
  # Call `evaluate` on css properties, such as 'font-size: @big'
  @tree = @tree.traverse :leaf do |key, value, path, node|
    evaluate key, value, node
  end
  
  #
  # Evaluate operations (2+2)
  #
  # Units are: 1px, 1em, 1%, #111
  @tree = @tree.traverse :leaf do |key, value, path, node|
    if value.match /[-+\/*]/
      if (unit = value.scan(/(%)|\d+(px)|\d+(em)|(#)/i).flatten.compact.uniq).size <= 1
        unit = unit.join            
        value = if unit == '#'
          evaluate = lambda do |v| 
            result = eval v
            unit + ( result.zero?? '000' : result.to_s(16) )
          end
          value.gsub(/#([a-z0-9]+)/i) do
            hex = $1 * ( $1.size < 6 ? 6 / $1.size : 1 )
            hex.to_i(16)
          end.delete unit
        else
          evaluate = lambda {|v| eval( v ).to_s + unit }
          value.gsub(/px|em|%/, '')
        end.to_s                
        next if value.match /[a-z]/i
        node[ key ] = evaluate.call value
      else
        raise MixedUnitsError
      end
    end
  end
end

#evaluate(key, value, node) ⇒ Object

Evaluate variables



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/less/engine.rb', line 93

def evaluate key, value, node               
  if value.is_a? String and value.include? '@'       # There's a var to evaluate    
    value.scan REGEXP[:path] do |p|
      p = p.join.delete ' '
      var = if p.include? '>'
        @tree.find :var, p.split('>')                # Try finding it in a specific namespace
      else
        node.var( p ) || @tree.var( p )              # Try local first, then global
      end

      if var
        node[ key ] = value.gsub REGEXP[:path], var  # Substitute variable with value
      else
        node.delete key                              # Discard the declaration if the variable wasn't found
      end
    end    
  end
end

#hashifyObject



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/less/engine.rb', line 116

def hashify
#
# Parse the LESS structure into a hash
#
###
  #   less:     color: black;
  #   hashify: "color" => "black"
  #
  hash = self.gsub(/\/\/.*\n/, '').                                                   # Comments //
              gsub(/\/\*.*?\//m, '').                                                 # Comments /*
              gsub(/"/, "'").                                                         # " => '
              gsub(/("|')(.+?)(\1)/) { $1 + CGI.escape( $2 ) + $1 }.                  # Escape string values
              gsub(/(#{REGEXP[:property]}):[ \t]*(.+?);/, '"\\1" => "\\2",').         # Declarations
              gsub(/\}/, "},").                                                       # Closing }
              gsub(/([ \t]*)(#{REGEXP[:selector]}+?)[ \t\n]*\{/m, '\\1"\\2" => {').   # Selectors
              gsub(/([.#][->\w .#]+);/, '"\\1" => :mixin,')                           # Mixins
  eval "{" + hash + "}"                                                               # Return {hash}
end

#to_cssObject



112
113
114
# File 'lib/less/engine.rb', line 112

def to_css
  self.compile.to_css
end