sycamore_web/
attributes.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use crate::*;

/// A trait that represents an attribute that can be set. This is not "attribute" in the HTML spec
/// sense. It can also represent JS properties (and possibly more ...) that can be set on an HTML
/// element.
pub trait AttributeValue: AttributeValueBoxed + 'static {
    fn set_self(self, el: &mut HtmlNode, name: Cow<'static, str>);
}

/// Type alias representing a possibly dynamic string value.
pub type StringAttribute = MaybeDyn<Option<Cow<'static, str>>>;
impl AttributeValue for StringAttribute {
    fn set_self(self, el: &mut HtmlNode, name: Cow<'static, str>) {
        el.set_attribute(name, self);
    }
}

/// Type alias respresenting a possibly dynamic boolean value.
pub type BoolAttribute = MaybeDyn<bool>;
impl AttributeValue for BoolAttribute {
    fn set_self(self, el: &mut HtmlNode, name: Cow<'static, str>) {
        el.set_bool_attribute(name, self);
    }
}

impl AttributeValue for MaybeDyn<JsValue> {
    fn set_self(self, el: &mut HtmlNode, name: Cow<'static, str>) {
        el.set_property(name, self);
    }
}

/// Trait used to implement `AttributeValue` for `Box<dyn AttributeValue>`.
#[doc(hidden)]
pub trait AttributeValueBoxed: 'static {
    fn set_self_boxed(self: Box<Self>, el: &mut HtmlNode, name: Cow<'static, str>);
}

impl<T> AttributeValueBoxed for T
where
    T: AttributeValue,
{
    fn set_self_boxed(self: Box<Self>, el: &mut HtmlNode, name: Cow<'static, str>) {
        self.set_self(el, name);
    }
}

impl AttributeValue for Box<dyn AttributeValue> {
    fn set_self(self, el: &mut HtmlNode, name: Cow<'static, str>) {
        self.set_self_boxed(el, name);
    }
}

/// Implemented for all types that can accept attributes ([`AttributeValue`]).
pub trait SetAttribute {
    fn set_attribute(&mut self, name: &'static str, value: impl AttributeValue);
    fn set_event_handler(
        &mut self,
        name: &'static str,
        value: impl FnMut(web_sys::Event) + 'static,
    );
}

impl<T> SetAttribute for T
where
    T: AsHtmlNode,
{
    fn set_attribute(&mut self, name: &'static str, value: impl AttributeValue) {
        value.set_self(self.as_html_node(), name.into());
    }

    fn set_event_handler(
        &mut self,
        name: &'static str,
        value: impl FnMut(web_sys::Event) + 'static,
    ) {
        self.as_html_node().set_event_handler(name.into(), value);
    }
}

/// A special prop type that can be used to spread attributes onto an element.
#[derive(Default)]
pub struct Attributes {
    values: Vec<(Cow<'static, str>, Box<dyn AttributeValue>)>,
    #[allow(clippy::type_complexity)]
    event_handlers: Vec<(Cow<'static, str>, Box<dyn FnMut(web_sys::Event)>)>,
}

impl SetAttribute for Attributes {
    fn set_attribute(&mut self, name: &'static str, value: impl AttributeValue) {
        self.values.push((name.into(), Box::new(value)));
    }

    fn set_event_handler(
        &mut self,
        name: &'static str,
        value: impl FnMut(web_sys::Event) + 'static,
    ) {
        self.event_handlers.push((name.into(), Box::new(value)));
    }
}

impl Attributes {
    /// Create a new empty [`Attributes`] instance.
    pub fn new() -> Self {
        Self::default()
    }

    pub fn apply_self(self, el: &mut HtmlNode) {
        for (name, value) in self.values {
            value.set_self(el, name);
        }
        for (name, handler) in self.event_handlers {
            el.set_event_handler(name, handler);
        }
    }
}

#[cfg(test)]
mod tests {
    use expect_test::{expect, Expect};

    use super::*;

    fn check<T: Into<View>>(view: impl FnOnce() -> T, expect: Expect) {
        let actual = render_to_string(move || view().into());
        expect.assert_eq(&actual);
    }

    #[test]
    fn attributes_apply_self() {
        let mut attributes = Attributes::new();
        attributes.set_attribute("class", StringAttribute::from("test-class"));
        attributes.set_attribute("id", StringAttribute::from(move || "test-id"));

        check(
            move || crate::tags::div().spread(attributes),
            expect![[r#"<div class="test-class" id="test-id" data-hk="0.0"></div>"#]],
        );
    }

    #[test]
    fn attributes_apply_self_macro() {
        let mut attributes = Attributes::new();
        attributes.set_attribute("class", StringAttribute::from("test-class"));
        attributes.set_attribute("id", StringAttribute::from(move || "test-id"));

        check(
            move || view! { div(..attributes) },
            expect![[r#"<div class="test-class" id="test-id" data-hk="0.0"></div>"#]],
        );
    }
}