hatmil 1.4.0

Simple HTML/SVG 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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// tree.rs
//
// Copyright (C) 2025-2026  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 tree builder
#[derive(Default)]
pub struct Tree {
    /// 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,
}

/// Renamed to `Tree`; will be removed in a future release
#[deprecated]
pub type Page = Tree;

/// Element borrowed from a `Tree`
pub trait Element<'t> {
    /// Element tag
    const TAG: &'static str;

    /// Element type
    const TP: ElemType;

    /// Make new "root" element
    fn new(tree: &'t mut Tree) -> Self;
}

impl fmt::Display for Tree {
    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(tree) = self.doc.strip_suffix('>') {
            write!(f, "{tree}")?;
        } 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<Tree> for String {
    fn from(mut tree: Tree) -> Self {
        // zero-copy alternative to fmt::Display
        tree.close_to(1);
        tree.doc
    }
}

impl Tree {
    /// Create an HTML tree builder
    ///
    /// ```rust
    /// use hatmil::Tree;
    ///
    /// let mut tree = Tree::new();
    /// let mut html = tree.html();
    /// let mut body = html.body();
    /// body.cdata("Page text");
    /// body.a().href("https://www.example.com/").cdata("Example link");
    /// assert_eq!(
    ///     String::from(tree),
    ///     "<!DOCTYPE html><html><body>Page text<a href=\"https://www.example.com/\">Example link</a></body></html>",
    /// );
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Has no effect; will be removed in a future release
    #[deprecated]
    pub fn with_doctype(self) -> Self {
        self
    }

    /// Create `<html>` element
    ///
    /// The `<!DOCTYPE html>` preamble will be included.
    pub fn html(&mut self) -> Html<'_> {
        self.stack.clear();
        self.doc.clear();
        self.raw("<!DOCTYPE html>");
        self.elem("html", ElemType::Html);
        Html::new(self)
    }

