Resolve SVG font-size percentages against the parent font size

Found while testing crates/svg/src/lib.rs:624

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NetterSilver
2026-10-19 20:22:36 +02:00
co-authored by Claude Haiku 5.5
parent ef74d82902
commit 81548edff9
2 changed files with 20 additions and 1 deletions
+5 -1
View File
@@ -621,7 +621,11 @@ impl<'a, 'i> Parser<'a, 'i> {
if let Some(c) = d.get("color").and_then(|v| parse_color(v)) {
st.color = c;
}
if let Some(v) = d.get("font-size").and_then(|v| self.length(v, 'o', st.font_size)) {
let font_size = d.get("font-size").and_then(|v| match v.trim().strip_suffix('%') {
Some(p) => p.trim().parse::<f64>().ok().map(|p| p / 100.0 * st.font_size),
None => self.length(v, 'o', st.font_size),
});
if let Some(v) = font_size.filter(|v| v.is_finite()) {
st.font_size = v;
}
if let Some(p) = d.get("fill").and_then(|v| self.paint_ref(v)) {
+15
View File
@@ -277,3 +277,18 @@ fn a_symbol_used_a_thousand_times_still_imports() {
let doc = parse(svg.as_bytes()).unwrap();
assert_eq!(depth_and_shapes(&doc.root).1, 3000);
}
#[test]
fn font_size_percentage_resolves_against_the_parent_font_size() {
for (body, expected) in [
(r#"<g font-size="200%"><rect width="1em" height="1em"/></g>"#, 32.0),
(r#"<g font-size="200%"><rect width="2ex" height="1em"/></g>"#, 32.0),
(r#"<g font-size="200%"><g font-size="200%"><rect width="1em" height="1em"/></g></g>"#, 64.0),
] {
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">{body}</svg>"#);
let d = parse(svg.as_bytes()).unwrap();
let shapes = d.flatten();
assert_eq!(shapes.len(), 1);
assert!(matches!(shapes[0].2.geom, Geom::Rect { w, .. } if w == expected), "{body}: {:?}", shapes[0].2.geom);
}
}