use wasm_bindgen::{JsCast, JsValue};
use yew::prelude::*;
use super::surface_sheet;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum StyleSurface {
#[default]
Viewer,
ColumnDropdown,
FilterDropdown,
FunctionDropdown,
DropdownMenu,
}
#[derive(Properties, PartialEq)]
pub struct StyleProviderProps {
pub root: web_sys::HtmlElement,
#[prop_or(true)]
pub is_shadow: bool,
#[prop_or_default]
pub surface: StyleSurface,
pub children: Children,
}
pub struct StyleProvider;
impl Component for StyleProvider {
type Message = ();
type Properties = StyleProviderProps;
fn create(ctx: &Context<Self>) -> Self {
adopt_surface_sheet(ctx.props());
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! { <>{ for ctx.props().children.iter() }</> }
}
}
fn adopt_surface_sheet(props: &StyleProviderProps) {
let root: JsValue = if props.is_shadow {
props.root.shadow_root().unwrap().into()
} else {
web_sys::window().unwrap().document().unwrap().into()
};
let sheets = js_sys::Reflect::get(&root, &"adoptedStyleSheets".into())
.unwrap()
.unchecked_into::<js_sys::Array>();
let sheet = surface_sheet(props.surface);
let sheet_val: &JsValue = sheet.as_ref();
if sheets.index_of(sheet_val, 0) < 0 {
sheets.push(sheet_val);
}
}