Class: CssParser::RuleSet
- Inherits:
-
Object
- Object
- CssParser::RuleSet
- Defined in:
- lib/css_parser/rule_set.rb
Constant Summary collapse
- RE_ELEMENTS_AND_PSEUDO_ELEMENTS =
Patterns for specificity calculations
/((^|[\s\+\>]+)[\w]+|\:(first\-line|first\-letter|before|after))/i
- RE_NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES =
/(\.[\w]+)|(\[[\w]+)|(\:(link|first\-child|lang))/i
- BACKGROUND_PROPERTIES =
['background-color', 'background-image', 'background-repeat', 'background-position', 'background-size', 'background-attachment']
- LIST_STYLE_PROPERTIES =
['list-style-type', 'list-style-position', 'list-style-image']
Instance Attribute Summary collapse
-
#selectors ⇒ Object
readonly
Array of selector strings.
-
#specificity ⇒ Object
Integer with the specificity to use for this RuleSet.
Instance Method Summary collapse
-
#add_declaration!(property, value) ⇒ Object
(also: #[]=)
Add a CSS declaration to the current RuleSet.
-
#create_background_shorthand! ⇒ Object
Looks for long format CSS background properties (e.g.
background-color
) and converts them into a shorthand CSSbackground
property. -
#create_border_shorthand! ⇒ Object
Combine border-color, border-style and border-width into border Should be run after create_dimensions_shorthand!.
-
#create_dimensions_shorthand! ⇒ Object
Looks for long format CSS dimensional properties (margin, padding, border-color, border-style and border-width) and converts them into shorthand CSS properties.
-
#create_font_shorthand! ⇒ Object
Looks for long format CSS font properties (e.g.
font-weight
) and tries to convert them into a shorthand CSSfont
property. -
#create_list_style_shorthand! ⇒ Object
Looks for long format CSS list-style properties (e.g.
list-style-type
) and converts them into a shorthand CSSlist-style
property. -
#create_shorthand! ⇒ Object
Create shorthand declarations (e.g.
margin
orfont
) whenever possible. -
#create_shorthand_properties!(properties, shorthand_property) ⇒ Object
Combine several properties into a shorthand one.
-
#declarations_to_s(options = {}) ⇒ Object
Return all declarations as a string.
-
#each_declaration ⇒ Object
Iterate through declarations.
-
#each_selector(options = {}) ⇒ Object
Iterate through selectors.
-
#expand_background_shorthand! ⇒ Object
Convert shorthand background declarations (e.g.
background: url("chess.png") gray 50% repeat fixed;
) into their constituent parts. -
#expand_border_shorthand! ⇒ Object
Split shorthand border declarations (e.g.
border: 1px red;
) Additional splitting happens in expand_dimensions_shorthand!. -
#expand_dimensions_shorthand! ⇒ Object
Split shorthand dimensional declarations (e.g.
margin: 0px auto;
) into their constituent parts. -
#expand_font_shorthand! ⇒ Object
Convert shorthand font declarations (e.g.
font: 300 italic 11px/14px verdana, helvetica, sans-serif;
) into their constituent parts. -
#expand_list_style_shorthand! ⇒ Object
Convert shorthand list-style declarations (e.g.
list-style: lower-alpha outside;
) into their constituent parts. -
#expand_shorthand! ⇒ Object
Split shorthand declarations (e.g.
margin
orfont
) into their constituent parts. - #extract_background_size_from(value) ⇒ Object
-
#get_value(property) ⇒ Object
(also: #[])
Get the value of a property.
-
#initialize(selectors, block, specificity = nil) ⇒ RuleSet
constructor
A new instance of RuleSet.
-
#remove_declaration!(property) ⇒ Object
Remove CSS declaration from the current RuleSet.
-
#to_s ⇒ Object
Return the CSS rule set as a string.
Constructor Details
#initialize(selectors, block, specificity = nil) ⇒ RuleSet
Returns a new instance of RuleSet.
16 17 18 19 20 21 22 23 |
# File 'lib/css_parser/rule_set.rb', line 16 def initialize(selectors, block, specificity = nil) @selectors = [] @specificity = specificity @declarations = {} @order = 0 parse_selectors!(selectors) if selectors parse_declarations!(block) end |
Instance Attribute Details
#selectors ⇒ Object (readonly)
Array of selector strings.
11 12 13 |
# File 'lib/css_parser/rule_set.rb', line 11 def selectors @selectors end |
#specificity ⇒ Object
Integer with the specificity to use for this RuleSet.
14 15 16 |
# File 'lib/css_parser/rule_set.rb', line 14 def specificity @specificity end |
Instance Method Details
#add_declaration!(property, value) ⇒ Object Also known as: []=
Add a CSS declaration to the current RuleSet.
rule_set.add_declaration!('color', 'blue')
puts rule_set['color']
=> 'blue;'
rule_set.add_declaration!('margin', '0px auto !important')
puts rule_set['margin']
=> '0px auto !important;'
If the property already exists its value will be over-written.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/css_parser/rule_set.rb', line 53 def add_declaration!(property, value) if value.nil? or value.empty? @declarations.delete(property) return end value.gsub!(/;\Z/, '') is_important = !value.gsub!(CssParser::IMPORTANT_IN_PROPERTY_RX, '').nil? property = property.downcase.strip #puts "SAVING #{property} #{value} #{is_important.inspect}" @declarations[property] = { :value => value, :is_important => is_important, :order => @order += 1 } end |
#create_background_shorthand! ⇒ Object
Looks for long format CSS background properties (e.g. background-color
) and converts them into a shorthand CSS background
property.
Leaves properties declared !important alone.
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 |
# File 'lib/css_parser/rule_set.rb', line 336 def create_background_shorthand! # :nodoc: # When we have a background-size property we must separate it and distinguish it from # background-position by preceeding it with a backslash. In this case we also need to # have a background-position property, so we set it if it's missing. # http://www.w3schools.com/cssref/css3_pr_background.asp if @declarations.has_key?('background-size') and not @declarations['background-size'][:is_important] unless @declarations.has_key?('background-position') @declarations['background-position'] = {:value => 'initial'} end @declarations['background-size'][:value] = "/ #{@declarations['background-size'][:value]}" end create_shorthand_properties! BACKGROUND_PROPERTIES, 'background' end |
#create_border_shorthand! ⇒ Object
Combine border-color, border-style and border-width into border Should be run after create_dimensions_shorthand!
TODO: this is extremely similar to create_background_shorthand! and should be combined
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
# File 'lib/css_parser/rule_set.rb', line 356 def create_border_shorthand! # :nodoc: values = [] ['border-width', 'border-style', 'border-color'].each do |property| if @declarations.has_key?(property) and not @declarations[property][:is_important] # can't merge if any value contains a space (i.e. has multiple values) # we temporarily remove any spaces after commas for the check (inside rgba, etc...) return if @declarations[property][:value].gsub(/\,[\s]/, ',').strip =~ /[\s]/ values << @declarations[property][:value] end end @declarations.delete('border-width') @declarations.delete('border-style') @declarations.delete('border-color') unless values.empty? @declarations['border'] = {:value => values.join(' ')} end end |
#create_dimensions_shorthand! ⇒ Object
Looks for long format CSS dimensional properties (margin, padding, border-color, border-style and border-width) and converts them into shorthand CSS properties.
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 |
# File 'lib/css_parser/rule_set.rb', line 379 def create_dimensions_shorthand! # :nodoc: directions = ['top', 'right', 'bottom', 'left'] {'margin' => 'margin-%s', 'padding' => 'padding-%s', 'border-color' => 'border-%s-color', 'border-style' => 'border-%s-style', 'border-width' => 'border-%s-width'}.each do |property, | top, right, bottom, left = ['top', 'right', 'bottom', 'left'].map { |side| % side } foldable = @declarations.select do |dim, val| dim == top or dim == right or dim == bottom or dim == left end # All four dimensions must be present if foldable.length == 4 values = {} directions.each { |d| values[d.to_sym] = @declarations[ % d][:value].downcase.strip } if values[:left] == values[:right] if values[:top] == values[:bottom] if values[:top] == values[:left] # All four sides are equal new_value = values[:top] else # Top and bottom are equal, left and right are equal new_value = values[:top] + ' ' + values[:left] end else # Only left and right are equal new_value = values[:top] + ' ' + values[:left] + ' ' + values[:bottom] end else # No sides are equal new_value = values[:top] + ' ' + values[:right] + ' ' + values[:bottom] + ' ' + values[:left] end new_value.strip! @declarations[property] = {:value => new_value.strip} unless new_value.empty? # Delete the longhand values directions.each { |d| @declarations.delete( % d) } end end end |
#create_font_shorthand! ⇒ Object
Looks for long format CSS font properties (e.g. font-weight
) and tries to convert them into a shorthand CSS font
property. All font properties must be present in order to create a shorthand declaration.
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 |
# File 'lib/css_parser/rule_set.rb', line 425 def create_font_shorthand! # :nodoc: ['font-style', 'font-variant', 'font-weight', 'font-size', 'line-height', 'font-family'].each do |prop| return unless @declarations.has_key?(prop) end new_value = '' ['font-style', 'font-variant', 'font-weight'].each do |property| unless @declarations[property][:value] == 'normal' new_value += @declarations[property][:value] + ' ' end end new_value += @declarations['font-size'][:value] unless @declarations['line-height'][:value] == 'normal' new_value += '/' + @declarations['line-height'][:value] end new_value += ' ' + @declarations['font-family'][:value] @declarations['font'] = {:value => new_value.gsub(/[\s]+/, ' ').strip} ['font-style', 'font-variant', 'font-weight', 'font-size', 'line-height', 'font-family'].each do |prop| @declarations.delete(prop) end end |
#create_list_style_shorthand! ⇒ Object
Looks for long format CSS list-style properties (e.g. list-style-type
) and converts them into a shorthand CSS list-style
property.
Leaves properties declared !important alone.
459 460 461 |
# File 'lib/css_parser/rule_set.rb', line 459 def create_list_style_shorthand! # :nodoc: create_shorthand_properties! LIST_STYLE_PROPERTIES, 'list-style' end |
#create_shorthand! ⇒ Object
Create shorthand declarations (e.g. margin
or font
) whenever possible.
308 309 310 311 312 313 314 315 |
# File 'lib/css_parser/rule_set.rb', line 308 def create_shorthand! create_background_shorthand! create_dimensions_shorthand! # border must be shortened after dimensions create_border_shorthand! create_font_shorthand! create_list_style_shorthand! end |
#create_shorthand_properties!(properties, shorthand_property) ⇒ Object
Combine several properties into a shorthand one
318 319 320 321 322 323 324 325 326 327 328 329 330 |
# File 'lib/css_parser/rule_set.rb', line 318 def create_shorthand_properties! properties, shorthand_property # :nodoc: values = [] properties.each do |property| if @declarations.has_key?(property) and not @declarations[property][:is_important] values << @declarations[property][:value] @declarations.delete(property) end end unless values.empty? @declarations[shorthand_property] = {:value => values.join(' ')} end end |
#declarations_to_s(options = {}) ⇒ Object
Return all declarations as a string. – TODO: Clean-up regexp doesn’t seem to work ++
107 108 109 110 111 112 113 114 115 |
# File 'lib/css_parser/rule_set.rb', line 107 def declarations_to_s( = {}) = {:force_important => false}.merge() str = '' each_declaration do |prop, val, is_important| importance = ([:force_important] || is_important) ? ' !important' : '' str += "#{prop}: #{val}#{importance}; " end str.gsub(/^[\s^(\{)]+|[\n\r\f\t]*|[\s]+$/mx, '').strip end |
#each_declaration ⇒ Object
Iterate through declarations.
95 96 97 98 99 100 101 |
# File 'lib/css_parser/rule_set.rb', line 95 def each_declaration # :yields: property, value, is_important decs = @declarations.sort { |a,b| a[1][:order].nil? || b[1][:order].nil? ? 0 : a[1][:order] <=> b[1][:order] } decs.each do |property, data| value = data[:value] yield property.downcase.strip, value.strip, data[:is_important] end end |
#each_selector(options = {}) ⇒ Object
Iterate through selectors.
Options
-
force_important
– boolean
Example
ruleset.each_selector do |sel, dec, spec|
...
end
85 86 87 88 89 90 91 92 |
# File 'lib/css_parser/rule_set.rb', line 85 def each_selector( = {}) # :yields: selector, declarations, specificity declarations = declarations_to_s() if @specificity @selectors.each { |sel| yield sel.strip, declarations, @specificity } else @selectors.each { |sel| yield sel.strip, declarations, CssParser.calculate_specificity(sel) } end end |
#expand_background_shorthand! ⇒ Object
Convert shorthand background declarations (e.g. background: url("chess.png") gray 50% repeat fixed;
) into their constituent parts.
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
# File 'lib/css_parser/rule_set.rb', line 137 def # :nodoc: return unless @declarations.has_key?('background') value = @declarations['background'][:value] if value =~ CssParser::RE_INHERIT BACKGROUND_PROPERTIES.each do |prop| split_declaration('background', prop, 'inherit') end end split_declaration('background', 'background-image', value.slice!(Regexp.union(CssParser::URI_RX, CssParser::RE_GRADIENT, /none/i))) split_declaration('background', 'background-attachment', value.slice!(CssParser::RE_SCROLL_FIXED)) split_declaration('background', 'background-repeat', value.slice!(CssParser::RE_REPEAT)) split_declaration('background', 'background-color', value.slice!(CssParser::RE_COLOUR)) split_declaration('background', 'background-size', extract_background_size_from(value)) split_declaration('background', 'background-position', value.slice(CssParser::RE_BACKGROUND_POSITION)) @declarations.delete('background') end |
#expand_border_shorthand! ⇒ Object
Split shorthand border declarations (e.g. border: 1px red;
) Additional splitting happens in expand_dimensions_shorthand!
166 167 168 169 170 171 172 173 174 175 176 177 178 |
# File 'lib/css_parser/rule_set.rb', line 166 def # :nodoc: ['border', 'border-left', 'border-right', 'border-top', 'border-bottom'].each do |k| next unless @declarations.has_key?(k) value = @declarations[k][:value] split_declaration(k, "#{k}-width", value.slice!(CssParser::RE_BORDER_UNITS)) split_declaration(k, "#{k}-color", value.slice!(CssParser::RE_COLOUR)) split_declaration(k, "#{k}-style", value.slice!(CssParser::RE_BORDER_STYLE)) @declarations.delete(k) end end |
#expand_dimensions_shorthand! ⇒ Object
Split shorthand dimensional declarations (e.g. margin: 0px auto;
) into their constituent parts. Handles margin, padding, border-color, border-style and border-width.
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/css_parser/rule_set.rb', line 182 def # :nodoc: {'margin' => 'margin-%s', 'padding' => 'padding-%s', 'border-color' => 'border-%s-color', 'border-style' => 'border-%s-style', 'border-width' => 'border-%s-width'}.each do |property, | next unless @declarations.has_key?(property) value = @declarations[property][:value] # RGB and HSL values in borders are the only units that can have spaces (within params). # We cheat a bit here by stripping spaces after commas in RGB and HSL values so that we # can split easily on spaces. # # TODO: rgba, hsl, hsla value.gsub!(RE_COLOUR) { |c| c.gsub(/(\s?\,\s?)/, ',') } matches = value.strip.split(/[\s]+/) t, r, b, l = nil case matches.length when 1 t, r, b, l = matches[0], matches[0], matches[0], matches[0] when 2 t, b = matches[0], matches[0] r, l = matches[1], matches[1] when 3 t = matches[0] r, l = matches[1], matches[1] b = matches[2] when 4 t = matches[0] r = matches[1] b = matches[2] l = matches[3] end split_declaration(property, % 'top', t) split_declaration(property, % 'right', r) split_declaration(property, % 'bottom', b) split_declaration(property, % 'left', l) @declarations.delete(property) end end |
#expand_font_shorthand! ⇒ Object
Convert shorthand font declarations (e.g. font: 300 italic 11px/14px verdana, helvetica, sans-serif;
) into their constituent parts.
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
# File 'lib/css_parser/rule_set.rb', line 232 def # :nodoc: return unless @declarations.has_key?('font') font_props = {} # reset properties to 'normal' per http://www.w3.org/TR/CSS21/fonts.html#font-shorthand ['font-style', 'font-variant', 'font-weight', 'font-size', 'line-height'].each do |prop| font_props[prop] = 'normal' end value = @declarations['font'][:value] is_important = @declarations['font'][:is_important] order = @declarations['font'][:order] in_fonts = false matches = value.scan(/("(.*[^"])"|'(.*[^'])'|(\w[^ ,]+))/) matches.each do |match| m = match[0].to_s.strip m.gsub!(/[;]$/, '') if in_fonts if font_props.has_key?('font-family') font_props['font-family'] += ', ' + m else font_props['font-family'] = m end elsif m =~ /normal|inherit/i ['font-style', 'font-weight', 'font-variant'].each do |font_prop| font_props[font_prop] = m unless font_props.has_key?(font_prop) end elsif m =~ /italic|oblique/i font_props['font-style'] = m elsif m =~ /small\-caps/i font_props['font-variant'] = m elsif m =~ /[1-9]00$|bold|bolder|lighter/i font_props['font-weight'] = m elsif m =~ CssParser::FONT_UNITS_RX if m =~ /\// font_props['font-size'], font_props['line-height'] = m.split('/') else font_props['font-size'] = m end in_fonts = true end end font_props.each { |font_prop, font_val| @declarations[font_prop] = {:value => font_val, :is_important => is_important, :order => order} } @declarations.delete('font') end |
#expand_list_style_shorthand! ⇒ Object
Convert shorthand list-style declarations (e.g. list-style: lower-alpha outside;
) into their constituent parts.
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/css_parser/rule_set.rb', line 289 def # :nodoc: return unless @declarations.has_key?('list-style') value = @declarations['list-style'][:value] if value =~ CssParser::RE_INHERIT LIST_STYLE_PROPERTIES.each do |prop| split_declaration('list-style', prop, 'inherit') end end split_declaration('list-style', 'list-style-type', value.slice!(CssParser::RE_LIST_STYLE_TYPE)) split_declaration('list-style', 'list-style-position', value.slice!(CssParser::RE_INSIDE_OUTSIDE)) split_declaration('list-style', 'list-style-image', value.slice!(Regexp.union(CssParser::URI_RX, /none/i))) @declarations.delete('list-style') end |
#expand_shorthand! ⇒ Object
Split shorthand declarations (e.g. margin
or font
) into their constituent parts.
124 125 126 127 128 129 130 131 |
# File 'lib/css_parser/rule_set.rb', line 124 def # border must be expanded before dimensions end |
#extract_background_size_from(value) ⇒ Object
158 159 160 161 162 |
# File 'lib/css_parser/rule_set.rb', line 158 def extract_background_size_from(value) size = value.slice!(CssParser::RE_BACKGROUND_SIZE) size.sub(/^\s*\/\s*/, '') if size end |
#get_value(property) ⇒ Object Also known as: []
Get the value of a property
26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/css_parser/rule_set.rb', line 26 def get_value(property) return '' unless property and not property.empty? property = property.downcase.strip properties = @declarations.inject('') do |val, (key, data)| #puts "COMPARING #{key} #{key.inspect} against #{property} #{property.inspect}" importance = data[:is_important] ? ' !important' : '' val << "#{data[:value]}#{importance}; " if key.downcase.strip == property val end return properties ? properties.strip : '' end |
#remove_declaration!(property) ⇒ Object
Remove CSS declaration from the current RuleSet.
rule_set.remove_declaration!('color')
72 73 74 |
# File 'lib/css_parser/rule_set.rb', line 72 def remove_declaration!(property) @declarations.delete(property) end |
#to_s ⇒ Object
Return the CSS rule set as a string.
118 119 120 121 |
# File 'lib/css_parser/rule_set.rb', line 118 def to_s decs = declarations_to_s "#{@selectors.join(',')} { #{decs} }" end |