html_tag 0.1.3

An Enigmatic Way to use HTML in Rust
Documentation
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::fmt::Display;

use crate::{
    styles::{convert_to_styles, sanitize_styles, Class, Style, StyleSheet},
    tags::TagType,
};

/// A struct representing an HTML tag.
/// The concept of a HTML tag is represented using this
/// struct. It contains all the information needed to
/// construct a HTML string.
///
/// The heart of the crate, it contains all the necessary traits
/// and methods to construct a HTML string.
///
/// # Examples
///
/// ```
/// use html_tag::HtmlTag;
///
/// let mut a = HtmlTag::new("a");
/// a.set_body("Hello World");
/// a.add_class("test");
/// a.set_href("https://example.com");
///
/// assert_eq!(a.to_html(), "<a class=\"test\" href=\"https://example.com\">Hello World</a>");
///
/// ```
/// This also has a `Display` implementation, so you can
/// print it directly.
///
/// Moreover, the elements can be nested, like so:
///
/// ```
/// use html_tag::HtmlTag;
///
/// let mut div = HtmlTag::new("div");
/// div.add_class("test");
/// let mut p = HtmlTag::new("p");
/// p.set_body("Hello World");
/// div.add_child(p);
///
/// assert_eq!(div.to_html(), "<div class=\"test\"><p>Hello World</p></div>");
/// ```
///
/// Hence, you can scaffold a HTML element quite easily.
///
/// # Custom Tags
///
/// You can also use custom tags, like so:
///
/// ```
/// use html_tag::HtmlTag;
///
/// let mut custom = HtmlTag::new("custom");
/// custom.set_body("Hello World");
///
/// assert_eq!(custom.to_html(), "<custom>Hello World</custom>");
/// ```
///
/// Remember, all of these can be nested as well as modifies using
/// the methods provided.
#[derive(Clone, PartialEq, Eq)]
pub struct HtmlTag {
    pub pre_content: Option<String>,
    pub tag_type: TagType,
    pub class_names: Vec<String>,
    pub id: Option<String>,
    pub body: Option<String>,
    pub children: Option<Vec<HtmlTag>>,
    pub custom_attributes: Option<Vec<(String, String)>>,
}

impl HtmlTag {
    /// Creates a new `HtmlTag` with the given tag type.
    ///
    /// The tag type can be any valid HTML tag, or a custom tag.
    /// The crate is smart enough to handle both.
    ///
    /// This initializes the `HtmlTag` with the given tag type,
    /// although none of the other fields are initialized.
    /// Hence, all are set to `None` or empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use html_tag::HtmlTag;
    ///
    /// let mut a = HtmlTag::new("a");
    ///
    /// assert_eq!(a.to_html(), "<a></a>");
    /// ```
    ///
    /// Essentially a initializer for the struct.
    pub fn new(tag_type: &str) -> HtmlTag {
        HtmlTag {
            pre_content: None,
            tag_type: TagType::from(tag_type),
            class_names: Vec::new(),
            id: None,
            body: None,
            children: None,
            custom_attributes: None,
        }
    }

    /// Creates a new `HtmlTag` with the given tag type and body.
    ///
    /// This is a more pragmatic approach to creating a new `HtmlTag`.
    /// You specify the exact tag type, the body, and the class names.
    ///
    /// # Examples
    ///
    /// ```
    /// use html_tag::HtmlTag;
    /// use html_tag::TagType;
    ///
    /// let mut a = HtmlTag::fresh(TagType::A, Some("Hello World"), vec!["test"]);
    ///
    /// assert_eq!(a.to_html(), "<a class=\"test\">Hello World</a>");
    /// ```
    ///
    /// This is the most commonly used scaffold for creating a new `HtmlTag`.
    pub fn fresh(tag_type: TagType, body: Option<&str>, class_names: Vec<&str>) -> HtmlTag {
        HtmlTag {
            pre_content: None,
            tag_type,
            class_names: class_names.iter().map(|s| s.to_string()).collect(),
            id: None,
            body: body.map(|s| s.to_string()),
            children: None,
            custom_attributes: None,
        }
    }

