virtual-dom 1.0.4

A virtual DOM implementation for HTML manipulation
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
use std::{collections::HashMap, io, io::Read};

use lssg_char_reader::CharReader;

use crate::DomNode;

pub fn parse_html_from_string(input: &String) -> Result<Vec<Html>, io::Error> {
    parse_html(input.as_bytes())
}

// TODO: return DomNode directly instead of parsing to intermediary representation
pub fn parse_html(input: impl Read) -> Result<Vec<Html>, io::Error> {
    let mut reader = CharReader::new(input);

    let mut tokens = vec![];

    loop {
        match read_token(&mut reader)? {
            None => break,
            Some(t) => tokens.push(t),
        }
    }

    // add texts together
    let mut reduced_tokens = vec![];
    for token in tokens.into_iter() {
        if let Some(Html::Text { text: a }) = reduced_tokens.last_mut() {
            if let Html::Text { text: b } = &token {
                *a += b;
                continue;
            }
        }
        reduced_tokens.push(token)
    }

    Ok(reduced_tokens)
}

fn attributes(start_tag_content: &str) -> Result<HashMap<String, String>, io::Error> {
    // remove whitespace before and after text
    let start_tag_content = start_tag_content.trim();
    let chars: Vec<char> = start_tag_content.chars().collect();
    let mut attributes = HashMap::new();
    let mut key = String::new();
    let mut value = String::new();
    let mut in_value = false;
    let mut quote_char: Option<char> = None;
    let mut i = 0;
    while i < chars.len() {
        match chars[i] {
            ' ' | '\n' if !in_value => {
                if !key.is_empty() {
                    attributes.insert(key, value);
                    key = String::new();
                    value = String::new();
                    in_value = false;
                }
            }
            '=' => match chars.get(i + 1) {
                Some(&q @ '"') | Some(&q @ '\'') => {
                    i += 1;
                    in_value = true;
                    quote_char = Some(q);
                }
                _ => {
                    // '=' not followed by a quote
                    if in_value {
                        value.push('=')
                    } else {
                        key.push('=')
                    }
                }
            },
            '\'' | '"' if in_value && Some(chars[i]) == quote_char => {
                in_value = false;
                quote_char = None;
            }
            c => {
                if in_value {
                    value.push(c)
                } else {
                    key.push(c)
                }
            }
        }
        i += 1;
    }
    if !key.is_empty() {
        attributes.insert(key, value);
    }

    Ok(attributes)
}

type ElementStartTag = (String, HashMap<String, String>, usize, bool);

/// Get the start tag with its attributes starts after the opening tag '<'
///
/// returns (tag, attributes, tag_content_length, void_element)
fn element_start_tag(
    reader: &mut CharReader<impl Read>,
) -> Result<Option<ElementStartTag>, io::Error> {
    let mut inside_single_quotes = false;
    let mut inside_double_quotes = false;
    let mut i = 1;
    while let Some(c) = reader.peek_char(i)? {
        match c {
            '>' if !inside_single_quotes && !inside_double_quotes => {
                let tag_content = reader.peek_string(i + 1)?;

                let mut tag = String::new();
                for c in tag_content.chars().skip(1) {
                    match c {
                        ' ' | '\n' | '>' | '/' => break,
                        _ => tag.push(c),
                    }
                }

                // Check if this is a void element (with or without self-closing /)
                let has_self_closing_slash = reader.peek_char(i - 1)? == Some('/');
                let void_element = is_void_element(&tag);

                // Calculate attributes end position
                let attributes_end = if has_self_closing_slash {
                    // if it has self-closing slash, exclude the / and >
                    tag_content.len() - 2
                } else {
                    // otherwise just exclude the >
                    tag_content.len() - 1
                };

                let attributes = attributes(&tag_content[tag.len() + 1..attributes_end])?;

                return Ok(Some((tag, attributes, i + 1, void_element)));
            }
            '"' if !inside_single_quotes => inside_double_quotes = !inside_double_quotes,
            '\'' if !inside_double_quotes => inside_single_quotes = !inside_single_quotes,
            _ => {}
        }
        i += 1;
    }
    Ok(None)
}

