htmlite 0.12.0

An HTML manipulation toolkit
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
446
447
448
449
450
451
452
453
454
455
456
use crate::parser::Namespace;
use crate::{Node, NodeKind};
use bumpalo::Bump;

/// Storage for parsed HTML nodes.
///
/// This wraps a bump allocator into which all HTML [nodes](Node) are allocated.
///
/// You'll generally pass an instance of this struct around to functions that create new nodes.
/// The created nodes will have a liftime tied to the arena that was used to create them.
///
/// Dropping the arena cleans up the memory used for storing HTML nodes all at once.
///
/// # Constructing HTML
///
/// This struct is also the starting point for programmatically constructing HTML ([impl block](crate::NodeArena#impl-NodeArena-1)).
///
/// The methods all have the same structure; they accept two arguments: attributes and child elements.
/// Don't let the function signatures scare you.
/// For attributes, you can pass in anything that can be converted into an iterator of two item tuples.
/// For children, you can pass in anything that can be converted into an iterator of [`Nodes`](crate::Node).
///
/// `Node` implements `IntoIterator`, so you can pass in a single item.
/// `Option<T>` implements `IntoIterator`, so you can also use `None` to mean "no children" or "no attributes"
///
/// ```
/// use htmlite::{NodeArena};
///
/// let h = NodeArena::new();
///
/// // These are the same
/// let empty_div = h.div([], []);
/// let empty_div = h.div(None, None);
///
/// let div_with_one_span = h.div(None, h.span(None, None));
/// let div_with_many_spans = h.div(None, [h.span(None, None), h.span(None, None)]);
///
/// let div_with_attributes = h.div([("class", "container"), ("id", "nav")], None);
/// ```
#[derive(Debug, Default)]
pub struct NodeArena {
    pub(crate) inner: Bump,
}

impl NodeArena {
    /// Returns an empty storage location for parsed nodes.
    pub fn new() -> NodeArena {
        NodeArena::default()
    }

    /// Allocates a new [element](crate::NodeKind::Element) `tag` in the arena and returns it.
    pub fn element<'arena, 'attr, A, C>(
        &'arena self,
        tag: &str,
        attributes: A,
        children: C,
    ) -> &'arena Node<'arena>
    where
        A: IntoIterator<Item = (&'attr str, &'attr str)>,
        <A as IntoIterator>::IntoIter: ExactSizeIterator,
        C: IntoIterator<Item = &'arena Node<'arena>>,
    {
        alloc::element(self, tag, attributes.into_iter(), Namespace::Html).append(children)
    }

    /// Allocates a [fragment](crate::NodeKind::Fragment) with the given nodes.
    pub fn fragment<'a, I>(&'a self, children: I) -> &'a Node<'a>
    where
        I: IntoIterator<Item = &'a Node<'a>>,
    {
        alloc::fragment(self).append(children)
    }

    /// Allocates a text node with the given contents and returns it.
    ///
    /// Serializing the node to HTML will escape its contents.   
    pub fn text<'a>(&'a self, text: impl AsRef<str>) -> &'a Node<'a> {
        alloc::text(self, text.as_ref(), false)
    }

    /// Allocates a text node with the given contents and returns it.
    ///
    /// Serializing the node to HTML will _not_ escape its contents.
    /// They will be output verbatim.
    pub fn raw_text<'a>(&'a self, text: impl AsRef<str>) -> &'a Node<'a> {
        alloc::text(self, text.as_ref(), true)
    }

    /// Creates a deep-copy of `node` by recursively building a tree out of new copies of its children.
    pub fn deep_copy<'a>(&'a self, node: &'a Node<'a>) -> &'a Node<'a> {
        match &node.kind {
            NodeKind::Fragment => {
                let new_chunk = self.fragment([]);
                for child in node.children() {
                    new_chunk.append(self.deep_copy(child));
                }
                new_chunk
            }
            NodeKind::Comment => alloc::comment(self, node.data),
            NodeKind::Doctype => alloc::doctype(self, node.data),
            NodeKind::Text => alloc::text(self, node.data, node.special),
            NodeKind::Element => {
                let new_element = alloc::element(self, node.data, node.attrs(), node.namespace);
                for child in node.children() {
                    new_element.append(self.deep_copy(child));
                }
                new_element
            }
        }
    }
}

