Module: CssParserMaster

Defined in:
lib/css_parser_master.rb,
lib/css_parser_master/parser.rb,
lib/css_parser_master/regexps.rb,
lib/css_parser_master/rule_set.rb,
lib/css_parser_master/selector.rb,
lib/css_parser_master/selectors.rb,
lib/css_parser_master/declaration.rb,
lib/css_parser_master/declarations.rb,
lib/css_parser_master/declaration_api.rb

Defined Under Namespace

Modules: DeclarationAPI Classes: CircularReferenceError, Declaration, Declarations, Parser, RemoteFileError, RuleSet, Selector, Selectors

Constant Summary collapse

VERSION =
'1.2.5'
RE_NL =

:stopdoc: Base types

Regexp.new('(\n|\r\n|\r|\f)')
RE_NON_ASCII =
^0-177
Regexp.new('([\x00-\xFF])', Regexp::IGNORECASE, 'n')
RE_UNICODE =
Regexp.new('(\\\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])*)', Regexp::IGNORECASE | Regexp::EXTENDED | Regexp::MULTILINE, 'n')
RE_ESCAPE =
Regexp.union(RE_UNICODE, '|(\\\\[^\n\r\f0-9a-f])')
RE_IDENT =
Regexp.new("[\-]?([_a-z]|#{RE_NON_ASCII}|#{RE_ESCAPE})([_a-z0-9\-]|#{RE_NON_ASCII}|#{RE_ESCAPE})*", Regexp::IGNORECASE, 'n')
RE_STRING1 =

General strings

Regexp.new('(\"(.[^\n\r\f\\"]*|\\\\' + RE_NL.to_s + '|' + RE_ESCAPE.to_s + ')*\")')
RE_STRING2 =
Regexp.new('(\'(.[^\n\r\f\\\']*|\\\\' + RE_NL.to_s + '|' + RE_ESCAPE.to_s + ')*\')')
RE_STRING =
Regexp.union(RE_STRING1, RE_STRING2)
RE_URI =
Regexp.new('(url\([\s]*([\s]*' + RE_STRING.to_s + '[\s]*)[\s]*\))|(url\([\s]*([!#$%&*\-~]|' + RE_NON_ASCII.to_s + '|' + RE_ESCAPE.to_s + ')*[\s]*)\)', Regexp::IGNORECASE | Regexp::EXTENDED  | Regexp::MULTILINE, 'n')
URI_RX =
/url\(("([^"]*)"|'([^']*)'|([^)]*))\)/im
RE_AT_IMPORT_RULE =

Initial parsing

/\@import[\s]+(url\()?["''"]?(.[^'"\s"']*)["''"]?\)?([\w\s\,^\])]*)\)?;?/
IMPORTANT_IN_PROPERTY_RX =

RE_AT_IMPORT_RULE = Regexp.new(‘@import*(’ + RE_STRING.to_s + ‘)([ws,]*)?’, Regexp::IGNORECASE) – should handle url() even though it is not allowed ++

/[\s]*\!important[\s]*/i
STRIP_CSS_COMMENTS_RX =
/\/\*.*?\*\//m
STRIP_HTML_COMMENTS_RX =
/\<\!\-\-|\-\-\>/m
BOX_MODEL_UNITS_RX =

Special units

/(auto|inherit|0|([\-]*([0-9]+|[0-9]*\.[0-9]+)(e[mx]+|px|[cm]+m|p[tc+]|in|\%)))([\s;]|\Z)/imx
RE_LENGTH_OR_PERCENTAGE =
Regexp.new('([\-]*(([0-9]*\.[0-9]+)|[0-9]+)(e[mx]+|px|[cm]+m|p[tc+]|in|\%))', Regexp::IGNORECASE)
RE_BACKGROUND_POSITION =
Regexp.new("((#{RE_LENGTH_OR_PERCENTAGE})|left|center|right|top|bottom)", Regexp::IGNORECASE | Regexp::EXTENDED)
FONT_UNITS_RX =
/(([x]+\-)*small|medium|large[r]*|auto|inherit|([0-9]+|[0-9]*\.[0-9]+)(e[mx]+|px|[cm]+m|p[tc+]|in|\%)*)/i
ELEMENTS_AND_PSEUDO_ELEMENTS_RX =

Patterns for specificity calculations

