From f2695447c2ba7203d6ae6db3e18e964f57aef49c Mon Sep 17 00:00:00 2001 From: Dmitriy Kovalenko Date: Tue, 13 Oct 2026 07:02:38 -0700 Subject: [PATCH 1/4] fix(usvgr): accept every font-weight number from 1 to 1000 CSS Fonts 4 allows any number from 1 to 1000 for font-weight, and browsers follow it. usvgr accepted only the nine multiples of 100 as text, so font-weight="650" and the runtime text of a number set from code kept the inherited weight. A number outside 1 to 1000 is invalid and keeps the inherited weight, written or set from code, as in a browser. The 650 reference now draws in the bold face, the same as 700. --- .../svgr/tests/tests/text/font-weight/650.png | Bin 1244 -> 3627 bytes crates/usvgr/src/parser/text.rs | 32 ++++++++++-------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/crates/svgr/tests/tests/text/font-weight/650.png b/crates/svgr/tests/tests/text/font-weight/650.png index df2f08deb4b6f0aef4fcb7abb37f2543f7353b50..0a1ef9b0fd8b0ccc29d74a445260bc61c68341d0 100644 GIT binary patch literal 3627 zcmeHK{XY|G8)tb-Bq^fB;pp*_akeL~4I#-(IFy%7T1JSma>x#w^s-*aa*~&5Qb#X` zWedX$tHqR;>BwR;Oc;hGG0fJp=YM!U&rj!v`*VNp>;8Q1`~H6K>-t{TbvroFM_bcK zQ%Oll+xNt=5G5sLoBs|CHH8I(El5|`zxf{XIF(tk$X|TGJ6^0dQRBMlPSoht8r6H_ zshjBlK$;CW0n*Iw{R_}!Mm~`HQp3iZJgO0P=V(u>Ie~||V)@#=+aJnyMqj=*QIh?Y zNW0-V)N^b7LOoVbsbuj>PhU=o1FudQJrdnUUtvkg7rm6Cijz;Zy+6C87KR_PR|p&X}S^H?iawaAow1)`!KjAsBo?20&Q_|NA5o`kNRiI=P8i>*$Tg!08o zn>7`DBk1GtasTqvYk3xA;@DzJ(rUG!bO9KxN~qS6 zojRytgP(dY?PJK1u#5*=u9hB%LdfGwhjG+VeLdFs+b!JW9|fou-eg8SmX98#Fx4Rm z(T>29gBzEoC?+v9V7A_%hs?Gh$u|v!aXm*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olHy`uVBq!ia0y~yVAKI&4rZW;-{LxVAQc|q6XFV_X#x1APtFCJD^n8W z7tA1_U|{dy9}u6AUr^uBKVklY^&9pdIDg^(gZCetR`2}6z`!Em>EaktaqG*-~4uj=cH z6tu7D6>-?Q|K|)oaR_?DW5RfsPIA2pI ze~T%@mF4;(Cr-Vy-B%IyDMVspp&sMeil3252mhts75tDgKk9JBeWSB8i!x7itYF=8 z@{xw^tDJk{4DVk=KUnhgs#?$q5i9L1g16Sr$P z`PIJMm-=*)=9{-BiF%R~#l;q?PTjPlzbRO6tH`U9&tJ(c37)p%M8+{zWwkf*zh3Iz z@w&bscp8u6c7-F(Gi+~`#Q%C&XW*5ZnkdG(egogh#3xQEisDwOo+o)f{ywC(V1m<= zuze1z*J#-~rnw~k5AYJ)loxqE_=IJYU{pm>koIc#rhsWZZ;al(p4!^GX~o2ZiJ@ZGH{BP_pDpK`*OeKV3&?>ZwJ?-W#Y?I{Ov>QQFwIZ_8E1*Gjwxv#u9R zl$Q3L&!=pa@^M2@N1E0lC7CC0ihAd+p5SU`6CrwLv;UlD1>0Z9O9%xhdM|RQ|387< zuGTJ^VP&!NZksaQBhzeLj{Tmd>Mv~=9(<%IcF*HGh) diff --git a/crates/usvgr/src/parser/text.rs b/crates/usvgr/src/parser/text.rs index c3470dbdd..3875ddfb7 100644 --- a/crates/usvgr/src/parser/text.rs +++ b/crates/usvgr/src/parser/text.rs @@ -2,6 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. +use std::str::FromStr; use std::sync::Arc; use kurbo::{ParamCurve, ParamCurveArclen}; @@ -597,26 +598,14 @@ fn resolve_font_weight(node: SvgNode) -> u16 { let mut weight = 400; for n in nodes.iter().rev().skip(1) { // skip Root - // A number set from code has no text: read the number (CSS allows 1 to 1000). - // A non-finite one is invalid and, like invalid text, keeps the inherited weight. + // A number set from code has no text: read the number. if let Some(SvgAttributeValueRef::Float(number, _)) = n.attribute_value(AId::FontWeight) { - if number.is_finite() { - weight = number.round().clamp(1.0, 1000.0) as usize; - } + weight = font_weight_number(number).unwrap_or(weight); continue; } weight = match n.attribute(AId::FontWeight).unwrap_or("") { "normal" => 400, "bold" => 700, - "100" => 100, - "200" => 200, - "300" => 300, - "400" => 400, - "500" => 500, - "600" => 600, - "700" => 700, - "800" => 800, - "900" => 900, "bolder" => { // By the CSS2 spec the default value should be 400 // so `bolder` will result in 500. @@ -637,13 +626,26 @@ fn resolve_font_weight(node: SvgNode) -> u16 { bound(100, weight.saturating_sub(step), 900) } - _ => weight, + // Any number, not only the multiples of 100: variable fonts have every weight. + text => svgrtypes::Number::from_str(text) + .ok() + .and_then(|number| font_weight_number(number.0 as f32)) + .unwrap_or(weight), }; } weight as u16 } +/// The weight of a `font-weight` number, the same whether it is written in the SVG or set +/// from code. CSS Fonts 4 allows any number from 1 to 1000, as browsers do; one outside, or +/// not finite, is invalid and keeps the inherited weight, like invalid text. +fn font_weight_number(number: f32) -> Option { + (1.0..=1000.0) + .contains(&number) + .then(|| number.round() as usize) +} + /// Resolves text's character positions. /// /// This includes: x, y, dx, dy. From 2e8ec25c7edbc84aa2ca5d99bdaed8aa9da18a13 Mon Sep 17 00:00:00 2001 From: Dmitriy Kovalenko Date: Tue, 13 Oct 2026 07:02:38 -0700 Subject: [PATCH 2/4] fix(usvgr): read feConvolveMatrix order and transform-origin set from code --- crates/usvgr/src/parser/filter.rs | 9 +++++---- crates/usvgr/src/parser/svgtree/mod.rs | 14 ++++++++++++-- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/usvgr/src/parser/filter.rs b/crates/usvgr/src/parser/filter.rs index 879741493..08f07599f 100644 --- a/crates/usvgr/src/parser/filter.rs +++ b/crates/usvgr/src/parser/filter.rs @@ -664,10 +664,11 @@ fn convert_convolve_matrix(fe: SvgNode, primitives: &[Primitive]) -> Option(AId::Order) { - let mut s = svgrtypes::NumberListParser::from(value); - let x = s.next().and_then(|a| a.ok()).map(|n| n as i32).unwrap_or(3); - let y = s.next().and_then(|a| a.ok()).map(|n| n as i32).unwrap_or(x); + // A list, so that a number set from code, which has no text, is read too. + if let Some(value) = fe.attribute::>(AId::Order) { + let mut s = value.into_iter(); + let x = s.next().map(|n| n as i32).unwrap_or(3); + let y = s.next().map(|n| n as i32).unwrap_or(x); if x > 0 && y > 0 { order_x = x as u32; order_y = y as u32; diff --git a/crates/usvgr/src/parser/svgtree/mod.rs b/crates/usvgr/src/parser/svgtree/mod.rs index 55d58876e..79bbe03a2 100644 --- a/crates/usvgr/src/parser/svgtree/mod.rs +++ b/crates/usvgr/src/parser/svgtree/mod.rs @@ -1394,8 +1394,18 @@ impl<'a, 'input: 'a> FromValue<'a, 'input> for MaybeTransform { } impl<'a, 'input: 'a> FromValue<'a, 'input> for svgrtypes::TransformOrigin { - fn parse(_: SvgNode, _: AId, value: SvgAttributeValueRef<'a>) -> Option { - Self::from_str(value.as_str()?).ok() + fn parse(node: SvgNode, aid: AId, value: SvgAttributeValueRef<'a>) -> Option { + match value { + // A single number or length is the horizontal offset and the vertical one is the + // center, as in the text form. One set from code or parsed at compile time has no + // text to parse. + SvgAttributeValueRef::Float(..) | SvgAttributeValueRef::Length(_) => Some(Self::new( + svgrtypes::Length::parse(node, aid, value)?, + svgrtypes::Length::new(50.0, LengthUnit::Percent), + svgrtypes::Length::new(0.0, LengthUnit::Px), + )), + _ => Self::from_str(value.as_str()?).ok(), + } } } From 638e49997f235687141c825ebc53634532ad2268 Mon Sep 17 00:00:00 2001 From: Dmitriy Kovalenko Date: Tue, 13 Oct 2026 07:02:38 -0700 Subject: [PATCH 3/4] test(usvgr): render every number and length attribute the same from text, compile time and code For each attribute usvgr reads that accepts a number or a length, the value written in the SVG must have an effect, and the same value parsed at compile time or set from code must render the same tree. --- crates/usvgr/tests/parser.rs | 407 +++++++++++++++++++++++++++++++++++ 1 file changed, 407 insertions(+) diff --git a/crates/usvgr/tests/parser.rs b/crates/usvgr/tests/parser.rs index 30c14f9cd..f95831ea5 100644 --- a/crates/usvgr/tests/parser.rs +++ b/crates/usvgr/tests/parser.rs @@ -996,4 +996,411 @@ mod numbers_set_from_code { )) }); } + + /// Writes the tree twice: with text kept, and with text converted to paths, so that both + /// the resolved attributes and their effect on the layout are compared. + fn written_with_layout(doc: &NestedSvgDocument) -> String { + let mut fontdb = usvgr::fontdb::Database::new(); + for font in [ + &include_bytes!("../../svgr/tests/fonts/NotoSans-Regular.ttf")[..], + &include_bytes!("../../svgr/tests/fonts/NotoSans-Bold.ttf")[..], + &include_bytes!("../../svgr/tests/fonts/NotoSans-Light.ttf")[..], + &include_bytes!("../../svgr/tests/fonts/RobotoFlex.subset.ttf")[..], + ] { + fontdb.load_font_data(font.to_vec()); + } + let tree = + usvgr::Tree::from_nested_svgtree(doc, &usvgr::Options::default(), &fontdb).unwrap(); + let mut out = tree.to_string(&usvgr::WriteOptions { + preserve_text: true, + ..Default::default() + }); + out.push_str(&tree.to_string(&usvgr::WriteOptions::default())); + out + } + + /// Builds the document of `template`, an SVG in which `?` marks the element under test. + /// That element gets `attr` instead of the template's value of it, or none for `None`. + fn from_template( + template: &str, + attr: Option<(AId, SvgAttributeValue<'static>)>, + ) -> NestedSvgDocument<'static> { + fn convert( + node: usvgr::roxmltree::Node, + attr: &Option<(AId, SvgAttributeValue<'static>)>, + ) -> Option> { + if node.is_text() { + let content = node.text()?; + return Some(NestedNodeData { + kind: NestedNodeKind::Text(StringStorage::Owned(content.into())), + attrs: Box::new([]), + children: vec![], + static_hash: None, + }); + } + let mut attrs: Attrs = node + .attributes() + .filter_map(|a| Some((AId::from_str(a.name())?, a.value().to_owned().into()))) + .collect(); + if node.has_attribute("under-test") { + if let Some((aid, value)) = attr { + attrs.retain(|(name, _)| name != aid); + attrs.push((*aid, value.clone())); + } + } + let children = node.children().filter_map(|c| convert(c, attr)).collect(); + Some(el(EId::from_str(node.tag_name().name())?, attrs, children)) + } + + let xml = template.replace('?', "under-test=''"); + let xml = usvgr::roxmltree::Document::parse(&xml).unwrap(); + NestedSvgDocument::from_nodes(vec![convert(xml.root_element(), &attr)]) + } + + macro_rules! doc { + ($body:expr) => { + concat!("", $body, "") + }; + } + + macro_rules! filtered { + ($primitive:literal) => { + doc!(concat!( + "", + $primitive, + "" + )) + }; + } + + macro_rules! painted { + ($server:literal) => { + doc!(concat!( + "", + $server, + "" + )) + }; + } + + const RECT: &str = doc!( + "" + ); + const ROTATED: &str = + doc!(""); + const STROKED: &str = doc!(""); + const CIRCLE: &str = doc!(""); + const ELLIPSE: &str = doc!(""); + const LINE: &str = doc!(""); + const LINEAR: &str = painted!(""); + const RADIAL: &str = painted!(""); + const STOP: &str = painted!(""); + const PATTERN: &str = painted!(""); + const NESTED_SVG: &str = doc!( + "" + ); + const USE: &str = doc!(""); + const MARKER: &str = doc!(""); + const MASK: &str = doc!(""); + const LABEL: &str = + doc!("Ab cd"); + const VARIABLE_LABEL: &str = + doc!("Ab cd"); + const KERNED_LABEL: &str = + doc!("AVAT To"); + const TSPAN: &str = doc!( + "Abcd" + ); + const TEXT_PATH: &str = doc!("Ab cd"); + const FILTER_REGION: &str = doc!(""); + const BLUR: &str = filtered!(""); + const OFFSET: &str = filtered!(""); + const FLOOD: &str = filtered!(""); + const DROP_SHADOW: &str = filtered!(""); + const MORPHOLOGY: &str = filtered!(""); + const TURBULENCE: &str = filtered!(""); + const SATURATE: &str = filtered!(""); + const LINEAR_TRANSFER: &str = + filtered!(""); + const GAMMA_TRANSFER: &str = + filtered!(""); + const ARITHMETIC: &str = filtered!(""); + const CONVOLVE: &str = + filtered!(""); + const CONVOLVE_ONE: &str = filtered!(""); + const CONVOLVE_FOUR: &str = filtered!(""); + const DISPLACEMENT: &str = + filtered!(""); + const DIFFUSE: &str = filtered!( + "" + ); + const SPECULAR: &str = filtered!( + "" + ); + const DISTANT_LIGHT: &str = filtered!( + "" + ); + const POINT_LIGHT: &str = filtered!( + "" + ); + const SPOT_LIGHT: &str = filtered!(""); + const SPOT_LIGHT_CONE: &str = + filtered!(""); + + /// Every attribute usvgr reads that accepts a plain number, in an element where it has an + /// effect, with a number different from its default. + const NUMBERS: &[(&str, f32, &str, &str)] = &[ + ("opacity", 0.5, "0.5", RECT), + ("fill-opacity", 0.5, "0.5", RECT), + ("stroke-opacity", 0.5, "0.5", RECT), + ("stroke-width", 7.0, "7", RECT), + ("x", 20.0, "20", RECT), + ("y", 20.0, "20", RECT), + ("width", 30.0, "30", RECT), + ("height", 30.0, "30", RECT), + ("rx", 5.0, "5", RECT), + ("ry", 5.0, "5", RECT), + ("transform-origin", 40.0, "40", ROTATED), + ("stroke-miterlimit", 1.5, "1.5", STROKED), + ("stroke-dashoffset", 3.0, "3", STROKED), + ("stroke-dasharray", 4.0, "4", STROKED), + ("cx", 40.0, "40", CIRCLE), + ("cy", 40.0, "40", CIRCLE), + ("r", 30.0, "30", CIRCLE), + ("rx", 10.0, "10", ELLIPSE), + ("ry", 10.0, "10", ELLIPSE), + ("x1", 20.0, "20", LINE), + ("y1", 20.0, "20", LINE), + ("x2", 70.0, "70", LINE), + ("y2", 70.0, "70", LINE), + ("x1", 0.2, "0.2", LINEAR), + ("y1", 0.2, "0.2", LINEAR), + ("x2", 0.7, "0.7", LINEAR), + ("y2", 0.7, "0.7", LINEAR), + ("cx", 0.3, "0.3", RADIAL), + ("cy", 0.3, "0.3", RADIAL), + ("r", 0.3, "0.3", RADIAL), + ("fx", 0.4, "0.4", RADIAL), + ("fy", 0.4, "0.4", RADIAL), + ("fr", 0.1, "0.1", RADIAL), + ("offset", 0.3, "0.3", STOP), + ("stop-opacity", 0.5, "0.5", STOP), + ("x", 5.0, "5", PATTERN), + ("y", 5.0, "5", PATTERN), + ("width", 25.0, "25", PATTERN), + ("height", 25.0, "25", PATTERN), + ("x", 10.0, "10", NESTED_SVG), + ("y", 10.0, "10", NESTED_SVG), + ("width", 80.0, "80", NESTED_SVG), + ("height", 80.0, "80", NESTED_SVG), + ("x", 10.0, "10", USE), + ("y", 10.0, "10", USE), + ("width", 80.0, "80", USE), + ("height", 80.0, "80", USE), + ("markerWidth", 6.0, "6", MARKER), + ("markerHeight", 6.0, "6", MARKER), + ("refX", 2.0, "2", MARKER), + ("refY", 2.0, "2", MARKER), + ("orient", 45.0, "45", MARKER), + ("x", 20.0, "20", MASK), + ("y", 20.0, "20", MASK), + ("width", 30.0, "30", MASK), + ("height", 30.0, "30", MASK), + ("font-size", 30.0, "30", LABEL), + ("font-weight", 700.0, "700", LABEL), + ("font-weight", 300.0, "300", LABEL), + ("font-weight", 650.0, "650", LABEL), + ("font-weight", 650.0, "650", VARIABLE_LABEL), + ("font-weight", 550.5, "550.5", VARIABLE_LABEL), + ("letter-spacing", 3.0, "3", LABEL), + ("word-spacing", 9.0, "9", LABEL), + ("x", 20.0, "20", LABEL), + ("y", 70.0, "70", LABEL), + ("dx", 4.0, "4", LABEL), + ("dy", 4.0, "4", LABEL), + ("rotate", 20.0, "20", LABEL), + ("textLength", 150.0, "150", LABEL), + ("kerning", 0.0, "0", KERNED_LABEL), + ("baseline-shift", 6.0, "6", TSPAN), + ("startOffset", 20.0, "20", TEXT_PATH), + ("x", 5.0, "5", FILTER_REGION), + ("y", 5.0, "5", FILTER_REGION), + ("width", 40.0, "40", FILTER_REGION), + ("height", 40.0, "40", FILTER_REGION), + ("stdDeviation", 3.0, "3", BLUR), + ("x", 5.0, "5", BLUR), + ("y", 5.0, "5", BLUR), + ("width", 20.0, "20", BLUR), + ("height", 20.0, "20", BLUR), + ("dx", 5.0, "5", OFFSET), + ("dy", 5.0, "5", OFFSET), + ("flood-opacity", 0.5, "0.5", FLOOD), + ("dx", 5.0, "5", DROP_SHADOW), + ("dy", 5.0, "5", DROP_SHADOW), + ("stdDeviation", 3.0, "3", DROP_SHADOW), + ("flood-opacity", 0.5, "0.5", DROP_SHADOW), + ("radius", 2.0, "2", MORPHOLOGY), + ("baseFrequency", 0.2, "0.2", TURBULENCE), + ("numOctaves", 3.0, "3", TURBULENCE), + ("seed", 7.0, "7", TURBULENCE), + ("values", 0.5, "0.5", SATURATE), + ("slope", 0.5, "0.5", LINEAR_TRANSFER), + ("intercept", 0.5, "0.5", LINEAR_TRANSFER), + ("amplitude", 0.5, "0.5", GAMMA_TRANSFER), + ("exponent", 2.0, "2", GAMMA_TRANSFER), + ("offset", 0.5, "0.5", GAMMA_TRANSFER), + ("k1", 0.5, "0.5", ARITHMETIC), + ("k2", 0.5, "0.5", ARITHMETIC), + ("k3", 0.5, "0.5", ARITHMETIC), + ("k4", 0.5, "0.5", ARITHMETIC), + ("divisor", 2.0, "2", CONVOLVE), + ("bias", 0.5, "0.5", CONVOLVE), + ("targetX", 0.0, "0", CONVOLVE), + ("targetY", 0.0, "0", CONVOLVE), + ("kernelMatrix", 2.0, "2", CONVOLVE_ONE), + ("order", 2.0, "2", CONVOLVE_FOUR), + ("scale", 10.0, "10", DISPLACEMENT), + ("surfaceScale", 3.0, "3", DIFFUSE), + ("diffuseConstant", 2.0, "2", DIFFUSE), + ("specularConstant", 2.0, "2", SPECULAR), + ("specularExponent", 5.0, "5", SPECULAR), + ("surfaceScale", 3.0, "3", SPECULAR), + ("azimuth", 45.0, "45", DISTANT_LIGHT), + ("elevation", 45.0, "45", DISTANT_LIGHT), + ("x", 10.0, "10", POINT_LIGHT), + ("y", 10.0, "10", POINT_LIGHT), + ("z", 10.0, "10", POINT_LIGHT), + ("x", 10.0, "10", SPOT_LIGHT), + ("y", 10.0, "10", SPOT_LIGHT), + ("z", 10.0, "10", SPOT_LIGHT), + ("pointsAtX", 10.0, "10", SPOT_LIGHT), + ("pointsAtY", 10.0, "10", SPOT_LIGHT), + ("pointsAtZ", 10.0, "10", SPOT_LIGHT), + ("specularExponent", 5.0, "5", SPOT_LIGHT), + ("limitingConeAngle", 20.0, "20", SPOT_LIGHT_CONE), + ]; + + /// Every attribute usvgr reads that accepts a length with a unit. svgr-macro parses such a + /// written value at compile time into `Length`, which has no text. + const LENGTHS: &[(&str, &str, &str)] = &[ + ("opacity", "50%", RECT), + ("fill-opacity", "50%", RECT), + ("stroke-opacity", "50%", RECT), + ("stroke-width", "7px", RECT), + ("x", "20%", RECT), + ("width", "30mm", RECT), + ("rx", "5px", RECT), + ("transform-origin", "40px", ROTATED), + ("transform-origin", "50%", ROTATED), + ("stroke-dashoffset", "3px", STROKED), + ("stroke-dasharray", "4px", STROKED), + ("cx", "40%", CIRCLE), + ("r", "30px", CIRCLE), + ("x2", "70%", LINE), + ("x1", "20%", LINEAR), + ("cx", "30%", RADIAL), + ("fr", "10%", RADIAL), + ("offset", "30%", STOP), + ("stop-opacity", "50%", STOP), + ("width", "25px", PATTERN), + ("x", "10px", NESTED_SVG), + ("width", "80%", NESTED_SVG), + ("x", "10px", USE), + ("markerWidth", "6px", MARKER), + ("refX", "2px", MARKER), + ("x", "10%", MASK), + ("font-size", "150%", LABEL), + ("font-size", "2em", LABEL), + ("letter-spacing", "3px", LABEL), + ("word-spacing", "0.5em", LABEL), + ("x", "20px", LABEL), + ("dx", "4px", LABEL), + ("textLength", "150px", LABEL), + ("kerning", "0px", KERNED_LABEL), + ("baseline-shift", "20%", TSPAN), + ("baseline-shift", "6px", TSPAN), + ("startOffset", "20%", TEXT_PATH), + ("x", "10%", FILTER_REGION), + ("width", "5px", BLUR), + ("flood-opacity", "50%", FLOOD), + ]; + + /// Checks that `text` written in the SVG has an effect, and that each of `parsed` renders + /// the same. Returns what differs. + fn same_as_text( + name: &str, + text: &'static str, + template: &str, + parsed: &[(&str, SvgAttributeValue<'static>)], + ) -> Vec { + let aid = AId::from_str(name).unwrap(); + let case = format!("{name}={text} in {template}"); + let runtime = written_with_layout(&from_template(template, Some((aid, s(text))))); + if runtime == written_with_layout(&from_template(template, None)) { + return vec![format!("{case}: the written value has no effect")]; + } + parsed + .iter() + .filter(|(_, value)| { + written_with_layout(&from_template(template, Some((aid, value.clone())))) != runtime + }) + .map(|(form, _)| format!("{case}: the {form} differs from the text")) + .collect() + } + + /// The same number renders the same whether it is written in the SVG (runtime parsing), + /// parsed at compile time, or set from code. + #[test] + fn every_number_attribute() { + let failures: Vec<_> = NUMBERS + .iter() + .flat_map(|&(name, number, text, template)| { + same_as_text( + name, + text, + template, + &[ + ( + "compile-time number", + SvgAttributeValue::Float(number, StringStorage::Borrowed(text)), + ), + ("number from code", SvgAttributeValue::from(number)), + ], + ) + }) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); + } + + /// A weight outside 1 to 1000 is invalid in CSS, written or set from code, and keeps the + /// inherited weight. + #[test] + fn font_weight_out_of_range() { + let inherited = written_with_layout(&from_template(LABEL, None)); + for (number, text) in [(1500.0, "1500"), (0.0, "0"), (-700.0, "-700"), (0.5, "0.5")] { + for value in [s(text), SvgAttributeValue::from(number)] { + let doc = from_template(LABEL, Some((AId::FontWeight, value))); + assert_eq!(written_with_layout(&doc), inherited, "font-weight {text}"); + } + } + } + + /// A length written in the SVG renders the same as the one svgr-macro parses at compile + /// time. + #[test] + fn every_length_attribute() { + let failures: Vec<_> = LENGTHS + .iter() + .flat_map(|&(name, text, template)| { + let length = text.parse().unwrap(); + same_as_text( + name, + text, + template, + &[("compile-time length", SvgAttributeValue::Length(length))], + ) + }) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); + } } From d76b11218b316aa060840c7008fd09d662bdb9b4 Mon Sep 17 00:00:00 2001 From: Dmitriy Kovalenko Date: Tue, 13 Oct 2026 07:29:26 -0700 Subject: [PATCH 4/4] fix(usvgr): compute bolder and lighter as CSS Fonts 4 and browsers do bolder and lighter used fixed steps of 100 (300 from 400 for bolder, 200 for lighter). Browsers use the table of CSS Fonts 4: lighter of 400 is 100, bolder of 700 is 900, lighter of 700 is 400. font-weight keywords are also ASCII case-insensitive, and the value can have spaces around it. --- crates/usvgr/src/parser/text.rs | 49 +++++++++++++++------------------ crates/usvgr/tests/parser.rs | 46 ++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 28 deletions(-) diff --git a/crates/usvgr/src/parser/text.rs b/crates/usvgr/src/parser/text.rs index 3875ddfb7..b156b4a12 100644 --- a/crates/usvgr/src/parser/text.rs +++ b/crates/usvgr/src/parser/text.rs @@ -590,10 +590,6 @@ fn conv_font_stretch(node: SvgNode) -> FontStretch { } fn resolve_font_weight(node: SvgNode) -> u16 { - fn bound(min: usize, val: usize, max: usize) -> usize { - std::cmp::max(min, std::cmp::min(max, val)) - } - let nodes: Vec<_> = node.ancestors().collect(); let mut weight = 400; for n in nodes.iter().rev().skip(1) { @@ -603,34 +599,33 @@ fn resolve_font_weight(node: SvgNode) -> u16 { weight = font_weight_number(number).unwrap_or(weight); continue; } - weight = match n.attribute(AId::FontWeight).unwrap_or("") { - "normal" => 400, - "bold" => 700, - "bolder" => { - // By the CSS2 spec the default value should be 400 - // so `bolder` will result in 500. - // But Chrome and Inkscape will give us 700. - // Have no idea is it a bug or something, but - // we will follow such behavior for now. - let step = if weight == 400 { 300 } else { 100 }; - - bound(100, weight + step, 900) + // CSS keywords are ASCII case-insensitive. + let text = n.attribute(AId::FontWeight).unwrap_or("").trim(); + weight = if text.eq_ignore_ascii_case("normal") { + 400 + } else if text.eq_ignore_ascii_case("bold") { + 700 + } else if text.eq_ignore_ascii_case("bolder") { + // The relative weights of CSS Fonts 4, as browsers compute them. + match weight { + ..350 => 400, + 350..550 => 700, + 550..900 => 900, + _ => weight, } - "lighter" => { - // By the CSS2 spec the default value should be 400 - // so `lighter` will result in 300. - // But Chrome and Inkscape will give us 200. - // Have no idea is it a bug or something, but - // we will follow such behavior for now. - let step = if weight == 400 { 200 } else { 100 }; - - bound(100, weight.saturating_sub(step), 900) + } else if text.eq_ignore_ascii_case("lighter") { + match weight { + ..100 => weight, + 100..550 => 100, + 550..750 => 400, + _ => 700, } + } else { // Any number, not only the multiples of 100: variable fonts have every weight. - text => svgrtypes::Number::from_str(text) + svgrtypes::Number::from_str(text) .ok() .and_then(|number| font_weight_number(number.0 as f32)) - .unwrap_or(weight), + .unwrap_or(weight) }; } diff --git a/crates/usvgr/tests/parser.rs b/crates/usvgr/tests/parser.rs index f95831ea5..5fad1b67f 100644 --- a/crates/usvgr/tests/parser.rs +++ b/crates/usvgr/tests/parser.rs @@ -909,8 +909,52 @@ mod numbers_set_from_code { #[test] fn font_weight_lighter_than_a_small_number() { + // CSS Fonts 4: `lighter` keeps a weight below 100. let doc = nested_weights(SvgAttributeValue::from(1.0), s("lighter")); - assert!(written(&doc).contains(r#"font-weight="100""#)); + assert!(written(&doc).contains(r#"font-weight="1""#)); + } + + /// `bolder` and `lighter` follow the table of CSS Fonts 4, as browsers do (checked in + /// Chrome 154), and keywords are case-insensitive. + #[test] + fn font_weight_relative_keywords() { + let cases = [ + (1.0, "bolder", 400), + (100.0, "bolder", 400), + (300.0, "bolder", 400), + (400.0, "bolder", 700), + (500.0, "bolder", 700), + (600.0, "bolder", 900), + (650.0, "bolder", 900), + (700.0, "bolder", 900), + (800.0, "bolder", 900), + (900.0, "bolder", 900), + (1000.0, "bolder", 1000), + (1.0, "lighter", 1), + (100.0, "lighter", 100), + (200.0, "lighter", 100), + (400.0, "lighter", 100), + (500.0, "lighter", 100), + (600.0, "lighter", 400), + (650.0, "lighter", 400), + (700.0, "lighter", 400), + (800.0, "lighter", 700), + (900.0, "lighter", 700), + (1000.0, "lighter", 700), + (300.0, "BOLD", 700), + (300.0, " Normal ", 400), + (300.0, " 650 ", 650), + ]; + for (parent, child, expected) in cases { + let out = written(&nested_weights(SvgAttributeValue::from(parent), s(child))); + // The writer leaves out the default weight. + let weight = if expected == 400 { + !out.contains("font-weight=") + } else { + out.contains(&format!(r#"font-weight="{expected}""#)) + }; + assert!(weight, "{parent} {child:?} should be {expected}:\n{out}"); + } } #[test]