macro_rules! tag_name_functions {
    ($($name:ident),*) => {
        $(
            pub fn $name<'a, 'attr, A, C>(&'a self, attributes: A, children: C) -> &'a $crate::Node<'a>
            where C: IntoIterator<Item = &'a Node<'a>>,
            A: IntoIterator<Item = (&'attr str, &'attr str)>,
            <A as IntoIterator>::IntoIter: ExactSizeIterator,
            {
                self.element(stringify!($name), attributes, children)
            }
        )*
    };
}

/// Methods for creating various HTML elements.
impl NodeArena {
    pub fn doctype<'a>(&'a self) -> &'a Node<'a> {
        alloc::doctype(self, "html")
    }

    pub fn title<'a, 'attr, A>(&'a self, attributes: A, title: &str) -> &'a Node<'a>
    where
        A: IntoIterator<Item = (&'attr str, &'attr str)>,
        <A as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        let text = alloc::text(self, title, true);
        self.element("title", attributes, text)
    }

    pub fn textarea<'a, 'attr, A>(&'a self, attributes: A, text: &str) -> &'a Node<'a>
    where
        A: IntoIterator<Item = (&'attr str, &'attr str)>,
        <A as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        let text = alloc::text(self, text, true);
        self.element("textarea", attributes, text)
    }

    pub fn style<'a, 'attr, A>(&'a self, attributes: A, css: &str) -> &'a Node<'a>
    where
        A: IntoIterator<Item = (&'attr str, &'attr str)>,
        <A as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        let text = alloc::text(self, css, true);
        self.element("style", attributes, text)
    }

    pub fn iframe<'a, 'attr, A>(&'a self, attributes: A, content: &str) -> &'a Node<'a>
    where
        A: IntoIterator<Item = (&'attr str, &'attr str)>,
        <A as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        let text = alloc::text(self, content, true);
        self.element("iframe", attributes, text)
    }

    pub fn script<'a, 'attr, A>(&'a self, attributes: A, script: &str) -> &'a Node<'a>
    where
        A: IntoIterator<Item = (&'attr str, &'attr str)>,
        <A as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        let text = alloc::text(self, script, true);
        self.element("script", attributes, text)
    }

    pub fn noscript<'a, 'attr, A>(&'a self, attributes: A, content: &str) -> &'a Node<'a>
    where
        A: IntoIterator<Item = (&'attr str, &'attr str)>,
        <A as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        let text = alloc::text(self, content, true);
        self.element("noscript", attributes, text)
    }

    tag_name_functions! {
        a,
        abbr,
        address,
        area,
        article,
        aside,
        audio,
        b,
        base,
        bdi,
        bdo,
        blockquote,
        body,
        br,
        button,
        canvas,
        caption,
        cite,
        code,
        col,
        colgroup,
        data,
        datalist,
        dd,
        del,
        details,
        dfn,
        dialog,
        div,
        dl,
        dt,
        em,
        embed,
        fieldset,
        figcaption,
        figure,
        footer,
        form,
        h1,
        h2,
        h3,
        h4,
        h5,
        h6,
        head,
        header,
        hgroup,
        hr,
        html,
        i,
        // iframe,
        img,
        input,
        ins,
        kbd,
        label,
        legend,
        li,
        link,
        main,
        map,
        mark,
        menu,
        meta,
        meter,
        nav,
        // noscript,
        object,
        ol,
        optgroup,
        option,
        output,
        p,
        picture,
        pre,
        progress,
        q,
        rp,
        rt,
        ruby,
        s,
        samp,
        // script,
        search,
        section,
        select,
        selectedcontent,
        slot,
        small,
        source,
        span,
        strong,
        // style,
        sub,
        summary,
        sup,
        table,
        tbody,
        td,
        template,
        // textarea,
        tfoot,
        th,
        thead,
        time,
        // title,
        tr,
        track,
        u,
        ul,
        var,
        video,
        wbr
    }
}

// Low-level methods for allocating in a NodeArena.
pub(crate) mod alloc {
    use crate::parser::Namespace;
    use crate::{Node, NodeArena, NodeKind};