/// Find the matching closing tag while respecting nesting
fn find_matching_closing_tag(
    reader: &mut CharReader<impl Read>,
    tag: &str,
    start_offset: usize,
) -> Result<Option<usize>, io::Error> {
    let start_tag = format!("<{}", tag);
    let end_tag = format!("</{}>", tag);
    let mut depth = 0;
    let mut i = start_offset;
    let mut in_double_quotes = false;
    let mut in_single_quotes = false;

    loop {
        // Try to peek ahead to see if we have more content
        let peek_char = reader.peek_char(i)?;
        if peek_char.is_none() {
            return Ok(None);
        }

        let current_char = peek_char.unwrap();

        // Track quote state to ignore tags inside attribute values
        match current_char {
            '"' if !in_single_quotes => in_double_quotes = !in_double_quotes,
            '\'' if !in_double_quotes => in_single_quotes = !in_single_quotes,
            _ => {}
        }

        // Only look for tags when not inside quotes
        if !in_double_quotes && !in_single_quotes && current_char == '<' {
            // Check if we can match the start tag at position i
            let start_tag_len = start_tag.len();
            if let Ok(peek_start) = reader.peek_string_from(i, start_tag_len + 1) {
                if peek_start.starts_with(&start_tag) {
                    // Make sure it's actually a tag (followed by space, >, or /)
                    if let Some(next_char) = peek_start.chars().nth(start_tag_len) {
                        if next_char == ' ' || next_char == '>' || next_char == '/' {
                            depth += 1;
                            i += start_tag_len;
                            continue;
                        }
                    }
                }
            }

            // Check if we can match the end tag at position i
            let end_tag_len = end_tag.len();
            if let Ok(peek_end) = reader.peek_string_from(i, end_tag_len) {
                if peek_end == end_tag {
                    if depth == 0 {
                        return Ok(Some(i - start_offset));
                    }
                    depth -= 1;
                    i += end_tag_len;
                    continue;
                }
            }
        }

        i += 1;
    }
}

type Element = (String, HashMap<String, String>, Option<String>);

/// parse html from start to end and return (tag, attributes, innerHtml)
///
/// seperated to make logic more reusable
fn element(reader: &mut CharReader<impl Read>) -> Result<Option<Element>, io::Error> {
    if let Some('<') = reader.peek_char(0)? {
        if let Some((tag, attributes, tag_content_length, void_element)) =
            element_start_tag(reader)?
        {
            // <{start_tag}/>
            if void_element {
                reader.consume(tag_content_length)?;
                return Ok(Some((tag, attributes, None)));
            }

            // <{start_tag}>{content}</{start_tag}>
            if let Some(content_length) =
                find_matching_closing_tag(reader, &tag, tag_content_length)?
            {
                reader.consume(tag_content_length)?;
                let content = reader.consume_string(content_length)?;
                reader.consume(tag.len() + 3)?; // </{tag}>

                return Ok(Some((tag, attributes, Some(content))));
            }
        }
    }
    Ok(None)
}

fn comment(reader: &mut CharReader<impl Read>) -> Result<Option<Html>, io::Error> {
    if "<!--" == reader.peek_string(4)? {
        if let Some(text) = reader.peek_until_match_exclusive_from(4, "-->")? {
            reader.consume(4)?; // skip start
            let text = reader.consume_string(text.len())?;
            reader.consume(3)?; // skip end
            return Ok(Some(Html::Comment { text }));
        }
    }

    Ok(None)
}

/// check if a html tag is a void tag (it can not have children)
pub fn is_void_element(tag: &str) -> bool {
    match tag {
        "base" | "img" | "br" | "col" | "embed" | "hr" | "area" | "input" | "link" | "meta"
        | "param" | "source" | "track" | "wbr" 
        // SVG void-like elements
        | "circle" | "ellipse" | "line" | "path" | "polygon" | "polyline" | "rect" 
        | "stop" | "use" => true,
        _ => false,
    }
}

/// A "simple" streaming html parser function. This is a fairly simplified way of parsing html
/// ignoring a lot of edge cases and validation normally seen when parsing html.
///
/// **NOTE: Might return multiple Text tokens one after another.**
fn read_token(reader: &mut CharReader<impl Read>) -> Result<Option<Html>, io::Error> {
    while let Some(c) = reader.peek_char(0)? {
        if c == '<' {
            if let Some(comment) = comment(reader)? {
                return Ok(Some(comment));
            }

            if let Some((tag, attributes, content)) = element(reader)? {
                let mut children = vec![];
                if let Some(content) = content {
                    let mut reader = CharReader::new(content.as_bytes());
                    while let Some(html) = read_token(&mut reader)? {
                        children.push(html);
                    }
                }
                return Ok(Some(Html::Element {
                    tag,
                    attributes,
                    children,
                }));
            }

            // non html opening
            reader.consume(1)?;
            let mut text = "<".to_string();
            text.push_str(&reader.consume_until_exclusive(|c| c == '<')?);
            return Ok(Some(Html::Text { text }));
        }

        let text = reader.consume_until_exclusive(|c| c == '<')?;
        // only valid text if it contains a non whitespace character
        if text.chars().any(|c| c != ' ' && c != '\n') {
            return Ok(Some(Html::Text { text }));
        }
    }

    Ok(None)
}