/((^|[\s\+\>]+)[\w]+|\:(first\-line|first\-letter|before|after))/i
NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX =
/(\.[\w]+)|(\[[\w]+)|(\:(link|first\-child|lang))/i
RE_COLOUR_RGB =

Colours

Regexp.new('(rgb[\s]*\([\s-]*[\d]+(\.[\d]+)?[%\s]*,[\s-]*[\d]+(\.[\d]+)?[%\s]*,[\s-]*[\d]+(\.[\d]+)?[%\s]*\))', Regexp::IGNORECASE)
RE_COLOUR_HEX =
/(#([0-9a-f]{6}|[0-9a-f]{3})([\s;]|$))/i
RE_COLOUR_NAMED =
/([\s]*^)?(aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|transparent)([\s]*$)?/i
RE_COLOUR =
Regexp.union(RE_COLOUR_RGB, RE_COLOUR_HEX, RE_COLOUR_NAMED)

Class Method Summary collapse

Class Method Details

.calculate_specificity(selector) ⇒ Object

Calculates the specificity of a CSS selector per www.w3.org/TR/CSS21/cascade.html#specificity

Returns an integer.

Example

CssParser.calculate_specificity('#content div p:first-line a:link')
=> 114

– Thanks to Rafael Salazar and Nick Fitzsimons on the css-discuss list for their help. ++



111
112
113
114
115
116
117
118
119
120
# File 'lib/css_parser_master.rb', line 111

def self.calculate_specificity(selector)
  a = 0
  b = selector.scan(/\#/).length
  c = selector.scan(NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX).length
  d = selector.scan(ELEMENTS_AND_PSEUDO_ELEMENTS_RX).length

  (a.to_s + b.to_s + c.to_s + d.to_s).to_i
rescue
  return 0
end

.convert_uris(css, base_uri) ⇒ Object

Make url() links absolute.

Takes a block of CSS and returns it with all relative URIs converted to absolute URIs.

“For CSS style sheets, the base URI is that of the style sheet, not that of the source document.” per www.w3.org/TR/CSS21/syndata.html#uri

Returns a string.

Example

CssParser.convert_uris("body { background: url('../style/yellow.png?abc=123') };", 
             "http://example.org/style/basic.css").inspect
=> "body { background: url('http://example.org/style/yellow.png?abc=123') };"


135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/css_parser_master.rb', line 135

def self.convert_uris(css, base_uri)
  out = ''
  base_uri = URI.parse(base_uri) unless base_uri.kind_of?(URI)

  out = css.gsub(URI_RX) do |s|
    uri = $1.to_s
    uri.gsub!(/["']+/, '')
    # Don't process URLs that are already absolute
    unless uri =~ /^[a-z]+\:\/\//i
      begin
        uri = base_uri.merge(uri) 
      rescue; end
    end
    "url('" + uri.to_s + "')"
  end
  out
end

.merge(*rule_sets) ⇒ Object

Merge multiple CSS RuleSets by cascading according to the CSS 2.1 cascading rules (www.w3.org/TR/REC-CSS2/cascade.html#cascading-order).

Takes one or more RuleSet objects.

Returns a RuleSet.

Cascading

If a RuleSet object has its specificity defined, that specificity is used in the cascade calculations.

If no specificity is explicitly set and the RuleSet has one selector, the specificity is calculated using that selector.

If no selectors or multiple selectors are present, the specificity is treated as 0.

Example #1

rs1 = RuleSet.new(nil, 'color: black;')
rs2 = RuleSet.new(nil, 'margin: 0px;')

merged = CssParserMaster.merge(rs1, rs2)

puts merged
=> "{ margin: 0px; color: black; }"

Example #2

rs1 = RuleSet.new(nil, 'background-color: black;')
rs2 = RuleSet.new(nil, 'background-image: none;')

merged = CssParserMaster.merge(rs1, rs2)

puts merged
=> "{ background: none black; }"

– TODO: declaration_hashes should be able to contain a RuleSet

this should be a Class method


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
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/css_parser_master.rb', line 46

def self.merge(*rule_sets)
  @folded_declaration_cache = {}

  # in case called like CssParser.merge([rule_set, rule_set])
  rule_sets.flatten! if rule_sets[0].kind_of?(Array)
  
  unless rule_sets.all? {|rs| rs.kind_of?(CssParser::RuleSet)}
    raise ArgumentError, "all parameters must be CssParser::RuleSets."
  end

  return rule_sets[0] if rule_sets.length == 1

  # Internal storage of CSS properties that we will keep
  properties = {}

  rule_sets.each do |rule_set|
    rule_set.expand_shorthand!
    
    specificity = rule_set.specificity
    unless specificity
      if rule_set.selectors.length == 1
        specificity = calculate_specificity(rule_set.selectors[0])
      else
        specificity = 0
      end
    end

    rule_set.each_declaration do |decl|
      
      property = decl.property
      value = decl.value
      is_important = decl.important
      
      # Add the property to the list to be folded per http://www.w3.org/TR/CSS21/cascade.html#cascading-order
      if not properties.has_key?(decl.property) or
             is_important or # step 2
             properties[property][:specificity] < specificity or # step 3
             properties[property][:specificity] == specificity # step 4    
        properties[property] = {:value => value, :specificity => specificity, :is_important => is_important}            
      end
    end
  end

  merged = RuleSet.new(nil, nil)

  # TODO: what about important
  properties.each do |property, details|
    merged[property.strip] = details[:value].strip
  end

  merged.create_shorthand!
  merged
end