css_in_rs/backend/
web.rs

1use wasm_bindgen::JsCast;
2
3use crate::Theme;
4
5use super::{Backend, CssGeneratorFn};
6
7pub struct WebSysBackend {
8    current_style: String,
9    styles: web_sys::Element,
10}
11
12impl WebSysBackend {
13    pub fn quickstart() -> Self {
14        let document = web_sys::window().unwrap().document().unwrap();
15        Self::new_and_mount_in_root(&document)
16    }
17
18    pub fn new_and_mount_in_root(root: &web_sys::Node) -> Self {
19        let styles = if let Some(doc) = root.dyn_ref::<web_sys::Document>() {
20            let head = doc.head().unwrap();
21            let styles = doc.create_element("style").unwrap();
22            head.append_child(&styles).unwrap();
23            styles
24        } else {
25            panic!("This is most likely a shadow root. Not supported yet");
26        };
27
28        Self {
29            styles,
30            current_style: Default::default(),
31        }
32    }
33}
34
35impl<T: Theme> Backend<T> for WebSysBackend {
36    fn replace_all(&mut self, css: String) {
37        self.current_style = css;
38        self.styles.set_text_content(Some(&self.current_style));
39    }
40
41    fn run_css_generator(&mut self, generator: CssGeneratorFn<T>, theme: &T, counter: &mut u64) {
42        // TODO: There is probably a much faster way than to append this style this way
43        (generator)(theme, &mut self.current_style, counter);
44        self.styles.set_text_content(Some(&self.current_style));
45    }
46}