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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use web_sys::Node;

use crate::{
    component::{node::AnyComponentNode, Component},
    utils::debug,
};

use std::{
    any::{Any, TypeId},
    cell::RefCell,
    collections::hash_map::DefaultHasher,
    fmt,
    hash::{Hash, Hasher},
    rc::Rc,
};

use super::VNode;

pub(crate) type PropertiesHash = u64;
pub(crate) type AnyProps = Option<Box<dyn Any>>;
pub(crate) type ComponentNodeGenerator =
    Box<dyn Fn(AnyProps, &Node) -> Rc<RefCell<AnyComponentNode>> + 'static>;

/// Special VNode type, which represents custom component node.
/// There is no direct translation of [VComponent] to a single DOM node, but it translates to a subtree of DOM nodes.
pub struct VComponent {
    props: AnyProps,
    hash: PropertiesHash,
    generator: ComponentNodeGenerator,
    key: Option<String>,
    depth: Option<u32>,

    pub(crate) comp: Option<Rc<RefCell<AnyComponentNode>>>,
}

impl VComponent {
    /// Creates [VComponent] out of provided properties. Function is generic, therefore type of [Component] ***C*** has to be specified.
    ///
    /// # Examples
    ///
    /// ```
    /// struct ExampleComponent;
    /// impl Component for ExampleComponent {
    ///     type Properties = ();
    ///     ...
    /// }
    /// let props = ();
    /// let vcomp = VComponent::new::<ExampleComponent>(props, None);
    /// ```
    pub fn new<C>(props: C::Properties, key: Option<String>) -> VComponent
    where
        C: Component + 'static,
    {
        let hash = Self::calculate_hash::<C>(&props);
        let generator = Box::new(Self::generator::<C>);
        VComponent {
            props: Some(Box::new(props)),
            generator,
            hash,
            key,
            depth: None,
            comp: None,
        }
    }

    fn calculate_hash<C>(props: &C::Properties) -> PropertiesHash
    where
        C: Component + 'static,
    {
        let mut hasher = DefaultHasher::new();
        props.hash(&mut hasher);
        TypeId::of::<C>().hash(&mut hasher);
        hasher.finish()
    }

    fn generator<C: Component + 'static>(
        props: AnyProps,
        ancestor: &Node,
    ) -> Rc<RefCell<AnyComponentNode>> {
        let props = props
            .unwrap()
            .downcast::<C::Properties>()
            .expect("Trying to unpack others component props");

        AnyComponentNode::new(C::new(*props), ancestor.clone())
    }

    pub(crate) fn patch(&mut self, last: Option<VNode>, ancestor: &Node) {
        debug::log("Patching component");
        let mut old_virt: Option<VComponent> = None;

        match last {
            Some(VNode::Component(vcomp)) => {
                debug::log("\tComparing two components");
                old_virt = Some(vcomp);
            }
            Some(VNode::Element(v)) => {
                debug::log("\tNew component over element");
                v.erase();
            }
            Some(VNode::Text(v)) => {
                debug::log("\tNew component over text");
                v.erase();
            }
            None => {
                debug::log("\tCreating the comp for the first time");
            }
            Some(VNode::List(v)) => {
                debug::log("\tNew component over list");
                v.erase();
            }
        }

        self.render(old_virt, ancestor);
    }

    pub(crate) fn erase(&self) {
        if let Some(node) = self.comp.as_ref() {
            debug::log("Erasing vcomponent");
            node.borrow_mut().vdom.as_ref().unwrap().erase();
        }
    }

    pub(crate) fn set_depth(&mut self, depth: u32) {
        debug::log(format!("VComponent: Setting depth: {depth}"));
        self.depth = Some(depth);
    }

    fn render(&mut self, last: Option<VComponent>, ancestor: &Node) {
        match last {
            Some(mut old_vcomp) if self.key.is_some() && old_vcomp.key == self.key => {
                debug::log("\t\tKeys are equal");
                self.comp = old_vcomp.comp.take();
            }
            Some(mut old_vcomp) if old_vcomp.hash == self.hash => {
                debug::log("\t\tHashes are equal");
                self.comp = old_vcomp.comp.take();
            }
            Some(old_vcomp) => {
                debug::log("\t\tHashes differ");
                let any_component_node_rc = (self.generator)(self.props.take(), ancestor);
                {
                    let mut any_component_node = any_component_node_rc.borrow_mut();
                    any_component_node.depth = self.depth;
                    any_component_node.view();
                    any_component_node.patch(old_vcomp.comp.clone(), ancestor);
                }
                self.comp = Some(any_component_node_rc);
            }
            None => {
                debug::log("\t\tThere was no component before");
                let any_component_node_rc = (self.generator)(self.props.take(), ancestor);
                {
                    let mut any_component_node = any_component_node_rc.borrow_mut();
                    any_component_node.depth = self.depth;
                    any_component_node.view();
                    any_component_node.patch(None, ancestor);
                }
                self.comp = Some(any_component_node_rc);
            }
        }
    }
}

impl fmt::Debug for VComponent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VComponent")
            .field("props", &self.props)
            .field("hash", &self.hash)
            .field("comp", &self.comp)
            .finish()
    }
}