/// Simple parsed html representation with recursively added children
#[derive(Debug, Clone, PartialEq)]
pub enum Html {
    Comment {
        text: String,
    },
    Text {
        text: String,
    },
    Element {
        tag: String,
        attributes: HashMap<String, String>,
        children: Vec<Html>,
    },
}

impl From<DomNode> for Html {
    fn from(value: DomNode) -> Self {
        match &*value.kind() {
            crate::DomNodeKind::Text { text } => Html::Text { text: text.clone() },
            crate::DomNodeKind::Element { tag, attributes } => {
                let children = value.children().map(|c| c.into()).collect();
                Html::Element {
                    tag: tag.clone(),
                    attributes: attributes.clone(),
                    children,
                }
            }
        }
    }
}

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

    /// Utility function to convert iteratables into attributes hashmap
    pub fn to_attributes<I: IntoIterator<Item = (impl Into<String>, impl Into<String>)>>(
        arr: I,
    ) -> HashMap<String, String> {
        arr.into_iter().map(|(k, v)| (k.into(), v.into())).collect()
    }

    #[test]
    fn test_html() {
        let input = r#"<a href="test.com"><i class="fa-solid fa-rss"></i>Test</a>
<button disabled></button>"#;
        let expected = vec![
            Html::Element {
                tag: "a".into(),
                attributes: to_attributes([("href", "test.com")]),
                children: vec![
                    Html::Element {
                        tag: "i".into(),
                        attributes: to_attributes([("class", "fa-solid fa-rss")]),
                        children: vec![],
                    },
                    Html::Text {
                        text: "Test".into(),
                    },
                ],
            },
            Html::Element {
                tag: "button".into(),
                attributes: to_attributes([("disabled", "")]),
                children: vec![],
            },
        ];

        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(expected, tokens);

        let input = r#"<div>
<a href="link.com">[other](other.com)</a>
</div>"#;
        let expected = vec![Html::Element {
            tag: "div".into(),
            attributes: HashMap::new(),
            children: vec![Html::Element {
                tag: "a".into(),
                attributes: to_attributes([("href", "link.com")]),
                children: vec![Html::Text {
                    text: "[other](other.com)".into(),
                }],
            }],
        }];
        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(expected, tokens);
    }

    #[test]
    fn test_text_looks_like_html() {
        let input = r#"<Lots of people say Rust > c++. even though it might be
< then c++. Who knows? 
<>
<nonclosing>
This should be text
"#;
        let expected = vec![Html::Text {
            text: "<Lots of people say Rust > c++. even though it might be
< then c++. Who knows? 
<>
<nonclosing>
This should be text
"
            .into(),
        }];

        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(expected, tokens);
    }

    #[test]
    fn test_js_in_attribute() {
        let input = r#"<div onclick="() => test()"></div>"#;

        let expected = vec![Html::Element {
            tag: "div".into(),
            attributes: to_attributes([("onclick", "() => test()")]),
            children: vec![],
        }];
        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(expected, tokens);
    }

    #[test]
    fn test_nested_elements() {
        let input = r#"<div class="a">
            <div class="b">
                <div class="c">
                </div>
            </div>
        </div>
        "#;
        let expected = vec![Html::Element {
            tag: "div".into(),
            attributes: to_attributes([("class", "a")]),
            children: vec![Html::Element {
                tag: "div".into(),
                attributes: to_attributes([("class", "b")]),
                children: vec![Html::Element {
                    tag: "div".into(),
                    attributes: to_attributes([("class", "c")]),
                    children: vec![],
                }],
            }],
        }];
        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(expected, tokens);
    }

    #[test]
    fn test_full_html_document() {
        let input = r#"<!doctype html>
<html>
  <head>
    <meta content="art,simulation,technology" name="keywords" />
    <script type="module" crossorigin src="./assets/main-B0Asn3MK.js"></script>
    <link rel="modulepreload" crossorigin href="./assets/creature-BZHPYSn1.js">
    <link rel="stylesheet" crossorigin href="./assets/main-CjrOOoWN.css">
  </head>
  <body>
    <div id="messages"></div>
    <div id="debug"></div>
    <canvas id="root">Your browser does not support the HTML canvas tag.</canvas>
    <a id="qr-link" target="_blank">
      <div id="qr"></div>
    </a>
  </body>
</html>"#;
        let expected = vec![
            Html::Text {
                text: "<!doctype html>\n".into(),
            },
            Html::Element {
                tag: "html".into(),
                attributes: HashMap::new(),
                children: vec![
                    Html::Element {
                        tag: "head".into(),
                        attributes: HashMap::new(),
                        children: vec![
                            Html::Element {
                                tag: "meta".into(),
                                attributes: to_attributes([
                                    ("content", "art,simulation,technology"),
                                    ("name", "keywords"),
                                ]),
                                children: vec![],
                            },
                            Html::Element {
                                tag: "script".into(),
                                attributes: to_attributes([
                                    ("type", "module"),
                                    ("crossorigin", ""),
                                    ("src", "./assets/main-B0Asn3MK.js"),
                                ]),
                                children: vec![],
                            },
                            Html::Element {
                                tag: "link".into(),
                                attributes: to_attributes([
                                    ("rel", "modulepreload"),
                                    ("crossorigin", ""),
                                    ("href", "./assets/creature-BZHPYSn1.js"),
                                ]),
                                children: vec![],
                            },
                            Html::Element {
                                tag: "link".into(),
                                attributes: to_attributes([
                                    ("rel", "stylesheet"),
                                    ("crossorigin", ""),
                                    ("href", "./assets/main-CjrOOoWN.css"),
                                ]),
                                children: vec![],
                            },
                        ],
                    },
                    Html::Element {
                        tag: "body".into(),
                        attributes: HashMap::new(),
                        children: vec![
                            Html::Element {
                                tag: "div".into(),
                                attributes: to_attributes([("id", "messages")]),
                                children: vec![],
                            },
                            Html::Element {
                                tag: "div".into(),
                                attributes: to_attributes([("id", "debug")]),
                                children: vec![],
                            },
                            Html::Element {
                                tag: "canvas".into(),
                                attributes: to_attributes([("id", "root")]),
                                children: vec![Html::Text {
                                    text: "Your browser does not support the HTML canvas tag."
                                        .into(),
                                }],
                            },
                            Html::Element {
                                tag: "a".into(),
                                attributes: to_attributes([
                                    ("id", "qr-link"),
                                    ("target", "_blank"),
                                ]),
                                children: vec![Html::Element {
                                    tag: "div".into(),
                                    attributes: to_attributes([("id", "qr")]),
                                    children: vec![],
                                }],
                            },
                        ],
                    },
                ],
            },
        ];
        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(expected, tokens);
    }

    #[test]
    fn test_svg() {
        let input = r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" viewBox="0 0 640 640" height="20"><path d="M451.5 160C434.9 160 418.8 164.5 404.7 172.7"/></svg>"#;
        let expected = vec![Html::Element {
            tag: "svg".into(),
            attributes: to_attributes([
                ("xmlns", "http://www.w3.org/2000/svg"),
                ("width", "20"),
                ("viewBox", "0 0 640 640"),
                ("height", "20"),
            ]),
            children: vec![Html::Element {
                tag: "path".into(),
                attributes: to_attributes([("d", "M451.5 160C434.9 160 418.8 164.5 404.7 172.7")]),
                children: vec![],
            }],
        }];
        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(expected, tokens);
    }

    #[test]
    fn test_void_elements_with_and_without_self_closing() {
        // Void elements without self-closing slash (HTML5 style)
        let input = r#"<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<img src="image.jpg" alt="test">"#;
        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(tokens.len(), 3);
        assert!(matches!(tokens[0], Html::Element { ref tag, .. } if tag == "meta"));
        assert!(matches!(tokens[1], Html::Element { ref tag, .. } if tag == "link"));
        assert!(matches!(tokens[2], Html::Element { ref tag, .. } if tag == "img"));

        // Void elements with self-closing slash (XHTML style)
        let input = r#"<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" />
<img src="image.jpg" alt="test" />"#;
        let tokens = parse_html(input.as_bytes()).unwrap();
        assert_eq!(tokens.len(), 3);
        assert!(matches!(tokens[0], Html::Element { ref tag, .. } if tag == "meta"));
        assert!(matches!(tokens[1], Html::Element { ref tag, .. } if tag == "link"));
        assert!(matches!(tokens[2], Html::Element { ref tag, .. } if tag == "img"));
    }
}