1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//! This module contains information about containers and container types

use crate::attributes::Attributes;
use crate::html_container::HtmlContainer;
use crate::Html;
use std::fmt::{self, Display};

/// The different types of HTML containers that can be added to the page
#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
#[non_exhaustive]
pub enum ContainerType {
    /// Corresponds to `<address>` tags
    Address,
    /// Corresponds to `<article>` tags
    Article,
    /// Corresponds to `<div>` tags
    ///
    /// This type is also the default for `Container`s
    #[default]
    Div,
    /// Corresponds to `<footer>` tags
    Footer,
    /// Corresponds to `<header>` tags
    Header,
    /// Corresponds to `<main>` tags
    Main,
    /// Corresponds to `<ol>` tags
    OrderedList,
    /// Corresponds to `<ul>` tags
    UnorderedList,
    /// Corresponts to `<nav>` tags
    Nav,
    /// Corresponts to `<section>` tags
    Section,
}

impl Display for ContainerType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Address => write!(f, "address"),
            Self::Article => write!(f, "article"),
            Self::Div => write!(f, "div"),
            Self::Footer => write!(f, "footer"),
            Self::Header => write!(f, "header"),
            Self::Main => write!(f, "main"),
            Self::OrderedList => write!(f, "ol"),
            Self::UnorderedList => write!(f, "ul"),
            Self::Nav => write!(f, "nav"),
            Self::Section => write!(f, "section"),
        }
    }
}

/// A container for HTML elements.
///
/// As the name would suggest, a `Container` contains other HTML elements. This struct guarantees
/// that the elements added will be converted to HTML strings in the same order as they were
/// added.
///
/// Supported container types are provided by the [`ContainerType`] enum.
///
/// Note that `Container` elements can be nested inside of each other.
/// ```rust
/// # use build_html::*;
/// let text = Container::new(ContainerType::Main)
///     .with_header(1, "My Container")
///     .with_container(
///         Container::new(ContainerType::Article)
///             .with_container(
///                 Container::new(ContainerType::Div)
///                     .with_paragraph("Inner Text")
///             )
///     )
///     .to_html_string();
///
/// assert_eq!(
///     text,
///     "<main><h1>My Container</h1><article><div><p>Inner Text</p></div></article></main>"
/// );
/// ```
#[derive(Debug, Default)]
pub struct Container {
    tag: ContainerType,
    elements: String,
    attr: Attributes,
}

impl Html for Container {
    fn to_html_string(&self) -> String {
        format!(
            "<{tag}{attr}>{content}</{tag}>",
            tag = self.tag,
            attr = self.attr,
            content = self.elements,
        )
    }
}

impl HtmlContainer for Container {
    #[inline]
    fn add_html<H: Html>(&mut self, content: H) {
        match self.tag {
            ContainerType::OrderedList | ContainerType::UnorderedList => {
                self.elements.push_str("<li>");
                self.elements.push_str(content.to_html_string().as_str());
                self.elements.push_str("</li>");
            }
            _ => self.elements.push_str(content.to_html_string().as_str()),
        };
    }
}

impl Container {
    /// Creates a new container with the specified tag.
    pub fn new(tag: ContainerType) -> Self {
        Container {
            tag,
            elements: String::new(),
            attr: Attributes::default(),
        }
    }

    /// Associates the specified map of attributes with this Container.
    ///
    /// Note that this operation overrides all previous `with_attribute` calls on
    /// this `Container`
    ///
    /// # Example
    /// ```
    /// # use build_html::*;
    /// let container = Container::default()
    ///     .with_attributes(vec![("class", "defaults")])
    ///     .with_paragraph("text")
    ///     .to_html_string();
    ///
    /// assert_eq!(container, r#"<div class="defaults"><p>text</p></div>"#)
    /// ```
    pub fn with_attributes<A, S>(mut self, attributes: A) -> Self
    where
        A: IntoIterator<Item = (S, S)>,
        S: ToString,
    {
        self.attr = Attributes::from(attributes);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_case::test_case;

    #[test_case(ContainerType::Article; "article")]
    #[test_case(ContainerType::Div; "div")]
    #[test_case(ContainerType::Main; "main")]
    fn test_content(container_type: ContainerType) {
        // Expected
        let content = concat!(
            r#"<h1 id="main-header">header</h1>"#,
            r#"<img src="myimage.png" alt="test image">"#,
            r#"<a href="rust-lang.org">Rust Home</a>"#,
            r#"<p class="red-text">Sample Text</p>"#,
            r#"<pre class="code">Text</pre>"#
        );

        // Act
        let sut = Container::new(container_type)
            .with_header_attr(1, "header", [("id", "main-header")])
            .with_image("myimage.png", "test image")
            .with_link("rust-lang.org", "Rust Home")
            .with_paragraph_attr("Sample Text", [("class", "red-text")])
            .with_preformatted_attr("Text", [("class", "code")]);

        // Assert
        assert_eq!(
            sut.to_html_string(),
            format!(
                "<{tag}>{content}</{tag}>",
                tag = container_type,
                content = content
            )
        )
    }

    #[test_case(ContainerType::OrderedList; "ordered_list")]
    #[test_case(ContainerType::UnorderedList; "unordered_list")]
    fn test_list(container_type: ContainerType) {
        // Expected
        let content = concat!(
            r#"<li><h1 id="main-header">header</h1></li>"#,
            r#"<li><img src="myimage.png" alt="test image"></li>"#,
            r#"<li><a href="rust-lang.org">Rust Home</a></li>"#,
            r#"<li><p class="red-text">Sample Text</p></li>"#,
            r#"<li><pre class="code">Text</pre></li>"#
        );

        // Act
        let sut = Container::new(container_type)
            .with_header_attr(1, "header", [("id", "main-header")])
            .with_image("myimage.png", "test image")
            .with_link("rust-lang.org", "Rust Home")
            .with_paragraph_attr("Sample Text", [("class", "red-text")])
            .with_preformatted_attr("Text", [("class", "code")]);

        // Assert
        assert_eq!(
            sut.to_html_string(),
            format!(
                "<{tag}>{content}</{tag}>",
                tag = container_type,
                content = content
            )
        )
    }

    #[test]
    fn test_nesting() {
        // Act
        let container = Container::new(ContainerType::Main)
            .with_paragraph("paragraph")
            .with_container(
                Container::new(ContainerType::OrderedList)
                    .with_container(Container::default().with_paragraph(1))
                    .with_container(Container::default().with_paragraph('2'))
                    .with_container(Container::default().with_paragraph("3")),
            )
            .with_paragraph("done");

        // Assert
        assert_eq!(
            container.to_html_string(),
            concat!(
                "<main><p>paragraph</p><ol>",
                "<li><div><p>1</p></div></li>",
                "<li><div><p>2</p></div></li>",
                "<li><div><p>3</p></div></li>",
                "</ol><p>done</p></main>"
            )
        )
    }
}