    /// Adds a child of the type `HtmlTag` to the current `HtmlTag`.
    ///
    /// This is used to essentially nest HTML tags.
    ///
    /// # Examples
    ///
    /// ```
    /// use html_tag::HtmlTag;
    ///
    /// let mut div = HtmlTag::new("div");
    /// let mut p = HtmlTag::new("p");  
    /// p.set_body("Hello World");
    /// div.add_child(p);
    ///
    /// assert_eq!(div.to_html(), "<div><p>Hello World</p></div>");
    /// ```
    ///
    /// This needs a mutable reference to the current `HtmlTag`.
    pub fn add_child(&mut self, child: HtmlTag) {
        if let Some(children) = &mut self.children {
            children.push(child);
        } else {
            self.children = Some(vec![child]);
        }
    }

    /// Adds a class name to the current `HtmlTag`.
    pub fn add_class(&mut self, class_name: &str) {
        self.class_names.push(class_name.to_string());
    }

    /// Sets the body of the current `HtmlTag`.
    pub fn set_body(&mut self, body: &str) {
        self.body = Some(body.to_string());
    }

    /// Sets the id of the current `HtmlTag`.
    pub fn set_id(&mut self, id: &str) {
        self.id = Some(id.to_string());
    }

    /// Sets the href of the current `HtmlTag`.
    pub fn set_href(&mut self, href: &str) {
        self.add_attribute("href", href);
    }

    /// Sets the style of the current `HtmlTag`.
    pub fn set_style(&mut self, key: &str, value: &str) {
        self.add_attribute("style", &format!("{}: {};", key, value));
    }

    /// Construct and applies styles
    /// The Class struct is a HashMap<String, String>
    /// This is to represent the key-value pairs of the styles
    ///
    /// # Examples
    ///
    /// ```
    /// use html_tag::HtmlTag;
    /// use html_tag::styles::Class;
    ///
    /// let mut div = HtmlTag::new("div");
    /// let mut font_style = Class::new();
    /// font_style.insert("font-size".to_string(), "20px".to_string());
    /// font_style.insert("font-family".to_string(), "sans-serif".to_string());
    /// div.add_styles(font_style);
    ///
    /// assert_eq!(div.to_html(), "<div style=\"font-family: sans-serif;font-size: 20px;\"></div>");
    pub fn add_styles(&mut self, styles: Class) {
        self.add_attribute("style", convert_to_styles(styles).as_str());
    }

    /// Chaining method for add_styles
    pub fn with_styles(mut self, styles: Class) -> Self {
        self.add_styles(styles);
        self
    }

    /// Chaining method for add_class
    pub fn with_class(mut self, class_name: &str) -> Self {
        self.add_class(class_name);
        self
    }

    /// Chaining method for set_body
    pub fn with_body(mut self, body: &str) -> Self {
        self.set_body(body);
        self
    }

    /// Chaining method for set_id
    pub fn with_id(mut self, id: &str) -> Self {
        self.set_id(id);
        self
    }

    /// Chaining method for set_href
    pub fn with_href(mut self, href: &str) -> Self {
        self.set_href(href);
        self
    }

    /// Chaining method for set_style
    pub fn with_style(mut self, key: &str, value: &str) -> Self {
        self.set_style(key, value);
        self
    }

    /// Chaining method for add_child
    pub fn with_child(mut self, child: HtmlTag) -> Self {
        self.add_child(child);
        self
    }

    /// Chaining method for add_attribute
    pub fn with_attribute(mut self, key: &str, value: &str) -> Self {
        self.add_attribute(key, value);
        self
    }

    /// Sets the pre tag of the current `HtmlTag`.
    pub fn set_pre_content(&mut self, body: &str) {
        self.pre_content = Some(body.to_string());
    }

    /// Embed custom StyleSheet
    pub fn embed_style_sheet(mut self, style_sheet: &StyleSheet) -> Self {
        self.set_pre_content(sanitize_styles(style_sheet.get_with_tag()).as_str());
        self
    }

    fn get_tags(tag_type: &TagType) -> (String, String) {
        let tag = format!("<{}", tag_type.html());
        let closing_tag = format!("</{}>", tag_type.html());
        (tag, closing_tag)
    }

