dioxus_web_component/
style.rs

1use std::borrow::Cow;
2
3use wasm_bindgen::UnwrapThrowExt as _;
4use web_sys::{Document, ShadowRoot};
5
6/// Provide style to the web component
7///
8/// Typical usage:
9///
10/// ```rust, ignore
11/// use dioxus_web_component::InjectedStyle;
12///
13/// const STYLE: InjectedStyle = InjectedStyle::css(include_str!("../style.css"));
14/// ```
15#[derive(Debug, Clone, Default)]
16pub enum InjectedStyle {
17    /// No style provided
18    #[default]
19    None,
20    /// Raw CSS content to go in an HTML `<style>`
21    Css(Cow<'static, str>),
22    /// Url containing the stylesheet to go in an HTML `<link rel="stylesheet" href="...">`
23    Stylesheet(Cow<'static, str>),
24    /// Multiple styles
25    Multiple(Vec<InjectedStyle>),
26}
27
28impl InjectedStyle {
29    /// Build with a static CSS code
30    #[must_use]
31    pub const fn css(css: &'static str) -> Self {
32        Self::Css(Cow::Borrowed(css))
33    }
34
35    /// Build with a static path to a stylesheet, e.g. an URL
36    #[must_use]
37    pub const fn stylesheet(url: &'static str) -> Self {
38        Self::Stylesheet(Cow::Borrowed(url))
39    }
40
41    pub(crate) fn inject(&self, document: &Document, root: &ShadowRoot) {
42        match self {
43            Self::None => {}
44            Self::Css(css) => {
45                let style_el = document.create_element("style").unwrap_throw();
46                style_el.set_inner_html(css);
47                root.append_child(&style_el).unwrap_throw();
48            }
49            Self::Stylesheet(url) => {
50                let link_el = document.create_element("link").unwrap_throw();
51                link_el.set_attribute("rel", "stylesheet").unwrap_throw();
52                link_el.set_attribute("href", url).unwrap_throw();
53                root.append_child(&link_el).unwrap_throw();
54            }
55            Self::Multiple(styles) => {
56                for style in styles {
57                    style.inject(document, root);
58                }
59            }
60        }
61    }
62}