wal_css/
css.rs

1use std::{collections::HashMap, ops::Index};
2use web_sys::Element;
3
4/// Css struct allows to reference the stylesheet selectors from appended stylesheet
5/// inside the [rsx macro](../../wal_rsx/macro.rsx.html).
6///
7/// In order to referecne a selector from the stylesheet use the indexing operator with
8/// the name of the selector as an argument.
9///
10/// # Example usage
11/// ```
12/// use wal_css::css:Css;
13/// use wal_css::css_stylesheet;
14///
15/// thread_local! {
16///     static CSS: Css = css_stylesheet!("path-to-css-file");
17/// }
18/// // ...
19/// CSS.with(|css| {
20///     rsx! {
21///         <div class={format!("{} {}", css["class1"], css["class2"])} />
22///     }
23/// })
24/// ```
25pub struct Css {
26    stylesheet_id: u8,
27    element: Element,
28    selector_map: HashMap<String, String>,
29}
30#[allow(dead_code)]
31impl Css {
32    pub(crate) fn new(
33        stylesheet_id: u8,
34        element: Element,
35        selector_map: HashMap<String, String>,
36    ) -> Self {
37        Css {
38            stylesheet_id,
39            element,
40            selector_map,
41        }
42    }
43
44    pub(crate) fn get_id(&self) -> u8 {
45        self.stylesheet_id
46    }
47
48    pub(crate) fn get_inner_css(&self) -> String {
49        self.element.text_content().unwrap()
50    }
51}
52
53impl Index<&str> for Css {
54    type Output = String;
55    /// Indexing operator for accessing prepended selectors by original selector names
56    fn index(&self, index: &str) -> &Self::Output {
57        self.selector_map.get(index).unwrap_or_else(|| {
58            panic!(
59                "CSS selector {} is not defined in the given stylesheet",
60                index
61            )
62        })
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use std::collections::HashMap;
69
70    use super::Css;
71    use wasm_bindgen_test::*;
72    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
73
74    fn get_document() -> web_sys::Document {
75        web_sys::window().unwrap().document().unwrap()
76    }
77
78    #[wasm_bindgen_test]
79    fn indexing_operator_yields_result_if_entry_present() {
80        let mut selector_map = HashMap::new();
81        selector_map.insert("class1".to_owned(), "_1-class1".to_owned());
82
83        let element = get_document().create_element("style").unwrap();
84
85        let css = Css::new(1, element, selector_map);
86
87        assert_eq!(css["class1"], "_1-class1");
88    }
89
90    #[wasm_bindgen_test]
91    #[should_panic]
92    fn indexing_operator_panicst_if_entry_not_present() {
93        let mut selector_map = HashMap::new();
94        selector_map.insert("class1".to_owned(), "_1-class1".to_owned());
95
96        let element = get_document().create_element("style").unwrap();
97
98        let css = Css::new(1, element, selector_map);
99
100        let _x = &css["clas_not_included"];
101    }
102}