Skip to main content

virtual_node/velement/
attribute_value.rs

1use std::fmt::{Display, Formatter};
2
3/// The value associated with an element's attribute.
4///
5/// For <button disabled=true></button>, the element attribute value would be
6/// `ElementAttributeValue::Bool(true)`
7#[derive(Debug, PartialEq, Clone)]
8pub enum AttributeValue {
9    /// A string attribute such as value="My text input contents"
10    String(String),
11    /// A boolean attribute disabled=true
12    Bool(bool),
13}
14
15impl AttributeValue {
16    /// If the attribute is a string, return it. Otherwise return None.
17    pub fn as_string(&self) -> Option<&String> {
18        match self {
19            AttributeValue::String(s) => Some(s),
20            _ => None,
21        }
22    }
23
24    /// If the attribute is a bool, return it. Otherwise return None.
25    pub fn as_bool(&self) -> Option<bool> {
26        match self {
27            AttributeValue::Bool(b) => Some(*b),
28            _ => None,
29        }
30    }
31}
32
33// Implements
34//   From<T> and From<&T> -> AttributeValue::String(T.to_string())
35macro_rules! to_string_impls {
36    ($ty:ty) => {
37        impl From<$ty> for AttributeValue {
38            fn from(val: $ty) -> Self {
39                AttributeValue::String(val.to_string())
40            }
41        }
42
43        impl From<&$ty> for AttributeValue {
44            fn from(val: &$ty) -> Self {
45                AttributeValue::String(val.to_string())
46            }
47        }
48    };
49
50    ($ty:ty, $($tys:ty),*) => {
51        to_string_impls!( $ty );
52        to_string_impls! ( $($tys),* );
53    }
54}
55to_string_impls!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, f32, f64);
56
57#[cfg(feature = "web")]
58impl Into<wasm_bindgen::JsValue> for AttributeValue {
59    fn into(self) -> wasm_bindgen::JsValue {
60        match self {
61            AttributeValue::String(s) => s.into(),
62            AttributeValue::Bool(b) => b.into(),
63        }
64    }
65}
66
67mod from_impls {
68    //! These `From` implementations are used by the `html-macro` to convert an arbitrary expression
69    //! into an [`AttributeValue`].
70    //! Relying on the `From` impl allows us to create an `AttributeValue` without needing the
71    //! `AttributeValue` type to be in scope. This means that the generated macro code does not
72    //! require `AttributeValue` to be in scope.
73    //! To find this use case, search for `#value.into()` within the `crates/html-macro` crate.
74
75    use super::*;
76
77    impl From<String> for AttributeValue {
78        fn from(s: String) -> Self {
79            AttributeValue::String(s)
80        }
81    }
82
83    impl From<&String> for AttributeValue {
84        fn from(s: &String) -> Self {
85            AttributeValue::String(s.to_string())
86        }
87    }
88
89    impl From<&str> for AttributeValue {
90        fn from(s: &str) -> Self {
91            AttributeValue::String(s.to_string())
92        }
93    }
94
95    impl<S: AsRef<str>, const N: usize> From<[S; N]> for AttributeValue {
96        fn from(vals: [S; N]) -> Self {
97            let mut combined = "".to_string();
98
99            for (idx, val) in vals.iter().enumerate() {
100                if idx != 0 {
101                    combined += " ";
102                }
103
104                combined += val.as_ref();
105            }
106
107            AttributeValue::String(combined)
108        }
109    }
110
111    impl<S: AsRef<str>> From<Vec<S>> for AttributeValue {
112        fn from(vals: Vec<S>) -> Self {
113            let mut combined = "".to_string();
114
115            for (idx, val) in vals.iter().enumerate() {
116                if idx != 0 {
117                    combined += " ";
118                }
119
120                combined += val.as_ref();
121            }
122
123            AttributeValue::String(combined)
124        }
125    }
126
127    impl From<bool> for AttributeValue {
128        fn from(b: bool) -> Self {
129            AttributeValue::Bool(b)
130        }
131    }
132
133    impl From<&bool> for AttributeValue {
134        fn from(b: &bool) -> Self {
135            AttributeValue::Bool(*b)
136        }
137    }
138}
139
140impl Display for AttributeValue {
141    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
142        match self {
143            AttributeValue::String(s) => s.fmt(f),
144            AttributeValue::Bool(b) => b.fmt(f),
145        }
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn array_of_as_ref_str() {
155        assert_eq!(
156            AttributeValue::from(["hello", "world"]),
157            AttributeValue::String("hello world".to_string())
158        );
159    }
160
161    #[test]
162    fn vec_of_as_ref_str() {
163        assert_eq!(
164            AttributeValue::from(vec!["foo", "bar"]),
165            AttributeValue::String("foo bar".to_string())
166        );
167    }
168}