hatmil 0.13.0

User-friendly HTML builder
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
414
415
416
417
418
419
// html.rs
//
// Copyright (C) 2025  Douglas P Lau
//
use crate::html::Html;
use crate::value::Value;
use std::fmt;

/// Element type
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ElemType {
    /// HTML element
    Html,
    /// HTML void element
    HtmlVoid,
    /// XML element (SVG)
    Xml,
}

/// HTML page builder
#[derive(Default)]
pub struct Page {
    /// Include HTML `doctype` preamble
    doctype: bool,
    /// HTML document text
    doc: String,
    /// Stack of element tags
    stack: Vec<&'static str>,
    /// Leaf node element type
    tp: Option<ElemType>,
    /// Current tag empty
    empty: bool,
}

/// Element borrowed from a [Page]
pub trait Element<'p> {
    /// Element tag
    const TAG: &'static str;

    /// Element type
    const TP: ElemType;

    /// Make a new element
    fn new(page: &'p mut Page) -> Self;
}

impl fmt::Display for Page {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut void = self.tp == Some(ElemType::HtmlVoid);
        let mut self_closing = self.empty && self.tp == Some(ElemType::Xml);
        if self_closing && let Some(page) = self.doc.strip_suffix('>') {
            write!(f, "{}", page)?;
        } else {
            write!(f, "{}", self.doc)?;
            self_closing = false;
        }
        for tag in self.stack.iter().rev() {
            if self_closing {
                write!(f, " />")?;
            } else if !void {
                write!(f, "</{tag}>")?;
            }
            self_closing = false;
            void = false;
        }
        Ok(())
    }
}

impl From<Page> for String {
    fn from(mut page: Page) -> Self {
        // zero-copy alternative to fmt::Display
        while !page.stack.is_empty() {
            page.close();
        }
        page.doc
    }
}

impl Page {
    /// Create an HTML page builder
    ///
    /// - `doctype`: Include HTML `doctype` preamble
    ///
    /// ```rust
    /// use hatmil::Page;
    ///
    /// let mut page = Page::new(true);
    /// let mut html = page.html();
    /// let mut body = html.body();
    /// body.cdata("Page text");
    /// body.a().href("https://www.example.com/").cdata("Example link");
    /// assert_eq!(
    ///     page.to_string(),
    ///     "<!doctype html><html><body>Page text<a href=\"https://www.example.com/\">Example link</a></body></html>",
    /// );
    /// ```
    pub fn new(doctype: bool) -> Self {
        Page {
            doctype,
            ..Default::default()
        }
    }

