Add id to Body

This commit is contained in:
benwis 2024-04-14 14:33:11 -07:00
parent a2927d7f18
commit 5baa76603b
No known key found for this signature in database
GPG key ID: 09BAB549B9C92245

View file

@ -11,6 +11,8 @@ pub struct BodyContext {
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
class: Rc<RefCell<Option<TextProp>>>, class: Rc<RefCell<Option<TextProp>>>,
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
id: Rc<RefCell<Option<TextProp>>>,
#[cfg(feature = "ssr")]
attributes: Rc<RefCell<HashMap<&'static str, Attribute>>>, attributes: Rc<RefCell<HashMap<&'static str, Attribute>>>,
} }
@ -24,6 +26,13 @@ impl BodyContext {
leptos::leptos_dom::ssr::escape_attr(&val.get()) leptos::leptos_dom::ssr::escape_attr(&val.get())
) )
}); });
let id = self.id.borrow().as_ref().map(|val| {
format!(
"id=\"{}\"",
leptos::leptos_dom::ssr::escape_attr(&val.get())
)
});
let attributes = self.attributes.borrow(); let attributes = self.attributes.borrow();
let attributes = (!attributes.is_empty()).then(|| { let attributes = (!attributes.is_empty()).then(|| {
attributes attributes
@ -41,7 +50,7 @@ impl BodyContext {
.join(" ") .join(" ")
}); });
let mut val = [class, attributes] let mut val = [id, class, attributes]
.into_iter() .into_iter()
.flatten() .flatten()
.collect::<Vec<_>>() .collect::<Vec<_>>()
@ -92,6 +101,9 @@ pub fn Body(
/// The `class` attribute on the `<body>`. /// The `class` attribute on the `<body>`.
#[prop(optional, into)] #[prop(optional, into)]
class: Option<TextProp>, class: Option<TextProp>,
/// The `id` attribute on the `<body>`.
#[prop(optional, into)]
id: Option<TextProp>,
/// Arbitrary attributes to add to the `<body>` /// Arbitrary attributes to add to the `<body>`
#[prop(attrs)] #[prop(attrs)]
attributes: Vec<(&'static str, Attribute)>, attributes: Vec<(&'static str, Attribute)>,
@ -112,15 +124,27 @@ pub fn Body(
}); });
} }
if let Some(id) = id {
create_render_effect({
let el = el.clone();
move |_| {
let value = id.get();
_ = el.set_attribute("id", &value);
}
});
}
for (name, value) in attributes { for (name, value) in attributes {
leptos::leptos_dom::attribute_helper(el.unchecked_ref(), name.into(), value); leptos::leptos_dom::attribute_helper(el.unchecked_ref(), name.into(), value);
} }
} else if #[cfg(feature = "ssr")] { } else if #[cfg(feature = "ssr")] {
let meta = crate::use_head(); let meta = crate::use_head();
*meta.body.class.borrow_mut() = class; *meta.body.class.borrow_mut() = class;
*meta.body.id.borrow_mut() = id;
meta.body.attributes.borrow_mut().extend(attributes); meta.body.attributes.borrow_mut().extend(attributes);
} else { } else {
_ = class; _ = class;
_ = id;
_ = attributes; _ = attributes;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]