vertigo-cli 0.14.4

Reactive Real-DOM library with SSR for Rust - packaging/serving tool
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use super::{HtmlNode, html_element::HtmlElement};
use html_escape::{encode_quoted_attribute, encode_safe};
use std::collections::VecDeque;
use std::{borrow::Cow, collections::BTreeMap};

enum ChildMode {
    Child {
        children: Vec<HtmlNode>,
        inline: bool,
    },
    Text(String),
}

pub fn convert_to_string(root: HtmlNode, pretty: bool) -> String {
    let mut result = vec!["<!DOCTYPE html>".to_owned()];

    if pretty {
        result.push("\n".to_string())
    }

    let root_ident = match pretty {
        true => Format::some(),
        false => Format::none(),
    };

    html_node_to_string(&mut result, root_ident, root);

    result.concat()
}

fn html_node_to_string(result: &mut Vec<String>, ident: Format, node: HtmlNode) {
    let mut ident_str = ident.get();

    match node {
        HtmlNode::Element(element) => {
            let is_self_closing = is_self_closing(&element);
            let el_name = encode_safe(&element.name);
            let attrs = attributes_to_string(element.attr);

            let l_chevron_str = ident.l_chevron();
            let l_chevron = l_chevron_str.as_str();

            if is_self_closing {
                let line = [l_chevron, &el_name, &attrs, ident.self_closing()];

                result.push(line.concat());
                return;
            }

            let r_chevron = ident.r_chevron();

            match get_render_child_mode(element.children) {
                ChildMode::Child { children, inline } => {
                    // Treat <pre> and inline (mixed text+element) content as
                    // preformatted: whitespace is significant, so don't inject
                    // indentation/newlines around the children.
                    let preformatted = el_name == "pre" || inline;
                    let inner_ident = if ident.is_some() && !preformatted {
                        ident.add(2)
                    } else {
                        Format::none()
                    };

                    let first_text = match children.first() {
                        Some(HtmlNode::Text(text)) => text.as_str(),
                        _ => "",
                    };

                    // open tag
                    let line = [
                        l_chevron,
                        &el_name,
                        &attrs,
                        inner_ident.r_chevron(),
                        line_break_for_parser(&element.name, first_text),
                    ];
                    result.push(line.concat());

                    // render child
                    for child in children {
                        html_node_to_string(result, inner_ident, child);
                    }

                    // If preformatted then do not ident the close tag
                    if preformatted {
                        ident_str.clear();
                    }

                    // close tag
                    let line = [&ident_str, "</", &el_name, r_chevron];
                    result.push(line.concat());
                }
                ChildMode::Text(text) => {
                    let line_break = line_break_for_parser(&element.name, &text);
                    let escaped_text =
                        if ["script", "style"].contains(&element.name.to_lowercase().as_str()) {
                            Cow::from(text)
                        } else {
                            encode_safe(&text)
                        };

                    let line = [
                        //open tag - no line break for formatting: it would become part of
                        // the text (`<a>\nLink</a>`)
                        l_chevron,
                        &el_name,
                        &attrs,
                        ">",
                        line_break,
                        // content
                        &escaped_text,
                        //close tag
                        "</",
                        &el_name,
                        r_chevron,
                    ];

                    result.push(line.concat());
                }
            }
        }
        HtmlNode::Text(text) => {
            result.push(format!("{ident_str}{}", encode_safe(&text)));
        }
        HtmlNode::Comment(comment) => {
            result.push(format!("{ident_str}<!--{}-->", encode_safe(&comment)));
        }
    }
}

const SELF_CLOSING_TAGS: [&str; 14] = [
    "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source",
    "track", "wbr",
];

fn is_self_closing(element: &HtmlElement) -> bool {
    SELF_CLOSING_TAGS.contains(&element.name.as_str())
}

/// The parser drops a line break right after the open tag of `<pre>`, `<textarea>` and
/// `<listing>` - content starting with one needs another in front, or loses it.
fn line_break_for_parser(name: &str, content: &str) -> &'static str {
    let drops_it = ["pre", "textarea", "listing"]
        .iter()
        .any(|tag| name.eq_ignore_ascii_case(tag));

    if drops_it && content.starts_with('\n') {
        "\n"
    } else {
        ""
    }
}

