dioxus_web_component/
style.rs1use std::borrow::Cow;
2
3use wasm_bindgen::UnwrapThrowExt as _;
4use web_sys::{Document, ShadowRoot};
5
6#[derive(Debug, Clone, Default)]
16pub enum InjectedStyle {
17 #[default]
19 None,
20 Css(Cow<'static, str>),
22 Stylesheet(Cow<'static, str>),
24 Multiple(Vec<InjectedStyle>),
26}
27
28impl InjectedStyle {
29 #[must_use]
31 pub const fn css(css: &'static str) -> Self {
32 Self::Css(Cow::Borrowed(css))
33 }
34
35 #[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}