wal_core/virtual_dom/
mod.rs

1pub mod vcomponent;
2pub mod velement;
3pub mod vlist;
4pub mod vnode;
5pub mod vtext;
6
7pub use self::vcomponent::VComponent;
8pub use self::velement::VElement;
9pub use self::vlist::VList;
10pub use self::vnode::VNode;
11pub use self::vtext::VText;
12
13pub(crate) mod dom {
14    use std::borrow::Cow;
15
16    use gloo::events::EventListener;
17    use gloo::utils::{body, document};
18    use web_sys::{Element, Event, Node, Text};
19
20    pub const ROOT_ELEMENT_ID: &str = "walrust-root";
21
22    pub fn get_root_element() -> Node {
23        Node::from(
24            document()
25                .get_element_by_id(ROOT_ELEMENT_ID)
26                .unwrap_or_else(|| {
27                    let root = document().create_element("div").unwrap();
28                    set_attribute(&root, "id", ROOT_ELEMENT_ID);
29                    append_child(&body(), &root);
30                    root
31                }),
32        )
33    }
34
35    pub fn create_element(local_name: &str) -> Element {
36        document()
37            .create_element(local_name)
38            .expect("Couldnt create new element")
39    }
40
41    pub fn create_text_node(data: &str) -> Text {
42        document().create_text_node(data)
43    }
44
45    pub fn remove_node(node: &Node) {
46        let ancestor = node.parent_node().expect("Node does not have a parent");
47        self::remove_child(&ancestor, node);
48    }
49
50    pub fn append_child(ancestor: &Node, child: &Node) -> Node {
51        ancestor
52            .append_child(child)
53            .expect("Couldnt append child to node")
54    }
55
56    pub fn replace_child(ancestor: &Node, old_child: &Node, child: &Node) -> Node {
57        ancestor
58            .replace_child(child, old_child)
59            .expect("Couldnt replace child with a new node")
60    }
61
62    pub fn remove_child(ancestor: &Node, child: &Node) -> Node {
63        ancestor.remove_child(child).expect("Couldnt remove child")
64    }
65
66    pub fn set_attribute(el: &Element, name: &str, value: &str) {
67        el.set_attribute(name, value)
68            .expect("Couldnt set attribute")
69    }
70
71    pub fn remove_attribute(el: &Element, name: &str) {
72        el.remove_attribute(name).expect("Couldnt remove attribute")
73    }
74
75    pub fn create_event_listener<F>(
76        element: &Element,
77        event_type: Cow<'static, str>,
78        callback: F,
79    ) -> EventListener
80    where
81        F: FnMut(&Event) + 'static,
82    {
83        EventListener::new(element, event_type, callback)
84    }
85}