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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use leptos_reactive::Scope;
use std::rc::Rc;
#[cfg(all(target_arch = "wasm32", feature = "web"))]
use wasm_bindgen::UnwrapThrowExt;

/// Represents the different possible values an attribute node could have.
///
/// This mostly exists for the [`view`](https://docs.rs/leptos_macro/latest/leptos_macro/macro.view.html)
/// macro’s use. You usually won't need to interact with it directly, but it can be useful for defining
/// permissive APIs for certain components.
#[derive(Clone)]
pub enum Attribute {
    /// A plain string value.
    String(String),
    /// A (presumably reactive) function, which will be run inside an effect to do targeted updates to the attribute.
    Fn(Scope, Rc<dyn Fn() -> Attribute>),
    /// An optional string value, which sets the attribute to the value if `Some` and removes the attribute if `None`.
    Option(Scope, Option<String>),
    /// A boolean attribute, which sets the attribute if `true` and removes the attribute if `false`.
    Bool(bool),
}

impl Attribute {
    /// Converts the attribute to its HTML value at that moment, including the attribute name,
    /// so it can be rendered on the server.
    pub fn as_value_string(&self, attr_name: &'static str) -> String {
        match self {
            Attribute::String(value) => format!("{attr_name}=\"{value}\""),
            Attribute::Fn(_, f) => {
                let mut value = f();
                while let Attribute::Fn(_, f) = value {
                    value = f();
                }
                value.as_value_string(attr_name)
            }
            Attribute::Option(_, value) => value
                .as_ref()
                .map(|value| format!("{attr_name}=\"{value}\""))
                .unwrap_or_default(),
            Attribute::Bool(include) => {
                if *include {
                    attr_name.to_string()
                } else {
                    String::new()
                }
            }
        }
    }

    /// Converts the attribute to its HTML value at that moment, not including
    /// the attribute name, so it can be rendered on the server.
    pub fn as_nameless_value_string(&self) -> Option<String> {
        match self {
            Attribute::String(value) => Some(value.to_string()),
            Attribute::Fn(_, f) => {
                let mut value = f();
                while let Attribute::Fn(_, f) = value {
                    value = f();
                }
                value.as_nameless_value_string()
            }
            Attribute::Option(_, value) => {
                value.as_ref().map(|value| value.to_string())
            }
            Attribute::Bool(include) => {
                if *include {
                    Some("".to_string())
                } else {
                    None
                }
            }
        }
    }
}

impl PartialEq for Attribute {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::String(l0), Self::String(r0)) => l0 == r0,
            (Self::Fn(_, _), Self::Fn(_, _)) => false,
            (Self::Option(_, l0), Self::Option(_, r0)) => l0 == r0,
            (Self::Bool(l0), Self::Bool(r0)) => l0 == r0,
            _ => false,
        }
    }
}

impl std::fmt::Debug for Attribute {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::String(arg0) => f.debug_tuple("String").field(arg0).finish(),
            Self::Fn(_, _) => f.debug_tuple("Fn").finish(),
            Self::Option(_, arg0) => {
                f.debug_tuple("Option").field(arg0).finish()
            }
            Self::Bool(arg0) => f.debug_tuple("Bool").field(arg0).finish(),
        }
    }
}

/// Converts some type into an [Attribute].
///
/// This is implemented by default for Rust primitive and string types.
pub trait IntoAttribute {
    /// Converts the object into an [Attribute].
    fn into_attribute(self, cx: Scope) -> Attribute;
    /// Helper function for dealing with `Box<dyn IntoAttribute>`.
    fn into_attribute_boxed(self: Box<Self>, cx: Scope) -> Attribute;
}

impl<T: IntoAttribute + 'static> From<T> for Box<dyn IntoAttribute> {
    fn from(value: T) -> Self {
        Box::new(value)
    }
}

impl IntoAttribute for Attribute {
    #[inline]
    fn into_attribute(self, _: Scope) -> Attribute {
        self
    }

    #[inline]
    fn into_attribute_boxed(self: Box<Self>, _: Scope) -> Attribute {
        *self
    }
}

macro_rules! impl_into_attr_boxed {
    () => {
        #[inline]
        fn into_attribute_boxed(self: Box<Self>, cx: Scope) -> Attribute {
            self.into_attribute(cx)
        }
    };
}

impl IntoAttribute for Option<Attribute> {
    fn into_attribute(self, cx: Scope) -> Attribute {
        self.unwrap_or(Attribute::Option(cx, None))
    }

    impl_into_attr_boxed! {}
}

impl IntoAttribute for String {
    fn into_attribute(self, _: Scope) -> Attribute {
        Attribute::String(self)
    }

    impl_into_attr_boxed! {}
}

impl IntoAttribute for bool {
    fn into_attribute(self, _: Scope) -> Attribute {
        Attribute::Bool(self)
    }

