silkenweb/elements/svg/
content_type.rs

1//! SVG content types.
2//!
3//! See [MDN SVG Content Types](https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type)
4
5use silkenweb_signals_ext::value::Value;
6
7use crate::attribute::{AsAttribute, Attribute};
8
9/// An SVG length with units. For percentages, use [`Percentage`] and for
10/// unitless lengths, use `f64`.
11pub enum Length {
12    Em(f64),
13    Ex(f64),
14    Px(f64),
15    Cm(f64),
16    Mm(f64),
17    In(f64),
18    Pt(f64),
19    Pc(f64),
20}
21
22impl Attribute for Length {
23    type Text<'a> = String;
24
25    fn text(&self) -> Option<Self::Text<'_>> {
26        let (length, units) = match self {
27            Length::Em(l) => (l, "em"),
28            Length::Ex(l) => (l, "ex"),
29            Length::Px(l) => (l, "px"),
30            Length::Cm(l) => (l, "cm"),
31            Length::Mm(l) => (l, "mm"),
32            Length::In(l) => (l, "in"),
33            Length::Pt(l) => (l, "pt"),
34            Length::Pc(l) => (l, "pc"),
35        };
36
37        Some(format!("{length}{units}"))
38    }
39}
40
41impl Value for Length {}
42
43impl AsAttribute<Length> for Length {}
44impl AsAttribute<Length> for Percentage {}
45impl AsAttribute<Length> for f64 {}
46
47/// SVG attribute type for percentages
48pub struct Percentage(pub f64);
49
50impl Attribute for Percentage {
51    type Text<'a> = String;
52
53    fn text(&self) -> Option<Self::Text<'_>> {
54        Some(format!("{}%", self.0))
55    }
56}
57
58impl AsAttribute<Percentage> for Percentage {}
59impl Value for Percentage {}
60
61/// For SVG attributes that accept "auto"
62pub struct Auto;
63
64impl Attribute for Auto {
65    type Text<'a> = &'static str;
66
67    fn text(&self) -> Option<Self::Text<'_>> {
68        Some("auto")
69    }
70}
71
72impl AsAttribute<Auto> for Auto {}
73
74impl Value for Auto {}
75
76/// Marker type for SVG attributes that can be a number or percentage
77pub struct NumberOrPercentage;
78
79impl AsAttribute<NumberOrPercentage> for f64 {}
80impl AsAttribute<NumberOrPercentage> for Percentage {}
81
82/// Marker type for SVG attributes that can be "auto" or a length
83pub struct AutoOrLength;
84
85impl AsAttribute<AutoOrLength> for Auto {}
86impl AsAttribute<AutoOrLength> for f64 {}
87impl AsAttribute<AutoOrLength> for Length {}
88impl AsAttribute<AutoOrLength> for Percentage {}