impl PartialEq for VComponent {
    fn eq(&self, other: &Self) -> bool {
        self.hash == other.hash
            && match (&self.props, &other.props) {
                (Some(self_props), Some(other_props)) => {
                    (*(*self_props)).type_id() == (*(*other_props)).type_id()
                }
                (None, None) => true,
                _ => false,
            }
    }
}

#[cfg(test)]
mod tests {
    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::{
        component::{behavior::Behavior, Component},
        virtual_dom::{dom, VElement, VList, VNode, VText},
    };

    use super::VComponent;
    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);

    macro_rules! function_name {
        () => {{
            fn f() {}
            fn type_name_of<T>(_: T) -> &'static str {
                std::any::type_name::<T>()
            }
            let name = type_name_of(f);
            name.strip_suffix("::f").unwrap()
        }};
    }

    const VALID_TEXT: &str = "";

    struct Tmp;
    impl Component for Tmp {
        type Message = ();
        type Properties = ();

        fn new(_props: Self::Properties) -> Self {
            Tmp
        }
        fn view(&self, _behavior: &mut impl Behavior<Self>) -> VNode {
            VElement::new(
                "div".into(),
                [(String::from("result"), String::from(VALID_TEXT))].into(),
                vec![],
                None,
                vec![],
            )
            .into()
        }
        fn update(&mut self, _message: Self::Message) -> bool {
            false
        }
    }

    #[wasm_bindgen_test]
    fn patch_last_none() {
        let ancestor = dom::create_element("div");
        dom::set_attribute(&ancestor, "id", function_name!());
        dom::append_child(&dom::get_root_element(), &ancestor);

        let mut target = VComponent::new::<Tmp>((), None);
        target.set_depth(0);
        target.patch(None, &ancestor);
    }

    #[wasm_bindgen_test]
    fn patch_last_text() {
        let ancestor = dom::create_element("div");
        dom::set_attribute(&ancestor, "id", function_name!());

        let current = dom::create_text_node("I dont love Rust");
        dom::append_child(&ancestor, &current);

        dom::append_child(&dom::get_root_element(), &ancestor);

        let text = VNode::Text(VText {
            text: "I dont love Rust".into(),
            dom: Some(current),
        });

        let mut target = VComponent::new::<Tmp>((), None);
        target.set_depth(0);
        target.patch(Some(text), &ancestor);
    }

    #[wasm_bindgen_test]
    fn patch_last_elem() {
        let ancestor = dom::create_element("div");
        dom::set_attribute(&ancestor, "id", function_name!());

        let current = dom::create_element("div");
        dom::set_attribute(&current, "id", "I dont love Rust");
        dom::append_child(&ancestor, &current);

        dom::append_child(&dom::get_root_element(), &ancestor);

        let elem = VNode::Element(VElement {
            tag_name: "div".into(),
            attr: [("id".into(), "I dont love Rust".into())].into(),
            event_handlers: vec![],
            key: None,
            children: vec![],
            dom: Some(current),
        });

        let mut target = VComponent::new::<Tmp>((), None);
        target.set_depth(0);
        target.patch(Some(elem), &ancestor);
    }

    struct Comp;
    impl Component for Comp {
        type Message = ();
        type Properties = ();

        fn new(_props: Self::Properties) -> Self {
            Comp
        }
        fn view(&self, _behavior: &mut impl Behavior<Self>) -> VNode {
            VElement::new(
                "div".into(),
                [(String::from("result"), String::from("I dont love Rust"))].into(),
                vec![],
                None,
                vec![],
            )
            .into()
        }
        fn update(&mut self, _message: Self::Message) -> bool {
            false
        }
    }

    #[wasm_bindgen_test]
    fn patch_last_comp_diff_keys() {
        let ancestor = dom::create_element("div");
        dom::set_attribute(&ancestor, "id", function_name!());
        dom::append_child(&dom::get_root_element(), &ancestor);

        let mut comp = VNode::Component(VComponent::new::<Comp>((), None));
        comp.set_depth(0);
        comp.patch(None, &ancestor);

        let mut target = VComponent::new::<Tmp>((), None);
        target.set_depth(0);
        target.patch(Some(comp), &ancestor);
    }

    #[wasm_bindgen_test]
    fn patch_last_comp_same_keys() {
        let ancestor = dom::create_element("div");
        dom::set_attribute(&ancestor, "id", function_name!());
        dom::append_child(&dom::get_root_element(), &ancestor);

        let key = Some(String::from("Same_key"));
        let mut comp = VNode::Component(VComponent::new::<Comp>((), key.clone()));
        comp.set_depth(0);
        comp.patch(None, &ancestor);

        let mut target = VComponent::new::<Tmp>((), key);
        target.set_depth(0);
        target.patch(Some(comp), &ancestor);
    }

    #[wasm_bindgen_test]
    fn patch_last_list() {
        let ancestor = dom::create_element("div");
        dom::set_attribute(&ancestor, "id", function_name!());
        dom::append_child(&dom::get_root_element(), &ancestor);

        let mut list = VNode::List(VList::new(
            vec![VText::new("I dont love Rust").into()],
            None,
        ));
        list.set_depth(0);
        list.patch(None, &ancestor);

        let mut target = VComponent::new::<Tmp>((), None);
        target.set_depth(0);
        target.patch(Some(list), &ancestor);
    }
}