    impl_into_attr_boxed! {}
}

impl IntoAttribute for Option<String> {
    fn into_attribute(self, cx: Scope) -> Attribute {
        Attribute::Option(cx, self)
    }

    impl_into_attr_boxed! {}
}

impl<T, U> IntoAttribute for T
where
    T: Fn() -> U + 'static,
    U: IntoAttribute,
{
    fn into_attribute(self, cx: Scope) -> Attribute {
        let modified_fn = Rc::new(move || (self)().into_attribute(cx));
        Attribute::Fn(cx, modified_fn)
    }

    impl_into_attr_boxed! {}
}

impl<T: IntoAttribute> IntoAttribute for (Scope, T) {
    fn into_attribute(self, _: Scope) -> Attribute {
        self.1.into_attribute(self.0)
    }

    impl_into_attr_boxed! {}
}

impl IntoAttribute for (Scope, Option<Box<dyn IntoAttribute>>) {
    fn into_attribute(self, _: Scope) -> Attribute {
        match self.1 {
            Some(bx) => bx.into_attribute_boxed(self.0),
            None => Attribute::Option(self.0, None),
        }
    }

    impl_into_attr_boxed! {}
}

impl IntoAttribute for (Scope, Box<dyn IntoAttribute>) {
    fn into_attribute(self, _: Scope) -> Attribute {
        self.1.into_attribute_boxed(self.0)
    }

    impl_into_attr_boxed! {}
}

macro_rules! attr_type {
    ($attr_type:ty) => {
        impl IntoAttribute for $attr_type {
            fn into_attribute(self, _: Scope) -> Attribute {
                Attribute::String(self.to_string())
            }

            #[inline]
            fn into_attribute_boxed(self: Box<Self>, cx: Scope) -> Attribute {
                self.into_attribute(cx)
            }
        }

        impl IntoAttribute for Option<$attr_type> {
            fn into_attribute(self, cx: Scope) -> Attribute {
                Attribute::Option(cx, self.map(|n| n.to_string()))
            }

            #[inline]
            fn into_attribute_boxed(self: Box<Self>, cx: Scope) -> Attribute {
                self.into_attribute(cx)
            }
        }
    };
}

attr_type!(&String);
attr_type!(&str);
attr_type!(usize);
attr_type!(u8);
attr_type!(u16);
attr_type!(u32);
attr_type!(u64);
attr_type!(u128);
attr_type!(isize);
attr_type!(i8);
attr_type!(i16);
attr_type!(i32);
attr_type!(i64);
attr_type!(i128);
attr_type!(f32);
attr_type!(f64);
attr_type!(char);

#[cfg(all(target_arch = "wasm32", feature = "web"))]
use std::borrow::Cow;
#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[doc(hidden)]
pub fn attribute_helper(
    el: &web_sys::Element,
    name: Cow<'static, str>,
    value: Attribute,
) {
    use leptos_reactive::create_render_effect;
    match value {
        Attribute::Fn(cx, f) => {
            let el = el.clone();
            create_render_effect(cx, move |old| {
                let new = f();
                if old.as_ref() != Some(&new) {
                    attribute_expression(&el, &name, new.clone(), true);
                }
                new
            });
        }
        _ => attribute_expression(el, &name, value, false),
    };
}

#[cfg(all(target_arch = "wasm32", feature = "web"))]
pub(crate) fn attribute_expression(
    el: &web_sys::Element,
    attr_name: &str,
    value: Attribute,
    force: bool,
) {
    use crate::HydrationCtx;

    if force || !HydrationCtx::is_hydrating() {
        match value {
            Attribute::String(value) => {
                let value = wasm_bindgen::intern(&value);
                if attr_name == "inner_html" {
                    el.set_inner_html(value);
                } else {
                    let attr_name = wasm_bindgen::intern(attr_name);
                    el.set_attribute(attr_name, value).unwrap_throw();
                }
            }
            Attribute::Option(_, value) => {
                if attr_name == "inner_html" {
                    el.set_inner_html(&value.unwrap_or_default());
                } else {
                    let attr_name = wasm_bindgen::intern(attr_name);
                    match value {
                        Some(value) => {
                            let value = wasm_bindgen::intern(&value);
                            el.set_attribute(attr_name, value).unwrap_throw();
                        }
                        None => el.remove_attribute(attr_name).unwrap_throw(),
                    }
                }
            }
            Attribute::Bool(value) => {
                let attr_name = wasm_bindgen::intern(attr_name);
                if value {
                    el.set_attribute(attr_name, attr_name).unwrap_throw();
                } else {
                    el.remove_attribute(attr_name).unwrap_throw();
                }
            }
            _ => panic!("Remove nested Fn in Attribute"),
        }
    }
}