domrs/html/body.rs
1use crate::HtmlElement;
2use std::fmt;
3use std::fmt::Display;
4
5/// A structure representing HTML `<body>` element.
6#[derive(Debug, Default, Clone)]
7pub struct HtmlBodyElement {
8 children: Vec<HtmlElement>,
9}
10
11impl HtmlBodyElement {
12 /// Creates new body element.
13 ///
14 /// # Example
15 ///
16 /// ```
17 /// # use domrs::HtmlBodyElement;
18 /// let body = HtmlBodyElement::new();
19 /// assert_eq!("<body/>", body.to_string());
20 /// ```
21 pub fn new() -> Self {
22 Self::default()
23 }
24
25 /// Adds child element into body element.
26 ///
27 /// ```
28 /// # use domrs::{HtmlBodyElement, HtmlElement};
29 /// let h1 = HtmlElement::h1("hello");
30 /// let body = HtmlBodyElement::new().child(h1);
31 /// assert_eq!("<body>\n <h1>hello</h1>\n</body>", body.to_string());
32 /// ```
33 pub fn child(mut self, child: impl Into<HtmlElement>) -> Self {
34 self.add_child(child);
35 self
36 }
37
38 /// Adds child element into body element.
39 ///
40 /// ```
41 /// # use domrs::{HtmlBodyElement, HtmlElement};
42 /// let h1 = HtmlElement::h1("hello");
43 /// let mut body = HtmlBodyElement::new();
44 /// body.add_child(h1);
45 /// assert_eq!("<body>\n <h1>hello</h1>\n</body>", body.to_string());
46 /// ```
47 pub fn add_child(&mut self, child: impl Into<HtmlElement>) {
48 self.children.push(child.into());
49 }
50}
51
52impl Display for HtmlBodyElement {
53 /// Implements [Display] for [HtmlBodyElement].
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 write!(f, "{}", <&HtmlBodyElement as Into<HtmlElement>>::into(self))
56 }
57}
58
59impl From<HtmlBodyElement> for HtmlElement {
60 /// Converts [HtmlBodyElement] into [HtmlElement].
61 fn from(value: HtmlBodyElement) -> Self {
62 let mut body = HtmlElement::new("body").no_indent();
63 for child in value.children {
64 body.add_child(child);
65 }
66 body
67 }
68}
69
70impl From<&HtmlBodyElement> for HtmlElement {
71 /// Converts a reference to [HtmlBodyElement] into [HtmlElement].
72 fn from(value: &HtmlBodyElement) -> Self {
73 Self::from(value.clone())
74 }
75}