Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for the !important attribute #843

Merged
merged 4 commits into from
Nov 26, 2024
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
Binary file modified crates/resvg/tests/tests/structure/style/important.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 4 additions & 2 deletions crates/usvg/src/parser/svgtree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,16 @@ pub struct Attribute<'input> {
pub name: AId,
/// Attribute's value.
pub value: roxmltree::StringStorage<'input>,
/// Attribute's importance
pub important: bool,
}

impl std::fmt::Debug for Attribute<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"Attribute {{ name: {:?}, value: {} }}",
self.name, self.value
"Attribute {{ name: {:?}, value: {}, important: {} }}",
self.name, self.value, self.important
)
}
}
Expand Down
106 changes: 75 additions & 31 deletions crates/usvg/src/parser/svgtree/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,17 @@ impl<'input> Document<'input> {
new_child_id
}

fn append_attribute(&mut self, name: AId, value: roxmltree::StringStorage<'input>) {
self.attrs.push(Attribute { name, value });
fn append_attribute(
&mut self,
name: AId,
value: roxmltree::StringStorage<'input>,
important: bool,
) {
self.attrs.push(Attribute {
name,
value,
important,
});
}
}

Expand Down Expand Up @@ -251,10 +260,17 @@ pub(crate) fn parse_svg_element<'input>(
continue;
}

append_attribute(parent_id, tag_name, aid, attr.value_storage().clone(), doc);
append_attribute(
parent_id,
tag_name,
aid,
attr.value_storage().clone(),
false,
doc,
);
}

