svg: extract shared SVG document/CSS interpretation helpers (#778) (#2456)

* svg: extract shared SVG document/CSS interpretation helpers (storytold/craft-libs#778)

* svg: document doc_style::length unknown-unit px fallback

* style(svg): fix clippy field_reassign_with_default in doc_style test
This commit is contained in:
Dylan M. Taylor
2026-11-19 20:36:26 -05:00
committed by GitHub
parent 1a3be2d439
commit 03d1afced9
3 changed files with 467 additions and 0 deletions
+7
View File
@@ -17,6 +17,13 @@ The shared adapter adds an aggregate 64 MiB stylesheet-text limit and idempotent
### Transform compatibility
`transform_compat::parse_transform` preserves EffectCraft transform-list recovery and exact composition. It retains six numeric arguments per operation; scanning is not time/byte capped and matrix overflow behavior is unchanged. The strict geometry reader is unchanged. Source: Brandon Thomas, EffectCraft94e1c86d89a866771f80ad1610afda9aa12e85d8; bounded safe argument matching by Altynzhan Karybai,4035d181329e847d7a57bf3d059502ea2c91b560.
### Document and CSS style compatibility
`doc_style` preserves EffectCraft's presentation-attribute + stylesheet + inline-`style`
cascade, unit/percentage length resolution, `PaintRef`/`resolve_paint`, and
`viewBox`/`preserveAspectRatio` transform helpers while leaving scene-graph mapping
with the importer. Note that `doc_style::length()` treats unknown units as `px` (`_ => v`).
### Opt-in validated embedded images
+457
View File
@@ -0,0 +1,457 @@
//! Compatibility SVG document/CSS interpretation helpers extracted from EffectCraft.
//!
//! Provides presentation-attribute + stylesheet + inline-`style` declaration collection
//! ([`declared`]), property cascading ([`cascade`]), unit/percentage length resolution
//! ([`length`], [`attr_len`]), paint reference parsing/resolution ([`PaintRef`], [`paint_ref`],
//! [`resolve_paint`]), and `viewBox` / `preserveAspectRatio` transforms ([`viewbox`],
//! [`viewbox_transform`]).
use std::collections::HashMap;
use kurbo::Affine;
use crate::{
color::parse_rgba_compat,
prefix_path::numbers_bounded,
simple_css::{StyleSheet, declarations},
};
/// SVG `fill-rule` property.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FillRule {
#[default]
NonZero,
EvenOdd,
}
/// SVG `stroke-linecap` property.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Cap {
#[default]
Butt,
Round,
Square,
}
/// SVG `stroke-linejoin` property.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Join {
#[default]
Miter,
Round,
Bevel,
}
/// Parsed SVG paint reference (`none`, `currentColor`, `url(#id) [fallback]`, or RGBA color).
#[derive(Clone, Debug, PartialEq)]
pub enum PaintRef {
/// Solid straight RGBA color `[r, g, b, a]` in `0.0..=1.0`.
Color([f64; 4]),
/// Paint server reference `url(#id)` with an optional fallback RGBA color.
Url(String, Option<[f64; 4]>),
/// `currentColor`.
Current,
}
/// Caller outcome when resolving a `url(#id)` paint reference.
#[derive(Clone, Debug, PartialEq)]
pub enum UrlPaint<S> {
/// Resolved to a caller paint server (for example, a gradient or pattern).
Server(S),
/// Resolved to a solid RGBA color (for example, a single-stop gradient).
Color([f64; 4]),
/// No paint server found; fall back to the `url(#id) fallback` color if present.
Fallback,
/// Paint server found but empty or invalid; do not fall back.
None,
}
/// Result of resolving a [`PaintRef`] without committing to a caller's paint-server type.
#[derive(Clone, Debug, PartialEq)]
pub enum ResolvedPaint<S> {
/// Solid RGB color `[r, g, b]` with alpha `a`.
Color([f64; 3], f64),
/// A caller-resolved paint server (`url(#id)`).
Server(S),
}
/// Inherited SVG style state.
#[derive(Clone, Debug, PartialEq)]
pub struct Style {
pub fill: Option<PaintRef>,
pub fill_opacity: f64,
pub fill_rule: FillRule,
pub stroke: Option<PaintRef>,
pub stroke_opacity: f64,
pub stroke_width: f64,
pub cap: Cap,
pub join: Join,
pub miter: f64,
pub dash: Option<Vec<f64>>,
pub dash_offset: f64,
pub color: [f64; 4],
pub visible: bool,
pub font_size: f64,
}
impl Default for Style {
fn default() -> Self {
Style {
fill: Some(PaintRef::Color([0.0, 0.0, 0.0, 1.0])),
fill_opacity: 1.0,
fill_rule: FillRule::NonZero,
stroke: None,
stroke_opacity: 1.0,
stroke_width: 1.0,
cap: Cap::Butt,
join: Join::Miter,
miter: 4.0,
dash: None,
dash_offset: 0.0,
color: [0.0, 0.0, 0.0, 1.0],
visible: true,
font_size: 16.0,
}
}
}
/// Presentation attributes recognised by [`declared`].
pub const STYLE_PROPS: &[&str] = &[
"fill",
"fill-opacity",
"fill-rule",
"stroke",
"stroke-width",
"stroke-opacity",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"stroke-dasharray",
"stroke-dashoffset",
"opacity",
"display",
"visibility",
"color",
"font-size",
"transform",
"stop-color",
"stop-opacity",
];
/// Collect the declared properties of an element: presentation attributes, then CSS rules
/// (by specificity and source order, bounded by `charge_css`), then the inline `style` attribute.
pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usize) -> bool) -> HashMap<String, String> {
let mut out = HashMap::new();
for a in n.attributes() {
if STYLE_PROPS.contains(&a.name()) && a.name() != "transform" {
out.insert(a.name().to_string(), a.value().to_string());
}
}
css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), &mut out, charge_css);
if let Some(st) = n.attribute("style") {
for (k, v) in declarations(st) {
out.insert(k, v);
}
}
out
}
/// Parse an SVG length or percentage into user-space pixels.
///
/// `axis` selects the percentage reference base: `'x'` uses `vw`, `'y'` uses `vh`, and any
/// other value uses the normalized diagonal `((vw^2 + vh^2) / 2).sqrt()`.
pub fn length(s: &str, axis: char, font: f64, vw: f64, vh: f64) -> Option<f64> {
let s = s.trim();
let num_end = s.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'))).unwrap_or(s.len());
// "e" also starts "em"/"ex": back off if the number does not parse.
let (mut num, mut unit) = (&s[..num_end], &s[num_end..]);
if num.parse::<f64>().is_err() && (num.ends_with('e') || num.ends_with('E')) {
let back = num_end.saturating_sub(1);
num = &s[..back];
unit = &s[back..];
}
let v: f64 = num.parse().ok()?;
let value = match unit.trim() {
"" | "px" => v,
"pt" => v * 4.0 / 3.0,
"pc" => v * 16.0,
"mm" => v * 96.0 / 25.4,
"cm" => v * 96.0 / 2.54,
"in" => v * 96.0,
"em" => v * font,
"ex" => v * font / 2.0,
"%" => {
let base = match axis {
'x' => vw,
'y' => vh,
_ => ((vw * vw + vh * vh) / 2.0).sqrt(),
};
v / 100.0 * base
}
_ => v,
};
value.is_finite().then_some(value)
}
/// Parse a length attribute on `n`, returning `0.0` if missing or invalid.
pub fn attr_len(n: roxmltree::Node, name: &str, axis: char, st: &Style, vw: f64, vh: f64) -> f64 {
n.attribute(name).and_then(|v| length(v, axis, st.font_size, vw, vh)).unwrap_or(0.0)
}
/// Parse an SVG paint value (`none`, `currentColor`, `url(#id) [fallback]`, `inherit`, or color).
///
/// Returns `None` for `"inherit"` or unrecognized values, `Some(None)` for `"none"`, and
/// `Some(Some(PaintRef))` for concrete paints or `url(...)` / `currentColor` references.
pub fn paint_ref(v: &str) -> Option<Option<PaintRef>> {
let v = v.trim();
if v == "none" {
return Some(None);
}
if v == "currentColor" || v == "currentcolor" {
return Some(Some(PaintRef::Current));
}
if let Some(rest) = v.strip_prefix("url(") {
let (url, fallback) = rest.split_once(')').unwrap_or((rest, ""));
let url = url.trim().trim_matches(['"', '\'']);
let id = url.strip_prefix('#').filter(|id| !id.is_empty()).unwrap_or_default().to_string();
let fb = fallback.trim();
let fb = if fb.is_empty() || fb == "none" { None } else { parse_rgba_compat(fb) };
return Some(Some(PaintRef::Url(id, fb)));
}
if v == "inherit" {
return None;
}
parse_rgba_compat(v).map(|c| Some(PaintRef::Color(c)))
}
/// Apply an element's declared inherited properties to `st`.
///
/// Returns `(opacity, display)` where `display` is `false` when `display: none` is set.
pub fn cascade(n: roxmltree::Node, css: &StyleSheet, st: &mut Style, vw: f64, vh: f64, charge_css: impl FnMut(usize) -> bool) -> (f64, bool) {
let d = declared(n, css, charge_css);
let num = |k: &str| {
d.get(k)
.and_then(|v| v.trim().trim_end_matches('%').parse::<f64>().ok().map(|x| if v.trim().ends_with('%') { x / 100.0 } else { x }))
.filter(|x| x.is_finite())
};
if let Some(c) = d.get("color").and_then(|v| parse_rgba_compat(v)) {
st.color = c;
}
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 => length(v, 'o', st.font_size, vw, vh),
});
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| paint_ref(v)) {
st.fill = p;
}
if let Some(p) = d.get("stroke").and_then(|v| paint_ref(v)) {
st.stroke = p;
}
if let Some(v) = num("fill-opacity") {
st.fill_opacity = v.clamp(0.0, 1.0);
}
if let Some(v) = num("stroke-opacity") {
st.stroke_opacity = v.clamp(0.0, 1.0);
}
if let Some(v) = d.get("stroke-width").and_then(|v| length(v, 'o', st.font_size, vw, vh)) {
st.stroke_width = v.max(0.0);
}
if let Some(v) = num("stroke-miterlimit") {
st.miter = v.max(1.0);
}
if let Some(v) = d.get("fill-rule") {
st.fill_rule = if v.trim() == "evenodd" { FillRule::EvenOdd } else { FillRule::NonZero };
}
if let Some(v) = d.get("stroke-linecap") {
st.cap = match v.trim() {
"round" => Cap::Round,
"square" => Cap::Square,
_ => Cap::Butt,
};
}
if let Some(v) = d.get("stroke-linejoin") {
st.join = match v.trim() {
"round" => Join::Round,
"bevel" => Join::Bevel,
_ => Join::Miter,
};
}
if let Some(v) = d.get("stroke-dasharray") {
st.dash = if v.trim() == "none" {
None
} else {
let a: Vec<f64> = v
.split(|c: char| c == ',' || c.is_whitespace())
.filter(|t| !t.is_empty())
.filter_map(|t| length(t, 'o', st.font_size, vw, vh))
.collect();
if a.iter().all(|x| *x >= 0.0) && a.iter().any(|x| *x > 0.0) { Some(a) } else { None }
};
}
if let Some(v) = d.get("stroke-dashoffset").and_then(|v| length(v, 'o', st.font_size, vw, vh)) {
st.dash_offset = v;
}
if let Some(v) = d.get("visibility") {
st.visible = !matches!(v.trim(), "hidden" | "collapse");
}
let display = d.get("display").is_none_or(|v| v.trim() != "none");
(num("opacity").unwrap_or(1.0).clamp(0.0, 1.0), display)
}
/// Resolve a [`PaintRef`] against `st` and a caller-supplied `url(#id)` resolver.
pub fn resolve_paint<S>(paint: &PaintRef, st: &Style, resolve_url: impl FnOnce(&str, Option<[f64; 4]>) -> UrlPaint<S>) -> Option<ResolvedPaint<S>> {
match paint {
PaintRef::Color(c) => Some(ResolvedPaint::Color([c[0], c[1], c[2]], c[3])),
PaintRef::Current => Some(ResolvedPaint::Color([st.color[0], st.color[1], st.color[2]], st.color[3])),
PaintRef::Url(id, fallback) => match resolve_url(id, *fallback) {
UrlPaint::Server(s) => Some(ResolvedPaint::Server(s)),
UrlPaint::Color(c) => Some(ResolvedPaint::Color([c[0], c[1], c[2]], c[3])),
UrlPaint::Fallback => fallback.map(|c| ResolvedPaint::Color([c[0], c[1], c[2]], c[3])),
UrlPaint::None => None,
},
}
}
/// Parse an element's `viewBox` attribute into `([min_x, min_y], width, height)`.
pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> {
let (v, exceeded) = numbers_bounded(n.attribute("viewBox")?, 5);
if exceeded || !v.iter().all(|x| x.is_finite()) {
return None;
}
let [x, y, width, height] = v.as_slice() else { return None };
(*width > 0.0 && *height > 0.0).then_some(([*x, *y], *width, *height))
}
/// The `viewBox` -> viewport transform (`preserveAspectRatio`, default `xMidYMid meet`).
pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine {
let Some(([x, y], vw, vh)) = viewbox(n) else { return Affine::IDENTITY };
let par = n.attribute("preserveAspectRatio").unwrap_or("xMidYMid meet");
let mut parts = par.split_whitespace();
let mut align = parts.next().unwrap_or("xMidYMid");
if align == "defer" {
align = parts.next().unwrap_or("xMidYMid");
}
let slice = parts.next() == Some("slice");
let (sx, sy) = (w / vw, h / vh);
if align == "none" {
return Affine::scale_non_uniform(sx, sy) * Affine::translate((-x, -y));
}
let s = if slice { sx.max(sy) } else { sx.min(sy) };
let fx = if align.contains("xMid") {
0.5
} else if align.contains("xMax") {
1.0
} else {
0.0
};
let fy = if align.contains("YMid") {
0.5
} else if align.contains("YMax") {
1.0
} else {
0.0
};
let tx = (w - vw * s) * fx;
let ty = (h - vh * s) * fy;
Affine::translate((tx, ty)) * Affine::scale(s) * Affine::translate((-x, -y))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::simple_css::parse as parse_css;
#[test]
fn declared_precedence_and_transform_exclusion() {
let doc = roxmltree::Document::parse(
r#"<svg xmlns="http://www.w3.org/2000/svg"><rect id="r" class="a" fill="black" transform="translate(5)" style="fill:blue"/></svg>"#,
)
.unwrap();
let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap();
let mut css = StyleSheet::default();
parse_css(".a { fill: green; stroke: red; }", &mut css).unwrap();
css.index();
let d = declared(rect, &css, |_| true);
assert_eq!(d.get("fill").map(String::as_str), Some("blue"));
assert_eq!(d.get("stroke").map(String::as_str), Some("red"));
assert!(!d.contains_key("transform"));
}
#[test]
fn length_units_and_exponents() {
assert_eq!(length("10", 'x', 16.0, 200.0, 100.0), Some(10.0));
assert_eq!(length("12pt", 'x', 16.0, 200.0, 100.0), Some(16.0));
assert_eq!(length("1in", 'x', 16.0, 200.0, 100.0), Some(96.0));
assert_eq!(length("2em", 'x', 16.0, 200.0, 100.0), Some(32.0));
assert_eq!(length("2ex", 'x', 16.0, 200.0, 100.0), Some(16.0));
assert_eq!(length("1e2em", 'x', 10.0, 200.0, 100.0), Some(1000.0));
assert_eq!(length("50%", 'x', 16.0, 200.0, 100.0), Some(100.0));
assert_eq!(length("50%", 'y', 16.0, 200.0, 100.0), Some(50.0));
assert_eq!(length("nan", 'x', 16.0, 200.0, 100.0), None);
}
#[test]
fn attr_len_reads_or_defaults_to_zero() {
let doc = roxmltree::Document::parse(r#"<svg xmlns="http://www.w3.org/2000/svg"><rect x="50%" y="bad"/></svg>"#).unwrap();
let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap();
let st = Style::default();
assert_eq!(attr_len(rect, "x", 'x', &st, 200.0, 100.0), 100.0);
assert_eq!(attr_len(rect, "y", 'y', &st, 200.0, 100.0), 0.0);
assert_eq!(attr_len(rect, "width", 'x', &st, 200.0, 100.0), 0.0);
}
#[test]
fn cascade_applies_inheritance_and_display() {
let doc = roxmltree::Document::parse(
r##"<svg xmlns="http://www.w3.org/2000/svg"><g color="red" font-size="20" fill="currentColor" stroke="#00ff00" stroke-width="2em" stroke-dasharray="4 2" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="bevel" opacity="50%" display="none" visibility="hidden"/></svg>"##,
)
.unwrap();
let g = doc.descendants().find(|n| n.tag_name().name() == "g").unwrap();
let css = StyleSheet::default();
let mut st = Style::default();
let (opacity, display) = cascade(g, &css, &mut st, 100.0, 100.0, |_| true);
assert_eq!(opacity, 0.5);
assert!(!display);
assert!(!st.visible);
assert_eq!(st.font_size, 20.0);
assert_eq!(st.stroke_width, 40.0);
assert_eq!(st.fill, Some(PaintRef::Current));
assert_eq!(st.fill_rule, FillRule::EvenOdd);
assert_eq!(st.cap, Cap::Round);
assert_eq!(st.join, Join::Bevel);
assert_eq!(st.dash, Some(vec![4.0, 2.0]));
}
#[test]
fn paint_ref_and_resolve_paint_handle_fallbacks() {
assert_eq!(paint_ref("none"), Some(None));
assert_eq!(paint_ref("inherit"), None);
assert_eq!(paint_ref("currentColor"), Some(Some(PaintRef::Current)));
assert_eq!(paint_ref("url(#grad) red"), Some(Some(PaintRef::Url("grad".into(), Some([1.0, 0.0, 0.0, 1.0])))));
let st = Style { color: [0.0, 1.0, 0.0, 0.5], ..Style::default() };
assert_eq!(resolve_paint(&PaintRef::Current, &st, |_, _| UrlPaint::<()>::None), Some(ResolvedPaint::Color([0.0, 1.0, 0.0], 0.5)));
let url = PaintRef::Url("g".into(), Some([1.0, 0.0, 0.0, 1.0]));
assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::Server("ok")), Some(ResolvedPaint::Server("ok")));
assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::Fallback), Some(ResolvedPaint::Color([1.0, 0.0, 0.0], 1.0)));
assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::None), None);
}
#[test]
fn viewbox_and_transform_preserve_aspect_ratio() {
let doc = roxmltree::Document::parse(
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 20 100 50" preserveAspectRatio="defer xMaxYMid meet"/>"#,
)
.unwrap();
let root = doc.root_element();
assert_eq!(viewbox(root), Some(([10.0, 20.0], 100.0, 50.0)));
let m = viewbox_transform(root, 200.0, 200.0);
// Scale is min(2, 4) = 2; tx = (200 - 200) * 1.0 = 0; ty = (200 - 100) * 0.5 = 50.
let p = m * kurbo::Point::new(10.0, 20.0);
assert_eq!(p, kurbo::Point::new(0.0, 50.0));
}
}
+3
View File
@@ -38,3 +38,6 @@ pub mod simple_css;
/// Prefix-preserving SVG transform-list compatibility.
pub mod transform_compat;
/// Compatibility SVG document/CSS interpretation helpers (style cascade, lengths, paints, viewBox).
pub mod doc_style;