2
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2025-08-20 18:52:44 +08:00

FIX: Prioritize !important CSS in emails (#32061)

7d587937 introduced css property deduplication in emails to workaround
bugs in some email clients. However, this didn't account for
admin-supplied customizations which were overriding core rules using
`!important`. This commit ensures that the deduplicator will always
prioritise `!important` rules, just like a browser.
This commit is contained in:
David Taylor 2025-03-28 16:24:03 +00:00 committed by GitHub
parent 12dffc5f7d
commit 3f353a726b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 15 additions and 1 deletions

View file

@ -381,7 +381,11 @@ module Email
.split(";")
.select(&:present?)
.map { _1.split(":", 2).map(&:strip) }
.each { |k, v| styles[k] = v if k.present? && v.present? }
.each do |k, v|
next if k.blank? || v.blank?
next if styles[k]&.end_with?("!important") && !v.end_with?("!important")
styles[k] = v
end
styles.map { |k, v| "#{k}:#{v}" }.join(";")
end

View file

@ -177,6 +177,7 @@ RSpec.describe Email::Styles do
styled = Nokogiri::HTML5.fragment(styled)
expect(styled.at("test")["style"]).to eq("color:red")
end
it "handles whitespace correctly" do
frag =
"<test style=' color : green ; ; ; color : red; background:white; background:yellow '>hello</test>"
@ -185,6 +186,15 @@ RSpec.describe Email::Styles do
styled = Nokogiri::HTML5.fragment(styled)
expect(styled.at("test")["style"]).to eq("color:red;background:yellow")
end
it "respects !important" do
frag = "<test style='color:yellow !important;color:green !important;color:red'>hello</test>"
styler = Email::Styles.new(frag)
styled = styler.to_html
styled = Nokogiri::HTML5.fragment(styled)
expect(styled.at("test")["style"]).to eq("color:green !important")
end
end
describe "dark mode emails" do