Skip to main content

elvis_web/
page.rs

1use crate::{node, StyleSheet};
2use elvis_core::Node;
3use std::{cell::RefCell, convert::Into, rc::Rc};
4use wasm_bindgen::prelude::*;
5
6/// basic widget without lifecycle nor state
7#[wasm_bindgen]
8#[derive(Clone, Debug, Default)]
9pub struct Page {
10    tree: Node,
11    style: Rc<RefCell<StyleSheet>>,
12}
13
14impl<N> From<N> for Page
15where
16    N: Into<Node>,
17{
18    fn from(n: N) -> Page {
19        let mut node: Node = n.into();
20        node.idx(&mut vec![]);
21        Page {
22            tree: node,
23            style: Rc::new(RefCell::new(StyleSheet::default())),
24        }
25    }
26}
27
28impl Page {
29    /// Render into body element
30    pub fn calling(&mut self) -> Result<(), JsValue> {
31        let window = web_sys::window().unwrap();
32        let dom = window.document().unwrap();
33
34        // set style
35        StyleSheet::shared()?;
36        self.style()?;
37
38        // set body
39        let body = dom.query_selector("body")?.unwrap();
40        body.set_inner_html("");
41        body.append_child(
42            &node::to_element(&Rc::new(RefCell::new(self.tree.clone())), &dom)?.into(),
43        )?;
44
45        Ok(())
46    }
47
48    /// Shoud update style
49    fn style(&mut self) -> Result<bool, JsValue> {
50        self.style.borrow_mut().batch(&mut self.tree);
51        Ok(self.style.borrow().ser(self.tree.attr.id.to_string())?)
52    }
53}