1use fenrix_core::create_effect;
2use std::cell::RefCell;
3use std::rc::Rc;
4use web_sys::{window, Document, Element, Node, Text};
5
6fn document() -> Document {
8 window()
9 .expect("should have a window")
10 .document()
11 .expect("window should have a document")
12}
13
14pub fn create_element(tag: &str) -> Element {
16 document()
17 .create_element(tag)
18 .expect("failed to create element")
19}
20
21pub fn create_text_node(text: &str) -> Text {
23 document().create_text_node(text)
24}
25
26pub fn append_child(parent: &Element, child: &Node) {
28 parent
29 .append_child(child)
30 .expect("failed to append child");
31}
32
33pub fn create_reactive_text_node(source: impl FnMut() -> String + 'static) -> Text {
40 let source = Rc::new(RefCell::new(source));
43
44 let initial_value = source.borrow_mut()();
46 let text_node = create_text_node(&initial_value);
47
48 let node_clone = text_node.clone();
50 create_effect({
51 let source = Rc::clone(&source);
52 move || {
53 let new_value = source.borrow_mut()();
55 node_clone.set_node_value(Some(&new_value));
56 }
57 });
58
59 text_node
60}
61
62pub fn render(root_node: Node) {
64 let body = document().body().expect("document should have a body");
65 body.append_child(&root_node)
66 .expect("failed to append to body");
67}