    pub(crate) fn fragment<'a>(arena: &'a NodeArena) -> &'a Node<'a> {
        arena.inner.alloc(Node::empty(NodeKind::Fragment))
    }

    pub(crate) fn element<'attr, 'arena, I>(
        arena: &'arena NodeArena,
        tag: &str,
        attrs: I,
        namespace: Namespace,
    ) -> &'arena Node<'arena>
    where
        I: Iterator<Item = (&'attr str, &'attr str)> + ExactSizeIterator,
    {
        let tag = arena.inner.alloc_str(tag);
        tag.make_ascii_lowercase();
        let attributes = attributes(arena, attrs);

        arena.inner.alloc(Node {
            attributes,
            data: tag,
            namespace,
            ..Node::empty(NodeKind::Element)
        })
    }

    /// Allocates memory for a new HTML comment with the given contents.
    pub(crate) fn comment<'a>(arena: &'a NodeArena, comment_text: &str) -> &'a Node<'a> {
        arena.inner.alloc(Node {
            data: arena.inner.alloc_str(comment_text),
            ..Node::empty(NodeKind::Comment)
        })
    }

    pub(crate) fn text<'a>(
        arena: &'a NodeArena,
        contents: &str,
        serialize_verbatim: bool,
    ) -> &'a Node<'a> {
        arena.inner.alloc(Node {
            data: arena.inner.alloc_str(contents),
            special: serialize_verbatim,
            ..Node::empty(NodeKind::Text)
        })
    }

    pub(crate) fn doctype<'a>(arena: &'a NodeArena, name: &str) -> &'a Node<'a> {
        arena.inner.alloc(Node {
            data: arena.inner.alloc_str(name),
            ..Node::empty(NodeKind::Doctype)
        })
    }

    pub(crate) fn attributes<'attr, 'arena, I>(
        arena: &'arena NodeArena,
        attrs: I,
    ) -> &'arena [(&'arena str, &'arena str)]
    where
        I: Iterator<Item = (&'attr str, &'attr str)>,
        I: ExactSizeIterator,
    {
        let allocated_attrs = attrs.into_iter().map(|(name, value)| {
            (
                arena.inner.alloc_str(name) as &str,
                arena.inner.alloc_str(value) as &str,
            )
        });
        arena.inner.alloc_slice_fill_iter(allocated_attrs)
    }
}

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

    #[test]
    fn empty_attribute_and_child_iterators() {
        let h = NodeArena::new();

        assert_eq!(h.span(None, None).html(), "<span></span>");

        assert_eq!(h.span([], []).html(), "<span></span>");
    }

    #[test]
    fn serializing_text_in_different_contexts() {
        let h = NodeArena::new();
        // Text is automatically escaped by default
        assert_eq!(
            h.text("hello &\u{a0}<>").html(),
            "hello &amp;&nbsp;&lt;&gt;"
        );
        assert_eq!(
            h.div(None, h.text("hello &\u{a0}<>")).html(),
            "<div>hello &amp;&nbsp;&lt;&gt;</div>"
        );

        // Except for inside certain elements
        assert_eq!(
            h.script(None, "hello &\u{a0}<>").html(),
            "<script>hello &\u{a0}<></script>"
        );
        assert_eq!(
            h.style(None, "hello &\u{a0}<>").html(),
            "<style>hello &\u{a0}<></style>"
        );
        assert_eq!(
            h.iframe(None, "hello &\u{a0}<>").html(),
            "<iframe>hello &\u{a0}<></iframe>"
        );
        assert_eq!(
            h.textarea(None, "hello &\u{a0}<>").html(),
            "<textarea>hello &\u{a0}<></textarea>"
        );
        assert_eq!(
            h.noscript(None, "hello &\u{a0}<>").html(),
            "<noscript>hello &\u{a0}<></noscript>"
        );
    }

    #[test]
    fn serializing_attributes() {
        let h = NodeArena::new();
        assert_eq!(
            h.div([("class", "&\u{a0}<>\"")], None).html(),
            r#"<div class="&amp;&nbsp;&lt;&gt;&quot;⋈"></div>"#
        )
    }

    #[test]
    fn children() {
        let h = NodeArena::new();

        assert_eq!(
            h.div(None, [h.button(None, None)]).html(),
            "<div><button></button></div>"
        );

        assert_eq!(
            h.div(None, h.button(None, None)).html(),
            "<div><button></button></div>"
        );

        assert_eq!(
            h.div(None, Some(h.button(None, None))).html(),
            "<div><button></button></div>"
        );
    }
}