Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Unreleased

* Prefer `!important` rules over non-`!important` rules in the same ruleset
* Minor performance improvements

### Version v1.21.0
Expand Down
9 changes: 6 additions & 3 deletions lib/css_parser/rule_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,20 @@ def initialize(declarations = {})
# puts declarations['margin']
# => #<CssParser::RuleSet::Declarations::Value:0x00000000030c1838 @important=true, @order=2, @value="0px auto">
#
# If the property already exists its value will be over-written.
# If the property already exists its value will be over-written unless it was !important and the new value
# is not !important.
# If the value is empty - property will be deleted
def []=(property, value)
property = normalize_property(property)
currently_important = declarations[property]&.important

if value.is_a?(Value)
if value.is_a?(Value) && (!currently_important || value.important)
declarations[property] = value
elsif value.to_s.strip.empty?
delete property
else
declarations[property] = Value.new(value)
value = Value.new(value)
declarations[property] = value if !currently_important || value.important
end
rescue ArgumentError => e
raise e.exception, "#{property} #{e.message}"
Expand Down
12 changes: 12 additions & 0 deletions test/test_merging.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,18 @@ def test_merging_important
assert_equal 'black !important;', merged['color']
end

def test_prioritising_important_over_non_important_in_the_same_block
rs1 = RuleSet.new(block: 'color: black !important; color: red;')
merged = CssParser.merge(rs1)
assert_equal 'black !important;', merged['color']
end

def test_prioritising_two_important_declarations_in_the_same_block
rs1 = RuleSet.new(block: 'color: black !important; color: red !important;')
merged = CssParser.merge(rs1)
assert_equal 'red !important;', merged['color']
end

def test_merging_multiple_important
rs1 = RuleSet.new(block: 'color: black !important;', specificity: 1000)
rs2 = RuleSet.new(block: 'color: red !important;', specificity: 1)
Expand Down
Loading