    fn partial_convert(&self) -> String {
        let mut html_to_return = if let Some(pre_tag) = &self.pre_content {
            pre_tag.to_string()
        } else {
            String::new()
        };
        let (opening_tag, _) = HtmlTag::get_tags(&self.tag_type);
        html_to_return.push_str(&opening_tag);

        if let Some(id) = &self.id {
            html_to_return.push_str(&format!(" id=\"{}\"", id));
        }

        if !self.class_names.is_empty() {
            html_to_return.push_str(&format!(" class=\"{}\"", self.class_names.join(" ")));
        }

        if let Some(custom_attributes) = &self.custom_attributes {
            for (key, value) in custom_attributes {
                html_to_return.push_str(&format!(" {}=\"{}\"", key, value));
            }
        }

        html_to_return
    }

    /// Adds an attribute to the current `HtmlTag`.
    /// This attribute can be a custom attribute, or a
    /// predefined attribute like `class` or `id`.
    ///
    /// # Examples
    ///
    /// ```
    /// use html_tag::HtmlTag;
    ///
    /// let mut div = HtmlTag::new("div");
    /// div.add_attribute("class", "test");
    /// div.add_attribute("id", "test");
    /// div.add_attribute("style", "color: red;");
    ///
    /// assert_eq!(div.to_html(), "<div id=\"test\" class=\"test\" style=\"color: red;\"></div>");
    /// ```
    ///
    /// This is used to add custom attributes as well.
    pub fn add_attribute(&mut self, key: &str, value: &str) {
        match key {
            "class" => self.add_class(value),
            "id" => self.set_id(value),
            _ => self.add_custom_attribute(key, value),
        }
    }

    fn add_custom_attribute(&mut self, key: &str, value: &str) {
        if let Some(custom_attributes) = &mut self.custom_attributes {
            custom_attributes.push((key.to_string(), value.to_string()));
        } else {
            self.custom_attributes = Some(vec![(key.to_string(), value.to_string())]);
        }
    }

    /// Adds multiple custom attributes to the current `HtmlTag`.
    /// You can declare the custom attributes as a vector of tuples
    /// of the form `(&str, &str)`.
    ///
    /// Where the first element of the tuple is the key, and the second
    /// element is the value.
    pub fn add_custom(&mut self, attributes: Vec<(&str, &str)>) {
        let mut custom_attributes = Vec::new();
        for (key, value) in attributes {
            custom_attributes.push((key.to_string(), value.to_string()));
        }
        self.custom_attributes = Some(custom_attributes);
    }

    /// Converts the current `HtmlTag` to a HTML string.
    ///
    /// This is the main form of conversion, and is used
    /// to convert the `HtmlTag` to a HTML string that can
    /// be used in a HTML document.
    ///
    /// # Examples
    ///
    /// ```
    /// use html_tag::HtmlTag;
    ///
    /// let mut div = HtmlTag::new("div");
    /// div.add_class("test");
    /// div.set_id("test");
    ///
    /// assert_eq!(div.to_html(), "<div id=\"test\" class=\"test\"></div>");
    ///
    /// ```
    ///
    /// This method is implemented as the display trait, so you can
    /// print it directly or use it in a format string.
    /// Like this
    ///
    /// ```
    /// use html_tag::HtmlTag;
    ///
    /// let mut div = HtmlTag::new("div");
    /// div.add_class("test");
    /// div.set_id("test");
    ///
    /// println!("{}", div);
    /// ```
    ///
    /// This will print the following: `<div class="test" id="test"></div>`
    pub fn to_html(&self) -> String {
        let mut html = self.partial_convert();
        let (_, closing_tag) = HtmlTag::get_tags(&self.tag_type);

        if let Some(body) = &self.body {
            html.push_str(&format!(">{}</{}>", body, self.tag_type.html()));
            return html;
        } else {
            html.push('>');
        }

        if let Some(children) = &self.children {
            for child in children {
                html.push_str(&child.to_html());
            }
        }

        html.push_str(&closing_tag);

        html
    }

    /// Just a fancy name for `to_html`.
    pub fn construct(&self) -> String {
        self.to_html()
    }
}

impl Display for HtmlTag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_html())
    }
}