Skip to content

Commit

Permalink
Merge pull request #141 from jdelStrother/media-spacers
Browse files Browse the repository at this point in the history
Fix parsing space-less media-features
  • Loading branch information
grosser committed Sep 1, 2023
2 parents 71f1603 + 22750be commit d6368ef
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,8 @@

### Unreleased

* Fix parsing space-less media query features like `@media(width:123px)` [#141](https://github.com/premailer/css_parser/pull/141)

### Version v1.15.0

* Fix parsing background shorthands in ruby 3.2 [#140](https://github.com/premailer/css_parser/pull/140)
Expand Down
13 changes: 11 additions & 2 deletions lib/css_parser/parser.rb
Expand Up @@ -329,7 +329,7 @@ def parse_block_into_rule_sets!(block, options = {}) # :nodoc:
rule_start = nil
offset = nil

block.scan(/\s+|\\{2,}|\\?[{}\s"]|.[^\s"{}\\]*/) do |token|
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 options[:capture_offsets]

Expand Down Expand Up @@ -391,7 +391,16 @@ def parse_block_into_rule_sets!(block, options = {}) # :nodoc:
current_media_query = String.new
else
token.strip!
current_media_query << token << ' '
# 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
Expand Down
19 changes: 19 additions & 0 deletions test/test_css_parser_media_types.rb
Expand Up @@ -46,6 +46,25 @@ def test_finding_by_media_type
assert_equal 'color: blue;', @cp.find_by_selector('body', 'print and resolution > 90dpi'.to_sym).join(' ')
end

def test_with_parenthesized_media_features
@cp.add_block!(<<-CSS)
body { color: black }
@media(prefers-color-scheme: dark) {
body { color: white }
}
@media(min-width: 500px) {
body { color: blue }
}
@media screen and (width > 500px) {
body { color: red }
}
CSS
assert_equal [:all, :'(prefers-color-scheme: dark)', :'(min-width: 500px)', :'screen and (width > 500px)'], @cp.rules_by_media_query.keys
assert_equal 'color: white;', @cp.find_by_selector('body', :'(prefers-color-scheme: dark)').join(' ')
assert_equal 'color: blue;', @cp.find_by_selector('body', :'(min-width: 500px)').join(' ')
assert_equal 'color: red;', @cp.find_by_selector('body', :'screen and (width > 500px)').join(' ')
end

def test_finding_by_multiple_media_types
@cp.add_block!(<<-CSS)
@media print {
Expand Down

0 comments on commit d6368ef

Please sign in to comment.