    /// Create root snippet `E` element
    ///
    /// - `E`: Element type, from either the [html] or [svg] modules
    ///
    /// ```rust
    /// use hatmil::{Tree, html::A};
    ///
    /// let mut tree = Tree::new();
    /// tree.root::<A>().href("https://www.example.com/").cdata("Example link");
    /// assert_eq!(
    ///     String::from(tree),
    ///     "<a href=\"https://www.example.com/\">Example link</a>",
    /// );
    /// ```
    ///
    /// [html]: crate::html
    /// [svg]: crate::svg
    pub fn root<'t, E>(&'t mut self) -> E
    where
        E: Element<'t>,
    {
        self.elem(E::TAG, E::TP);
        E::new(self)
    }

    /// Renamed to `root`; will be removed in a future release
    #[deprecated]
    pub fn frag<'t, E>(&'t mut self) -> E
    where
        E: Element<'t>,
    {
        self.root()
    }

    /// 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) -> usize {
        self.doc.push('<');
        self.doc.push_str(tag);
        self.doc.push('>');
        self.empty = true;
        self.tp = Some(tp);
        self.stack.push(tag);
        self.stack.len()
    }

    /// Add an attribute with value
    ///
    /// These characters will be replaced with entities:
    ///
    /// - `&` ⇨ `&amp;`
    /// - `"` ⇨ `&quot;`
    pub(crate) fn attr<'a, V>(&mut self, attr: &str, val: V)
    where
        V: Into<Value<'a>>,
    {
        match self.doc.pop() {
            Some(gt) => assert_eq!(gt, '>'),
            None => panic!("cannot add {attr} attribute after child content"),
        }
        self.doc.push(' ');
        self.doc.push_str(attr);
        self.doc.push_str("=\"");
        val.into().encode_attr(&mut self.doc);
        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 => panic!("cannot add {attr} attribute after child content"),
        }
        self.doc.push(' ');
        self.doc.push_str(attr);
        self.doc.push('>');
    }

    /// Add a comment
    ///
    /// These characters will be replaced with entities:
    ///
    /// - `-` ⇨ `&hyphen;`
    /// - `<` ⇨ `&lt;`
    /// - `>` ⇨ `&gt;`
    pub fn comment<'a, V>(&mut self, com: V) -> &mut Self
    where
        V: Into<Value<'a>>,
    {
        self.doc.push_str("<!--");
        com.into().encode_comment(&mut self.doc);
        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>>,
    {
        text.into().encode_cdata(&mut self.doc);
        self.empty = false;
        self
    }

    /// 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>>,
    {
        text.into().encode_cdata_len(&mut self.doc, len);
        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 elements to the specified depth
    pub(crate) fn close_to(&mut self, depth: usize) -> &mut Self {
        while self.stack.len() >= depth {
            self.close();
        }
        self
    }

    /// Close the final open element
    ///
    /// 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 tree = Tree::new();
        tree.root::<Div>();
        assert_eq!(tree.to_string(), "<div></div>");
    }

    #[test]
    fn boolean() {
        let mut tree = Tree::new();
        tree.root::<Div>().id("test").spellcheck(true);
        assert_eq!(
            tree.to_string(),
            "<div id=\"test\" spellcheck=\"true\"></div>"
        );
    }

    #[test]
    fn paragraph() {
        let mut tree = Tree::new();
        tree.root::<P>().cdata("This is a paragraph");
        assert_eq!(tree.to_string(), "<p>This is a paragraph</p>");
    }

    #[test]
    fn escape_attr() {
        let mut tree = Tree::new();
        tree.root::<P>().id("quote\"ampersand&");
        assert_eq!(
            tree.to_string(),
            "<p id=\"quote&quot;ampersand&amp;\"></p>"
        );
    }

    #[test]
    fn escape_cdata() {
        let mut tree = Tree::new();
        tree.root::<Em>().cdata("You <&> I");
        assert_eq!(tree.to_string(), "<em>You &lt;&amp;&gt; I</em>");
    }

    #[test]
    fn raw_burger() {
        let mut tree = Tree::new();
        tree.root::<Span>().cdata("Raw").raw(" <em>Burger</em>!");
        assert_eq!(tree.to_string(), "<span>Raw <em>Burger</em>!</span>");
    }

    #[test]
    fn void() {
        let mut tree = Tree::new();
        tree.root::<Div>().input().r#type("text");
        assert_eq!(tree.to_string(), "<div><input type=\"text\"></div>");
    }

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

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

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

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

    #[test]
    fn comment() {
        let mut tree = Tree::new();
        tree.root::<I>().comment("comment");
        assert_eq!(tree.to_string(), "<i><!--comment--></i>");
    }

    #[test]
    fn escape_comment() {
        let mut tree = Tree::new();
        tree.comment("<-->");
        assert_eq!(tree.to_string(), "<!--&lt;&hyphen;&hyphen;&gt;-->");
    }

    #[test]
    fn xml() {
        let mut tree = Tree::new();
        tree.root::<Link>().rel("stylesheet").close();
        assert_eq!(tree.to_string(), "<link rel=\"stylesheet\" />");
    }

    #[test]
    fn close() {
        let mut tree = Tree::new();
        tree.root::<Span>().id("gle").close();
        assert_eq!(tree.to_string(), "<span id=\"gle\"></span>");
    }

    #[test]
    fn image() {
        let mut tree = Tree::new();
        tree.root::<Img>().width(100).height(50).close();
        assert_eq!(tree.to_string(), "<img width=\"100\" height=\"50\">");
    }

    #[test]
    fn data() {
        let mut tree = Tree::new();
        tree.root::<P>().data_("macro", "macrodata");
        assert_eq!(tree.to_string(), "<p data-macro=\"macrodata\"></p>");
    }

    #[test]
    #[should_panic]
    fn attributes() {
        let mut tree = Tree::new();
        tree.root::<P>().cdata("character data").id("123");
    }

    #[test]
    fn double_root() {
        let mut tree = Tree::new();
        tree.root::<Div>().close();
        tree.root::<Div>().close();
        assert_eq!(String::from(tree), "<div></div><div></div>");
    }
}