    /// Convert page into a fragment
    ///
    /// - `E`: Element type, from either the [html] or [svg] modules
    ///
    /// ```rust
    /// use hatmil::{Page, html::A};
    ///
    /// let mut page = Page::default();
    /// page.frag::<A>().href("https://www.example.com/").cdata("Example link");
    /// assert_eq!(
    ///     page.to_string(),
    ///     "<a href=\"https://www.example.com/\">Example link</a>",
    /// );
    /// ```
    ///
    /// [html]: crate::html
    /// [svg]: crate::svg
    pub fn frag<'p, E>(&'p mut self) -> E
    where
        E: Element<'p>,
    {
        self.doc.clear();
        self.elem(E::TAG, E::TP);
        E::new(self)
    }

    /// Add `<html>` root element
    pub fn html(&mut self) -> Html<'_> {
        self.doc.clear();
        if self.doctype {
            self.raw("<!doctype html>");
        }
        self.elem("html", ElemType::Html);
        Html::new(self)
    }

    /// Add an element
    ///
    /// - `tag`: Element tag
    /// - `tp`: Element type
    ///
    /// [Void]: https://developer.mozilla.org/en-US/docs/Glossary/Void_element
    pub(crate) fn elem(&mut self, tag: &'static str, tp: ElemType) {
        self.doc.push('<');
        self.doc.push_str(tag);
        self.doc.push('>');
        self.tp = Some(tp);
        self.stack.push(tag);
        self.empty = true;
    }

    /// Add an attribute with value
    ///
    /// These characters will be replaced with entities:
    ///
    /// | Char | Entity   |
    /// |------|----------|
    /// | `&`  | `&amp;`  |
    /// | `"`  | `&quot;` |
    pub(crate) fn attr<'a, V>(&mut self, attr: &'static str, val: V)
    where
        V: Into<Value<'a>>,
    {
        match self.doc.pop() {
            Some(gt) => assert_eq!(gt, '>'),
            None => unreachable!(),
        }
        self.doc.push(' ');
        self.doc.push_str(attr);
        self.doc.push_str("=\"");
        for c in val.into().chars() {
            match c {
                '&' => self.doc.push_str("&amp;"),
                '"' => self.doc.push_str("&quot;"),
                _ => self.doc.push(c),
            }
        }
        self.doc.push_str("\">");
    }

    /// Add a [Boolean] attribute
    ///
    /// [Boolean]: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
    pub(crate) fn attr_bool(&mut self, attr: &'static str) {
        match self.doc.pop() {
            Some(gt) => assert_eq!(gt, '>'),
            None => unreachable!(),
        }
        self.doc.push(' ');
        self.doc.push_str(attr);
        self.doc.push('>');
    }

    /// Add a comment
    ///
    /// These characters will be replaced with entities:
    ///
    /// | Char | Entity     |
    /// |------|------------|
    /// | `-`  | `&hyphen;` |
    /// | `<`  | `&gt;`     |
    /// | `>`  | `&lt;`     |
    pub fn comment<'a, V>(&mut self, com: V) -> &mut Self
    where
        V: Into<Value<'a>>,
    {
        self.doc.push_str("<!--");
        for c in com.into().chars() {
            match c {
                '-' => self.doc.push_str("&hyphen;"),
                '<' => self.doc.push_str("&lt;"),
                '>' => self.doc.push_str("&gt;"),
                _ => self.doc.push(c),
            }
        }
        self.doc.push_str("-->");
        self.empty = false;
        self
    }

    /// Add character data content
    pub(crate) fn cdata<'a, V>(&mut self, text: V) -> &mut Self
    where
        V: Into<Value<'a>>,
    {
        self.cdata_len(text, usize::MAX)
    }

    /// Add character data content with a maximum character limit
    pub(crate) fn cdata_len<'a, V>(&mut self, text: V, len: usize) -> &mut Self
    where
        V: Into<Value<'a>>,
    {
        for c in text.into().chars().take(len) {
            match c {
                '&' => self.doc.push_str("&amp;"),
                '<' => self.doc.push_str("&lt;"),
                '>' => self.doc.push_str("&gt;"),
                _ => self.doc.push(c),
            }
        }
        self.empty = false;
        self
    }

    /// Add raw content
    ///
    /// **WARNING**: `trusted` is used verbatim, with no escaping; do not call
    /// with untrusted content.
    pub fn raw(&mut self, trusted: impl AsRef<str>) -> &mut Self {
        self.doc.push_str(trusted.as_ref());
        self.empty = false;
        self
    }

    /// Close the leaf tag
    ///
    /// Add a closing tag (e.g. `</span>`).
    pub fn close(&mut self) -> &mut Self {
        let tp = self.tp.take();
        if let Some(tag) = self.stack.pop() {
            let void = tp == Some(ElemType::HtmlVoid);
            let self_closing = self.empty && tp == Some(ElemType::Xml);
            if self_closing && self.doc.ends_with('>') {
                self.doc.pop();
                self.doc.push_str(" />");
            } else if !void {
                self.doc.push_str("</");
                self.doc.push_str(tag);
                self.doc.push('>');
            }
        }
        self.empty = false;
        self
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::html::*;

    #[test]
    fn div() {
        let mut page = Page::default();
        page.frag::<Div>();
        assert_eq!(page.to_string(), "<div></div>");
    }

    #[test]
    fn boolean() {
        let mut page = Page::default();
        page.frag::<Div>().id("test").spellcheck(true);
        assert_eq!(
            page.to_string(),
            "<div id=\"test\" spellcheck=\"true\"></div>"
        );
    }

    #[test]
    fn paragraph() {
        let mut page = Page::default();
        page.frag::<P>().cdata("This is a paragraph");
        assert_eq!(page.to_string(), "<p>This is a paragraph</p>");
    }

    #[test]
    fn escaping() {
        let mut page = Page::default();
        page.frag::<Em>().cdata("You & I");
        assert_eq!(page.to_string(), "<em>You &amp; I</em>");
    }

    #[test]
    fn raw_burger() {
        let mut page = Page::default();
        page.frag::<Span>().cdata("Raw").raw(" <em>Burger</em>!");
        assert_eq!(page.to_string(), "<span>Raw <em>Burger</em>!</span>");
    }

    #[test]
    fn void() {
        let mut page = Page::default();
        page.frag::<Div>().input().r#type("text");
        assert_eq!(page.to_string(), "<div><input type=\"text\"></div>");
    }

    #[test]
    fn html() {
        let mut page = Page::default();
        let mut ol = page.frag::<Ol>();
        ol.li().class("cat").cdata("nori").close();
        ol.li().class("cat").cdata("chashu");
        assert_eq!(
            page.to_string(),
            "<ol><li class=\"cat\">nori</li><li class=\"cat\">chashu</li></ol>"
        );
    }

    #[test]
    fn build_html() {
        let mut page = Page::default();
        let mut div = page.frag::<Div>();
        div.p().cdata("Paragraph Text").close();
        div.pre().cdata("Preformatted Text");
        assert_eq!(
            page.to_string(),
            "<div><p>Paragraph Text</p><pre>Preformatted Text</pre></div>"
        );
    }

    #[test]
    fn html_builder() {
        let mut page = Page::default();
        let mut html = page.html();
        html.lang("en")
            .head()
            .title_el()
            .cdata("Title!")
            .close()
            .close();
        html.body().h1().cdata("Header!");
        assert_eq!(
            page.to_string(),
            "<html lang=\"en\"><head><title>Title!</title></head><body><h1>Header!</h1></body></html>"
        );
    }

    #[test]
    fn string_from() {
        let mut page = Page::new(false);
        let mut html = page.html();
        html.head().title_el().cdata("Head").close().close();
        html.body().cdata("Body");
        assert_eq!(
            String::from(page),
            "<html><head><title>Head</title></head><body>Body</body></html>"
        );
    }

    #[test]
    fn comment() {
        let mut page = Page::default();
        page.frag::<I>().comment("comment");
        assert_eq!(page.to_string(), "<i><!--comment--></i>");
    }

    #[test]
    fn comment_escape() {
        let mut page = Page::default();
        page.comment("<-->");
        assert_eq!(page.to_string(), "<!--&lt;&hyphen;&hyphen;&gt;-->");
    }

    #[test]
    fn xml() {
        let mut page = Page::default();
        page.frag::<Link>().rel("stylesheet").close();
        assert_eq!(page.to_string(), "<link rel=\"stylesheet\" />");
    }

    #[test]
    fn close() {
        let mut page = Page::default();
        page.frag::<Span>().id("gle").close();
        assert_eq!(page.to_string(), "<span id=\"gle\"></span>");
    }

    #[test]
    fn image() {
        let mut page = Page::default();
        page.frag::<Img>().width(100).height(50).close();
        assert_eq!(page.to_string(), "<img width=\"100\" height=\"50\">");
    }
}