fn attributes_to_string(attr: BTreeMap<String, String>) -> String {
    let mut line = Vec::new();
    for (name, value) in attr.iter() {
        line.push(format!(
            " {}=\"{}\"",
            encode_safe(&name),
            encode_quoted_attribute(&value)
        ));
    }
    line.concat()
}

fn get_render_child_mode(element: VecDeque<HtmlNode>) -> ChildMode {
    let mut result: Vec<HtmlNode> = Vec::new();
    let mut last_text: Option<Vec<String>> = None;

    for child in element {
        match child {
            HtmlNode::Text(child_text) => {
                last_text_add(&mut last_text, child_text);
            }
            HtmlNode::Comment(_) => {}
            element => {
                if let Some(text) = last_text_get(&mut last_text) {
                    result.push(HtmlNode::Text(text));
                }

                result.push(element);
            }
        };
    }

    if let Some(text) = last_text_get(&mut last_text) {
        result.push(HtmlNode::Text(text));
    }

    let last = result.pop();

    // Nothing inside is written the same as empty text - `<textarea></textarea>`, not a line
    // break and indentation: the parser drops the line break, but the indentation would be
    // the textarea's value
    let Some(last) = last else {
        return ChildMode::Text(String::new());
    };

    if result.is_empty()
        && let HtmlNode::Text(last) = last
    {
        return ChildMode::Text(last);
    }

    result.push(last);

    // Mixed content (a text node interleaved with other children) is an inline
    // formatting context where whitespace is significant.
    let inline = result.iter().any(|n| matches!(n, HtmlNode::Text(_)));

    ChildMode::Child {
        children: result,
        inline,
    }
}

fn last_text_add(last_text: &mut Option<Vec<String>>, text: String) {
    if let Some(last_text) = last_text {
        last_text.push(text);
        return;
    }

    *last_text = Some(vec![text]);
}

fn last_text_get(last_text: &mut Option<Vec<String>>) -> Option<String> {
    let prev = std::mem::take(last_text);
    prev.map(|inner| inner.concat())
}

#[derive(Clone, Copy)]
struct Format {
    ident: Option<usize>,
}

impl Format {
    fn some() -> Format {
        Format { ident: Some(0) }
    }

    fn none() -> Format {
        Format { ident: None }
    }

    fn get(&self) -> String {
        match self.ident {
            Some(ident) => " ".repeat(ident),
            None => String::new(),
        }
    }

    fn add(&self, up_value: usize) -> Self {
        Self {
            ident: self.ident.map(|value| value + up_value),
        }
    }

    fn is_some(&self) -> bool {
        self.ident.is_some()
    }

    fn l_chevron(&self) -> String {
        if self.is_some() {
            [&self.get(), "<"].concat()
        } else {
            "<".to_string()
        }
    }

    fn r_chevron(&self) -> &'static str {
        if self.is_some() { ">\n" } else { ">" }
    }

    fn self_closing(&self) -> &'static str {
        if self.is_some() { " />\n" } else { " />" }
    }
}

#[cfg(test)]
mod tests {
    use crate::serve::html::{HtmlNode, html_element::HtmlElement};

    use super::convert_to_string;

    #[test]
    fn html_pre_formatting() {
        let div: HtmlNode = HtmlElement::new("div")
            .child(
                HtmlElement::new("pre")
                    .child(
                        HtmlElement::new("span")
                            .child(HtmlNode::Text("    ".into()))
                            .into(),
                    )
                    .child(
                        HtmlElement::new("span")
                            .child(HtmlNode::Text("let".into()))
                            .into(),
                    )
                    .child(
                        HtmlElement::new("span")
                            .child(HtmlNode::Text(" ".into()))
                            .into(),
                    )
                    .child(
                        HtmlElement::new("span")
                            .child(HtmlNode::Text("x".into()))
                            .into(),
                    )
                    .child(
                        HtmlElement::new("span")
                            .child(HtmlNode::Text(" ".into()))
                            .into(),
                    )
                    .child(
                        HtmlElement::new("span")
                            .child(HtmlNode::Text(";".into()))
                            .into(),
                    )
                    .child(
                        HtmlElement::new("span")
                            .child(HtmlNode::Text("\n".into()))
                            .into(),
                    )
                    .into(),
            )
            .child(HtmlElement::new("img").into())
            .into();

        let output = convert_to_string(div.clone(), true);

        assert_eq!(
            output,
            "<!DOCTYPE html>
<div>
  <pre><span>    </span><span>let</span><span> </span><span>x</span><span> </span><span>;</span><span>\n</span></pre>
  <img />
</div>
"
        );

        let output = convert_to_string(div, false);

        assert_eq!(
            output,
            "<!DOCTYPE html><div><pre><span>    </span><span>let</span><span> </span><span>x</span><span> </span><span>;</span><span>\n</span></pre><img /></div>"
        );
    }