let mut insert_attribute = |aid, value: &str| {
let mut insert_attribute = |aid, value: &str, important: bool| {
// Check that attribute already exists.
let idx = doc.attrs[attrs_start_idx..]
.iter_mut()
Expand All @@ -266,15 +282,37 @@ pub(crate) fn parse_svg_element<'input>(
tag_name,
aid,
roxmltree::StringStorage::new_owned(value),
important,
doc,
);

// Check that attribute was actually added, because it could be skipped.
if added {
if let Some(idx) = idx {
// Swap the last attribute with an existing one.
let last_idx = doc.attrs.len() - 1;
doc.attrs.swap(attrs_start_idx + idx, last_idx);
let existing_idx = attrs_start_idx + idx;

// See https://developer.mozilla.org/en-US/docs/Web/CSS/important
// When a declaration is important, the order of precedence is reversed.
// Declarations marked as important in the user-agent style sheets override
// all important declarations in the user style sheets. Similarly, all important
// declarations in the user style sheets override all important declarations in the
// author's style sheets. Finally, all important declarations take precedence over
// all animations.
//
// Which means:
// 1) Existing is not important, new is not important -> swap
// 2) Existing is important, new is not important -> don't swap
// 3) Existing is not important, new is important -> swap
// 4) Existing is important, new is important -> don't swap (since the order
// is reversed, so existing important attributes take precedence over new
// important attributes)
let has_precedence = !doc.attrs[existing_idx].important;

if has_precedence {
doc.attrs.swap(existing_idx, last_idx);
}

// Remove last.
doc.attrs.pop();
}
Expand All @@ -283,41 +321,44 @@ pub(crate) fn parse_svg_element<'input>(

let mut write_declaration = |declaration: &Declaration| {
// TODO: perform XML attribute normalization
let imp = declaration.important;
let val = declaration.value;

if declaration.name == "marker" {
insert_attribute(AId::MarkerStart, declaration.value);
insert_attribute(AId::MarkerMid, declaration.value);
insert_attribute(AId::MarkerEnd, declaration.value);
insert_attribute(AId::MarkerStart, val, imp);
insert_attribute(AId::MarkerMid, val, imp);
insert_attribute(AId::MarkerEnd, val, imp);
} else if declaration.name == "font" {
if let Ok(shorthand) = FontShorthand::from_str(declaration.value) {
if let Ok(shorthand) = FontShorthand::from_str(val) {
// First we need to reset all values to their default.
insert_attribute(AId::FontStyle, "normal");
insert_attribute(AId::FontVariant, "normal");
insert_attribute(AId::FontWeight, "normal");
insert_attribute(AId::FontStretch, "normal");
insert_attribute(AId::LineHeight, "normal");
insert_attribute(AId::FontSizeAdjust, "none");
insert_attribute(AId::FontKerning, "auto");
insert_attribute(AId::FontVariantCaps, "normal");
insert_attribute(AId::FontVariantLigatures, "normal");
insert_attribute(AId::FontVariantNumeric, "normal");
insert_attribute(AId::FontVariantEastAsian, "normal");
insert_attribute(AId::FontVariantPosition, "normal");
insert_attribute(AId::FontStyle, "normal", imp);
insert_attribute(AId::FontVariant, "normal", imp);
insert_attribute(AId::FontWeight, "normal", imp);
insert_attribute(AId::FontStretch, "normal", imp);
insert_attribute(AId::LineHeight, "normal", imp);
insert_attribute(AId::FontSizeAdjust, "none", imp);
insert_attribute(AId::FontKerning, "auto", imp);
insert_attribute(AId::FontVariantCaps, "normal", imp);
insert_attribute(AId::FontVariantLigatures, "normal", imp);
insert_attribute(AId::FontVariantNumeric, "normal", imp);
insert_attribute(AId::FontVariantEastAsian, "normal", imp);
insert_attribute(AId::FontVariantPosition, "normal", imp);

// Then, we set the properties that have been declared.
shorthand
.font_stretch
.map(|s| insert_attribute(AId::FontStretch, s));
.map(|s| insert_attribute(AId::FontStretch, s, imp));
shorthand
.font_weight
.map(|s| insert_attribute(AId::FontWeight, s));
.map(|s| insert_attribute(AId::FontWeight, s, imp));
shorthand
.font_variant
.map(|s| insert_attribute(AId::FontVariant, s));
.map(|s| insert_attribute(AId::FontVariant, s, imp));
shorthand
.font_style
.map(|s| insert_attribute(AId::FontStyle, s));
insert_attribute(AId::FontSize, shorthand.font_size);
insert_attribute(AId::FontFamily, shorthand.font_family);
.map(|s| insert_attribute(AId::FontStyle, s, imp));
insert_attribute(AId::FontSize, shorthand.font_size, imp);
insert_attribute(AId::FontFamily, shorthand.font_family, imp);
} else {
log::warn!(
"Failed to parse {} value: '{}'",
Expand All @@ -328,7 +369,7 @@ pub(crate) fn parse_svg_element<'input>(
} else if let Some(aid) = AId::from_str(declaration.name) {
// Parse only the presentation attributes.
if aid.is_presentation() {
insert_attribute(aid, declaration.value);
insert_attribute(aid, val, imp);
}
}
};
Expand Down Expand Up @@ -369,6 +410,7 @@ fn append_attribute<'input>(
tag_name: EId,
aid: AId,
value: roxmltree::StringStorage<'input>,
important: bool,
doc: &mut Document<'input>,
) -> bool {
match aid {
Expand All @@ -389,7 +431,7 @@ fn append_attribute<'input>(
return resolve_inherit(parent_id, aid, doc);
}

doc.append_attribute(aid, value);
doc.append_attribute(aid, value, important);
true
}

Expand All @@ -412,6 +454,7 @@ fn resolve_inherit(parent_id: NodeId, aid: AId, doc: &mut Document) -> bool {
doc.attrs.push(Attribute {
name: aid,
value: attr.value,
important: attr.important,
});

return true;
Expand All @@ -429,6 +472,7 @@ fn resolve_inherit(parent_id: NodeId, aid: AId, doc: &mut Document) -> bool {
doc.attrs.push(Attribute {
name: aid,
value: attr.value,
important: attr.important,
});

return true;
Expand Down Expand Up @@ -483,7 +527,7 @@ fn resolve_inherit(parent_id: NodeId, aid: AId, doc: &mut Document) -> bool {
_ => return false,
};

doc.append_attribute(aid, roxmltree::StringStorage::Borrowed(value));
doc.append_attribute(aid, roxmltree::StringStorage::Borrowed(value), false);
true
}

Expand Down
77 changes: 77 additions & 0 deletions crates/usvg/tests/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ fn stylesheet_injection() {
<rect id='rect2' x='120' y='20' width='60' height='60' fill='green'/>
<rect id='rect3' x='20' y='120' width='60' height='60' style='fill: green'/>
<rect id='rect4' x='120' y='120' width='60' height='60'/>
<rect id='rect5' x='70' y='70' width='60' height='60' style='fill: green !important'/>
</svg>
";

Expand Down Expand Up @@ -73,6 +74,82 @@ fn stylesheet_injection() {
third.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(0, 128, 0))
);

let usvg::Node::Path(ref third) = &tree.root().children()[3] else {
unreachable!()
};
assert_eq!(
third.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(0, 128, 0))
);
}

#[test]
fn stylesheet_injection_with_important() {
let svg = "<svg id='svg1' viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'>
<style>
#rect4 {
fill: green
}
</style>
<rect id='rect1' x='20' y='20' width='60' height='60'/>
<rect id='rect2' x='120' y='20' width='60' height='60' fill='green'/>
<rect id='rect3' x='20' y='120' width='60' height='60' style='fill: green'/>
<rect id='rect4' x='120' y='120' width='60' height='60'/>
<rect id='rect5' x='70' y='70' width='60' height='60' style='fill: green !important'/>
</svg>
";

let stylesheet = "rect { fill: red !important }".to_string();

let options = usvg::Options {
style_sheet: Some(stylesheet),
..usvg::Options::default()
};

let tree = usvg::Tree::from_str(&svg, &options).unwrap();

let usvg::Node::Path(ref first) = &tree.root().children()[0] else {
unreachable!()
};

// All rects should be overriden, since we use `important`.
assert_eq!(
first.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);

let usvg::Node::Path(ref second) = &tree.root().children()[1] else {
unreachable!()
};
assert_eq!(
second.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);

let usvg::Node::Path(ref third) = &tree.root().children()[2] else {
unreachable!()
};
assert_eq!(
third.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);

let usvg::Node::Path(ref third) = &tree.root().children()[3] else {
unreachable!()
};
assert_eq!(
third.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);

let usvg::Node::Path(ref third) = &tree.root().children()[4] else {
unreachable!()
};
assert_eq!(
third.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);
}

#[test]
Expand Down
Loading