use super::Props;
use crate::{
Callback, create_element, hooks::JsRefContainer, KeyType, VNode,
};
use std::borrow::Cow;
use wasm_bindgen::{
convert::{FromWasmAbi, IntoWasmAbi},
intern, JsValue,
};
use web_sys::Element;
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct HtmlTag<'a>(pub &'a str);
impl AsRef<str> for HtmlTag<'_> {
fn as_ref(&self) -> &str {
&self.0
}
}
pub trait HType {
fn as_js(&self) -> Cow<'_, JsValue>;
}
impl HType for HtmlTag<'_> {
fn as_js(&self) -> Cow<'_, JsValue> {
Cow::Owned(intern(self.0).into())
}
}
#[derive(Debug, Clone)]
pub struct H<T> {
pub(crate) typ: T,
pub(crate) props: Props,
}
impl<T: HType> H<T> {
pub fn new(typ: T) -> Self {
Self {
typ,
props: Props::new(),
}
}
pub fn key(mut self, value: Option<impl KeyType>) -> Self {
self.props = self.props.key(value);
self
}
pub fn ref_container(
mut self,
ref_container: &JsRefContainer<Element>,
) -> Self {
self.props = self.props.ref_container(ref_container);
self
}
pub fn ref_callback(
mut self,
ref_callback: &Callback<Option<Element>>,
) -> Self {
self.props = self.props.ref_callback(ref_callback);
self
}
pub fn attr(mut self, key: &str, value: &JsValue) -> Self {
self.props = self.props.insert(key, value);
self
}
pub fn attr_callback<U, V>(mut self, key: &str, f: &Callback<U, V>) -> Self
where
U: FromWasmAbi + 'static,
V: IntoWasmAbi + 'static,
{
self.props = self.props.insert_callback(key, f);
self
}
pub fn build(self, children: impl Into<VNode>) -> VNode {
create_element(&self.typ.as_js(), &self.props, children.into())
}
}