    #[test]
    fn html_text_and_empty_elements_get_no_extra_whitespace() {
        // The text of an element, and the lack of it, are the content - formatting may only
        // add whitespace between elements
        let div: HtmlNode = HtmlElement::new("div")
            .child(
                HtmlElement::new("h1")
                    .child(HtmlNode::Text("Title".into()))
                    .into(),
            )
            .child(
                HtmlElement::new("a")
                    .attr("href", "/panel/")
                    .child(HtmlNode::Text("Panel".into()))
                    .into(),
            )
            .child(HtmlElement::new("textarea").attr("name", "text").into())
            .child(HtmlElement::new("div").into())
            .into();

        assert_eq!(
            convert_to_string(div.clone(), true),
            "<!DOCTYPE html>
<div>
  <h1>Title</h1>
  <a href=\"/panel/\">Panel</a>
  <textarea name=\"text\"></textarea>
  <div></div>
</div>
"
        );

        assert_eq!(
            convert_to_string(div, false),
            "<!DOCTYPE html><div><h1>Title</h1><a href=\"/panel/\">Panel</a><textarea name=\"text\"></textarea><div></div></div>"
        );
    }

    #[test]
    fn html_leading_line_break_survives_the_parser() {
        // The parser drops a line break right after `<textarea>` and `<pre>`, so the one their
        // content starts with needs another in front - any other element keeps it as it is
        let div: HtmlNode = HtmlElement::new("div")
            .child(
                HtmlElement::new("textarea")
                    .child(HtmlNode::Text("\nsecond line".into()))
                    .into(),
            )
            .child(
                HtmlElement::new("pre")
                    .child(HtmlNode::Text("\nfn ".into()))
                    .child(
                        HtmlElement::new("b")
                            .child(HtmlNode::Text("main".into()))
                            .into(),
                    )
                    .into(),
            )
            .child(
                HtmlElement::new("div")
                    .child(HtmlNode::Text("\nkept".into()))
                    .into(),
            )
            .into();

        assert_eq!(
            convert_to_string(div.clone(), true),
            concat!(
                "<!DOCTYPE html>\n",
                "<div>\n",
                "  <textarea>\n\nsecond line</textarea>\n",
                "  <pre>\n\nfn <b>main</b></pre>\n",
                "  <div>\nkept</div>\n",
                "</div>\n",
            )
        );

        assert_eq!(
            convert_to_string(div, false),
            "<!DOCTYPE html><div><textarea>\n\nsecond line</textarea><pre>\n\nfn <b>main</b></pre><div>\nkept</div></div>"
        );
    }

    #[test]
    fn html_inline_mixed_content_no_extra_whitespace() {
        // A paragraph mixing text with inline elements must not have whitespace
        // injected around the inline elements, otherwise the server-rendered
        // output differs from the dynamic (hydrated) DOM and the page flickers.
        let div: HtmlNode = HtmlElement::new("div")
            .child(
                HtmlElement::new("p")
                    .child(HtmlNode::Text("a [".into()))
                    .child(
                        HtmlElement::new("a")
                            .attr("href", "https://example.com")
                            .child(HtmlNode::Text("x".into()))
                            .into(),
                    )
                    .child(HtmlNode::Text("] b".into()))
                    .into(),
            )
            .into();

        let pretty = convert_to_string(div.clone(), true);

        assert_eq!(
            pretty,
            "<!DOCTYPE html>
<div>
  <p>a [<a href=\"https://example.com\">x</a>] b</p>
</div>
"
        );

        // The inline content of the <p> is byte-identical to the unformatted
        // render, which is what the dynamic DOM produces.
        let plain = convert_to_string(div, false);

        assert_eq!(
            plain,
            "<!DOCTYPE html><div><p>a [<a href=\"https://example.com\">x</a>] b</p></div>"
        );
    }
}