Class: CssParser::Parser
- Inherits:
-
Object
- Object
- CssParser::Parser
- Defined in:
- lib/css_parser/parser.rb
Overview
Parser class
All CSS is converted to UTF-8.
When calling Parser#new there are some configuaration options:
absolute_paths
-
Convert relative paths to absolute paths (
href
,src
andurl('')
. Boolean, default isfalse
. import
-
Follow
@import
rules. Boolean, default istrue
. io_exceptions
-
Throw an exception if a link can not be found. Boolean, default is
true
.
Constant Summary collapse
- USER_AGENT =
"Ruby CSS Parser/#{CssParser::VERSION} (https://github.com/premailer/css_parser)"
- STRIP_CSS_COMMENTS_RX =
%r{/\*.*?\*/}m.freeze
- STRIP_HTML_COMMENTS_RX =
/<!--|-->/m.freeze
- RE_AT_IMPORT_RULE =
Initial parsing
/@import\s*(?:url\s*)?(?:\()?(?:\s*)["']?([^'"\s)]*)["']?\)?([\w\s,^\]()]*)\)?[;\n]?/.freeze
- MAX_REDIRECTS =
3
Class Attribute Summary collapse
-
.folded_declaration_cache ⇒ Object
readonly
Returns the value of attribute folded_declaration_cache.
Instance Attribute Summary collapse
-
#loaded_uris ⇒ Object
readonly
Array of CSS files that have been loaded.
Instance Method Summary collapse
-
#add_block!(block, options = {}) ⇒ Object
Add a raw block of CSS.
-
#add_rule!(selectors, declarations, media_types = :all) ⇒ Object
Add a CSS rule by setting the
selectors
,declarations
andmedia_types
. -
#add_rule_set!(ruleset, media_types = :all) ⇒ Object
Add a CssParser RuleSet object.
-
#add_rule_with_offsets!(selectors, declarations, filename, offset, media_types = :all) ⇒ Object
Add a CSS rule by setting the
selectors
,declarations
,filename
,offset
andmedia_types
. -
#compact! ⇒ Object
Merge declarations with the same selector.
-
#each_rule_set(media_types = :all) ⇒ Object
Iterate through RuleSet objects.
-
#each_selector(all_media_types = :all, options = {}) ⇒ Object
Iterate through CSS selectors.
-
#find_by_selector(selector, media_types = :all) ⇒ Object
(also: #[])
Get declarations by selector.
-
#find_rule_sets(selectors, media_types = :all) ⇒ Object
Finds the rule sets that match the given selectors.
-
#initialize(options = {}) ⇒ Parser
constructor
A new instance of Parser.
-
#load_file!(file_name, options = {}, deprecated = nil) ⇒ Object
Load a local CSS file.
-
#load_string!(src, options = {}, deprecated = nil) ⇒ Object
Load a local CSS string.
-
#load_uri!(uri, options = {}, deprecated = nil) ⇒ Object
Load a remote CSS file.
-
#parse_block_into_rule_sets!(block, options = {}) ⇒ Object
:nodoc:.
-
#remove_rule_set!(ruleset, media_types = :all) ⇒ Object
Remove a CssParser RuleSet object.
-
#rules_by_media_query ⇒ Object
A hash of { :media_query => rule_sets }.
-
#to_h(which_media = :all) ⇒ Object
Output all CSS rules as a Hash.
-
#to_s(which_media = :all) ⇒ Object
Output all CSS rules as a single stylesheet.
Constructor Details
#initialize(options = {}) ⇒ Parser
Returns a new instance of Parser.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/css_parser/parser.rb', line 37 def initialize( = {}) @options = { absolute_paths: false, import: true, io_exceptions: true, rule_set_exceptions: true, capture_offsets: false, user_agent: USER_AGENT }.merge() # array of RuleSets @rules = [] @redirect_count = nil @loaded_uris = [] # unprocessed blocks of CSS @blocks = [] reset! end |
Class Attribute Details
.folded_declaration_cache ⇒ Object (readonly)
Returns the value of attribute folded_declaration_cache.
35 36 37 |
# File 'lib/css_parser/parser.rb', line 35 def folded_declaration_cache @folded_declaration_cache end |
Instance Attribute Details
#loaded_uris ⇒ Object (readonly)
Array of CSS files that have been loaded.
29 30 31 |
# File 'lib/css_parser/parser.rb', line 29 def loaded_uris @loaded_uris end |
Instance Method Details
#add_block!(block, options = {}) ⇒ Object
Add a raw block of CSS.
In order to follow @import rules you must supply either a :base_dir
or :base_uri
option.
Use the :media_types
option to set the media type(s) for this block. Takes an array of symbols.
Use the :only_media_types
option to selectively follow @import rules. Takes an array of symbols.
Example
css = <<-EOT
body { font-size: 10pt }
p { margin: 0px; }
@media screen, print {
body { line-height: 1.2 }
}
EOT
parser = CssParser::Parser.new
parser.add_block!(css)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/css_parser/parser.rb', line 120 def add_block!(block, = {}) = {base_uri: nil, base_dir: nil, charset: nil, media_types: :all, only_media_types: :all}.merge() [:media_types] = [[:media_types]].flatten.collect { |mt| CssParser.sanitize_media_query(mt) } [:only_media_types] = [[:only_media_types]].flatten.collect { |mt| CssParser.sanitize_media_query(mt) } block = cleanup_block(block, ) if [:base_uri] and @options[:absolute_paths] block = CssParser.convert_uris(block, [:base_uri]) end # Load @imported CSS if @options[:import] block.scan(RE_AT_IMPORT_RULE).each do |import_rule| media_types = [] if (media_string = import_rule[-1]) media_string.split(/,/).each do |t| media_types << CssParser.sanitize_media_query(t) unless t.empty? end else media_types = [:all] end next unless [:only_media_types].include?(:all) or media_types.empty? or !(media_types & [:only_media_types]).empty? import_path = import_rule[0].to_s.gsub(/['"]*/, '').strip = {media_types: media_types} [:capture_offsets] = true if [:capture_offsets] if [:base_uri] import_uri = Addressable::URI.parse([:base_uri].to_s) + Addressable::URI.parse(import_path) [:base_uri] = [:base_uri] load_uri!(import_uri, ) elsif [:base_dir] [:base_dir] = [:base_dir] load_file!(import_path, ) end end end # Remove @import declarations block = ignore_pattern(block, RE_AT_IMPORT_RULE, ) parse_block_into_rule_sets!(block, ) end |
#add_rule!(selectors, declarations, media_types = :all) ⇒ Object
Add a CSS rule by setting the selectors
, declarations
and media_types
.
media_types
can be a symbol or an array of symbols.
170 171 172 173 174 175 |
# File 'lib/css_parser/parser.rb', line 170 def add_rule!(selectors, declarations, media_types = :all) rule_set = RuleSet.new(selectors, declarations) add_rule_set!(rule_set, media_types) rescue ArgumentError => e raise e if @options[:rule_set_exceptions] end |
#add_rule_set!(ruleset, media_types = :all) ⇒ Object
Add a CssParser RuleSet object.
media_types
can be a symbol or an array of symbols.
190 191 192 193 194 195 196 197 |
# File 'lib/css_parser/parser.rb', line 190 def add_rule_set!(ruleset, media_types = :all) raise ArgumentError unless ruleset.is_a?(CssParser::RuleSet) media_types = [media_types] unless media_types.is_a?(Array) media_types = media_types.flat_map { |mt| CssParser.sanitize_media_query(mt) } @rules << {media_types: media_types, rules: ruleset} end |
#add_rule_with_offsets!(selectors, declarations, filename, offset, media_types = :all) ⇒ Object
Add a CSS rule by setting the selectors
, declarations
, filename
, offset
and media_types
.
filename
can be a string or uri pointing to the file or url location. offset
should be Range object representing the start and end byte locations where the rule was found in the file. media_types
can be a symbol or an array of symbols.
182 183 184 185 |
# File 'lib/css_parser/parser.rb', line 182 def add_rule_with_offsets!(selectors, declarations, filename, offset, media_types = :all) rule_set = OffsetAwareRuleSet.new(filename, offset, selectors, declarations) add_rule_set!(rule_set, media_types) end |
#compact! ⇒ Object
Merge declarations with the same selector.
308 309 310 |
# File 'lib/css_parser/parser.rb', line 308 def compact! # :nodoc: [] end |
#each_rule_set(media_types = :all) ⇒ Object
Iterate through RuleSet objects.
media_types
can be a symbol or an array of symbols.
215 216 217 218 219 220 221 222 223 224 |
# File 'lib/css_parser/parser.rb', line 215 def each_rule_set(media_types = :all) # :yields: rule_set, media_types media_types = [:all] if media_types.nil? media_types = [media_types].flatten.collect { |mt| CssParser.sanitize_media_query(mt) } @rules.each do |block| if media_types.include?(:all) or block[:media_types].any? { |mt| media_types.include?(mt) } yield(block[:rules], block[:media_types]) end end end |
#each_selector(all_media_types = :all, options = {}) ⇒ Object
Iterate through CSS selectors.
media_types
can be a symbol or an array of symbols. See RuleSet#each_selector for options
.
251 252 253 254 255 256 257 258 259 |
# File 'lib/css_parser/parser.rb', line 251 def each_selector(all_media_types = :all, = {}) # :yields: selectors, declarations, specificity, media_types return to_enum(__method__, all_media_types, ) unless block_given? each_rule_set(all_media_types) do |rule_set, media_types| rule_set.each_selector() do |selectors, declarations, specificity| yield selectors, declarations, specificity, media_types end end end |
#find_by_selector(selector, media_types = :all) ⇒ Object Also known as: []
Get declarations by selector.
media_types
are optional, and can be a symbol or an array of symbols. The default value is :all
.
Examples
find_by_selector('#content')
=> 'font-size: 13px; line-height: 1.2;'
find_by_selector('#content', [:screen, :handheld])
=> 'font-size: 13px; line-height: 1.2;'
find_by_selector('#content', :print)
=> 'font-size: 11pt; line-height: 1.2;'
Returns an array of declarations.
75 76 77 78 79 80 81 |
# File 'lib/css_parser/parser.rb', line 75 def find_by_selector(selector, media_types = :all) out = [] each_selector(media_types) do |sel, dec, _spec| out << dec if sel.strip == selector.strip end out end |
#find_rule_sets(selectors, media_types = :all) ⇒ Object
Finds the rule sets that match the given selectors
85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/css_parser/parser.rb', line 85 def find_rule_sets(selectors, media_types = :all) rule_sets = [] selectors.each do |selector| selector = selector.gsub(/\s+/, ' ').strip each_rule_set(media_types) do |rule_set, _media_type| if !rule_sets.member?(rule_set) && rule_set.selectors.member?(selector) rule_sets << rule_set end end end rule_sets end |
#load_file!(file_name, options = {}, deprecated = nil) ⇒ Object
Load a local CSS file.
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 |
# File 'lib/css_parser/parser.rb', line 475 def load_file!(file_name, = {}, deprecated = nil) opts = {base_dir: nil, media_types: :all} if .is_a? Hash opts.merge!() else opts[:base_dir] = if .is_a? String opts[:media_types] = deprecated if deprecated end file_name = File.(file_name, opts[:base_dir]) return unless File.readable?(file_name) return unless circular_reference_check(file_name) src = File.read(file_name) opts[:filename] = file_name if opts[:capture_offsets] opts[:base_dir] = File.dirname(file_name) add_block!(src, opts) end |
#load_string!(src, options = {}, deprecated = nil) ⇒ Object
Load a local CSS string.
498 499 500 501 502 503 504 505 506 507 508 509 |
# File 'lib/css_parser/parser.rb', line 498 def load_string!(src, = {}, deprecated = nil) opts = {base_dir: nil, media_types: :all} if .is_a? Hash opts.merge!() else opts[:base_dir] = if .is_a? String opts[:media_types] = deprecated if deprecated end add_block!(src, opts) end |
#load_uri!(uri, options = {}, deprecated = nil) ⇒ Object
Load a remote CSS file.
You can also pass in file://test.css
See add_block! for options.
Deprecated: originally accepted three params: ‘uri`, `base_uri` and `media_types`
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 |
# File 'lib/css_parser/parser.rb', line 447 def load_uri!(uri, = {}, deprecated = nil) uri = Addressable::URI.parse(uri) unless uri.respond_to? :scheme opts = {base_uri: nil, media_types: :all} if .is_a? Hash opts.merge!() else opts[:base_uri] = if .is_a? String opts[:media_types] = deprecated if deprecated end if uri.scheme == 'file' or uri.scheme.nil? uri.path = File.(uri.path) uri.scheme = 'file' end opts[:base_uri] = uri if opts[:base_uri].nil? # pass on the uri if we are capturing file offsets opts[:filename] = uri.to_s if opts[:capture_offsets] src, = read_remote_file(uri) # skip charset add_block!(src, opts) if src end |
#parse_block_into_rule_sets!(block, options = {}) ⇒ Object
:nodoc:
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 |
# File 'lib/css_parser/parser.rb', line 312 def parse_block_into_rule_sets!(block, = {}) # :nodoc: current_media_queries = [:all] if [:media_types] current_media_queries = [:media_types].flatten.collect { |mt| CssParser.sanitize_media_query(mt) } end in_declarations = 0 block_depth = 0 in_charset = false # @charset is ignored for now in_string = false in_at_media_rule = false in_media_block = false current_selectors = String.new current_media_query = String.new current_declarations = String.new # once we are in a rule, we will use this to store where we started if we are capturing offsets rule_start = nil offset = nil block.scan(/\s+|\\{2,}|\\?[{}\s"]|[()]|.[^\s"{}()\\]*/) do |token| # save the regex offset so that we know where in the file we are offset = Regexp.last_match.offset(0) if [:capture_offsets] if token.start_with?('"') # found un-escaped double quote in_string = !in_string end if in_declarations > 0 # too deep, malformed declaration block if in_declarations > 1 in_declarations -= 1 if token.include?('}') next end if !in_string && token.include?('{') in_declarations += 1 next end current_declarations << token if !in_string && token.include?('}') current_declarations.gsub!(/\}\s*$/, '') in_declarations -= 1 current_declarations.strip! unless current_declarations.empty? if [:capture_offsets] add_rule_with_offsets!(current_selectors, current_declarations, [:filename], (rule_start..offset.last), current_media_queries) else add_rule!(current_selectors, current_declarations, current_media_queries) end end current_selectors = String.new current_declarations = String.new # restart our search for selectors and declarations rule_start = nil if [:capture_offsets] end elsif token =~ /@media/i # found '@media', reset current media_types in_at_media_rule = true current_media_queries = [] elsif in_at_media_rule if token.include?('{') block_depth += 1 in_at_media_rule = false in_media_block = true current_media_queries << CssParser.sanitize_media_query(current_media_query) current_media_query = String.new elsif token.include?(',') # new media query begins token.tr!(',', ' ') token.strip! current_media_query << token << ' ' current_media_queries << CssParser.sanitize_media_query(current_media_query) current_media_query = String.new else token.strip! # special-case the ( and ) tokens to remove inner-whitespace # (eg we'd prefer '(width: 500px)' to '( width: 500px )' ) case token when '(' current_media_query << token when ')' current_media_query.sub!(/ ?$/, token) else current_media_query << token << ' ' end end elsif in_charset or token =~ /@charset/i # iterate until we are out of the charset declaration in_charset = !token.include?(';') elsif !in_string && token.include?('}') block_depth -= 1 # reset the current media query scope if in_media_block current_media_queries = [:all] in_media_block = false end elsif !in_string && token.include?('{') current_selectors.strip! in_declarations += 1 else # if we are in a selector, add the token to the current selectors current_selectors << token # mark this as the beginning of the selector unless we have already marked it rule_start = offset.first if [:capture_offsets] && rule_start.nil? && token =~ /^[^\s]+$/ end end # check for unclosed braces return unless in_declarations > 0 unless [:capture_offsets] return add_rule!(current_selectors, current_declarations, current_media_queries) end add_rule_with_offsets!(current_selectors, current_declarations, [:filename], (rule_start..offset.last), current_media_queries) end |
#remove_rule_set!(ruleset, media_types = :all) ⇒ Object
Remove a CssParser RuleSet object.
media_types
can be a symbol or an array of symbols.
202 203 204 205 206 207 208 209 210 |
# File 'lib/css_parser/parser.rb', line 202 def remove_rule_set!(ruleset, media_types = :all) raise ArgumentError unless ruleset.is_a?(CssParser::RuleSet) media_types = [media_types].flatten.collect { |mt| CssParser.sanitize_media_query(mt) } @rules.reject! do |rule| rule[:media_types] == media_types && rule[:rules].to_s == ruleset.to_s end end |
#rules_by_media_query ⇒ Object
A hash of { :media_query => rule_sets }
293 294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/css_parser/parser.rb', line 293 def rules_by_media_query rules_by_media = {} @rules.each do |block| block[:media_types].each do |mt| unless rules_by_media.key?(mt) rules_by_media[mt] = [] end rules_by_media[mt] << block[:rules] end end rules_by_media end |
#to_h(which_media = :all) ⇒ Object
Output all CSS rules as a Hash
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# File 'lib/css_parser/parser.rb', line 227 def to_h(which_media = :all) out = {} styles_by_media_types = {} each_selector(which_media) do |selectors, declarations, _specificity, media_types| media_types.each do |media_type| styles_by_media_types[media_type] ||= [] styles_by_media_types[media_type] << [selectors, declarations] end end styles_by_media_types.each_pair do |media_type, media_styles| ms = {} media_styles.each do |media_style| ms = css_node_to_h(ms, media_style[0], media_style[1]) end out[media_type.to_s] = ms end out end |
#to_s(which_media = :all) ⇒ Object
Output all CSS rules as a single stylesheet.
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
# File 'lib/css_parser/parser.rb', line 262 def to_s(which_media = :all) out = [] styles_by_media_types = {} each_selector(which_media) do |selectors, declarations, _specificity, media_types| media_types.each do |media_type| styles_by_media_types[media_type] ||= [] styles_by_media_types[media_type] << [selectors, declarations] end end styles_by_media_types.each_pair do |media_type, media_styles| media_block = (media_type != :all) out << "@media #{media_type} {" if media_block media_styles.each do |media_style| if media_block out.push(" #{media_style[0]} {\n #{media_style[1]}\n }") else out.push("#{media_style[0]} {\n#{media_style[1]}\n}") end end out << '}' if media_block end out << '' out.join("\n") end |