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
//! Internal DOM manipulation utilities. Generated by the `template!` macro. Should not be used directly.
//! Internal APIs can be changed at any time without a major release.

use std::cell::RefCell;
use std::rc::Rc;

use wasm_bindgen::{prelude::*, JsCast};
use web_sys::{DocumentFragment, Element, Event, Node};

use crate::prelude::*;

/// Create a new [`HtmlElement`] with the specified tag.
pub fn element(tag: &str) -> Element {
    web_sys::window()
        .unwrap()
        .document()
        .unwrap()
        .create_element(tag)
        .unwrap()
        .dyn_into()
        .unwrap()
}

pub fn fragment() -> DocumentFragment {
    web_sys::window()
        .unwrap()
        .document()
        .unwrap()
        .create_document_fragment()
}

/// Create a new [`Text`] with the specified content.
pub fn text(value: impl Fn() -> String + 'static) -> Node {
    let text_node = web_sys::window()
        .unwrap()
        .document()
        .unwrap()
        .create_text_node("" /* placeholder */);

    create_effect({
        let text_node = text_node.clone();
        move || {
            text_node.set_text_content(Some(&value()));
        }
    });

    text_node.into()
}

/// Sets an attribute on an [`Element`].
pub fn attr(element: &Element, name: &str, value: impl Fn() -> String + 'static) {
    let element = element.clone();
    let name = name.to_string();
    create_effect(move || {
        element.set_attribute(&name, &value()).unwrap();
    })
}

type EventListener = dyn Fn(Event);

thread_local! {
    /// A global event listener pool to prevent [`Closure`]s from being deallocated.
    /// TODO: remove events when elements are detached.
    static EVENT_LISTENERS: RefCell<Vec<Closure<EventListener>>> = RefCell::new(Vec::new());
}

/// Sets an event listener on an [`Element`].
pub fn event(element: &Element, name: &str, handler: Box<EventListener>) {
    let closure = Closure::wrap(handler);
    element
        .add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())
        .unwrap();

    EVENT_LISTENERS.with(|event_listeners| event_listeners.borrow_mut().push(closure));
}

/// Appends a child node to an element.
pub fn append(element: &impl AsRef<Node>, child: &impl AsRef<Node>) {
    element.as_ref().append_child(child.as_ref()).unwrap();
}

/// Appends a [`dyn Render`](Render) to the `parent` node.
/// Node is created inside an effect.
pub fn append_render(parent: &impl AsRef<Node>, child: Box<dyn Fn() -> Box<dyn Render>>) {
    let node = create_effect_initial(move || {
        let node = RefCell::new(child().render());

        let effect = cloned!((node) => move || {
            let new_node = child().render();
            node.borrow().parent_element().unwrap().replace_child(&new_node, &node.borrow()).unwrap();

            *node.borrow_mut() = new_node;
        });

        (Rc::new(effect), node)
    });

    parent.as_ref().append_child(&node.borrow()).unwrap();
}