feature: add class prop to <Html/> component (#554)

This commit is contained in:
PolarMutex 2023-02-21 12:28:11 -05:00 committed by GitHub
parent bf246a62e7
commit f7d0eea04d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -8,18 +8,37 @@ use std::{cell::RefCell, rc::Rc};
pub struct HtmlContext {
lang: Rc<RefCell<Option<TextProp>>>,
dir: Rc<RefCell<Option<TextProp>>>,
class: Rc<RefCell<Option<TextProp>>>,
}
impl HtmlContext {
/// Converts the `<html>` metadata into an HTML string.
pub fn as_string(&self) -> Option<String> {
match (self.lang.borrow().as_ref(), self.dir.borrow().as_ref()) {
(None, None) => None,
(Some(lang), None) => Some(format!(" lang=\"{}\"", lang.get())),
(None, Some(dir)) => Some(format!(" dir=\"{}\"", dir.get())),
(Some(lang), Some(dir)) => {
Some(format!(" lang=\"{}\" dir=\"{}\"", lang.get(), dir.get()))
}
let lang = self
.lang
.borrow()
.as_ref()
.map(|val| format!("lang=\"{}\"", val.get()));
let dir = self
.dir
.borrow()
.as_ref()
.map(|val| format!("dir=\"{}\"", val.get()));
let class = self
.class
.borrow()
.as_ref()
.map(|val| format!("class=\"{}\"", val.get()));
let mut val = [lang, dir, class]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join(" ");
if val.is_empty() {
None
} else {
val.insert(0, ' ');
Some(val)
}
}
}
@ -57,6 +76,9 @@ pub fn Html(
/// The `dir` attribute on the `<html>`.
#[prop(optional, into)]
dir: Option<TextProp>,
/// The `class` attribute on the `<html>`.
#[prop(optional, into)]
class: Option<TextProp>,
) -> impl IntoView {
cfg_if! {
if #[cfg(any(feature = "csr", feature = "hydrate"))] {
@ -71,15 +93,24 @@ pub fn Html(
}
if let Some(dir) = dir {
let el = el.clone();
create_render_effect(cx, move |_| {
let value = dir.get();
_ = el.set_attribute("dir", &value);
});
}
if let Some(class) = class {
create_render_effect(cx, move |_| {
let value = class.get();
_ = el.set_attribute("class", &value);
});
}
} else {
let meta = crate::use_head(cx);
*meta.html.lang.borrow_mut() = lang;
*meta.html.dir.borrow_mut() = dir;
*meta.html.class.borrow_mut() = class;
}
}
}