brik 0.10.0

HTML tree manipulation library - a building block for HTML parsing and 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
//! TreeSink implementation for building DOM trees during HTML parsing.

use crate::attributes;
use crate::tree::NodeRef;
use html5ever::tendril::StrTendril;
use html5ever::tree_builder::{ElementFlags, NodeOrText, QuirksMode, TreeSink};
use html5ever::{Attribute, ExpandedName, QualName};
use std::borrow::Cow;
use std::cell::RefCell;

/// Type alias for the parse error callback handler.
type ParseErrorHandler = RefCell<Option<Box<dyn FnMut(Cow<'static, str>)>>>;

/// Receives new tree nodes during parsing.
pub struct Sink {
    /// The root document node being constructed.
    pub(super) document_node: NodeRef,
    /// Optional callback for handling parse errors.
    pub(super) on_parse_error: ParseErrorHandler,
}

/// Implements TreeSink for Sink.
///
/// Provides the html5ever TreeSink interface for building a DOM tree during
/// HTML parsing. Handles node creation, tree manipulation, and parse error
/// callbacks as the parser processes HTML content.
impl TreeSink for Sink {
    type Output = NodeRef;

    fn finish(self) -> NodeRef {
        self.document_node
    }

    type Handle = NodeRef;

    type ElemName<'a>
        = ExpandedName<'a>
    where
        Self: 'a;

    #[inline]
    fn parse_error(&self, message: Cow<'static, str>) {
        if let Some(ref mut handler) = *self.on_parse_error.borrow_mut() {
            handler(message)
        }
    }

    #[inline]
    fn get_document(&self) -> NodeRef {
        self.document_node.clone()
    }

    #[inline]
    fn set_quirks_mode(&self, mode: QuirksMode) {
        self.document_node
            .as_document()
            .unwrap()
            ._quirks_mode
            .set(mode)
    }

    #[inline]
    fn same_node(&self, x: &NodeRef, y: &NodeRef) -> bool {
        x == y
    }

    #[inline]
    fn elem_name<'a>(&self, target: &'a NodeRef) -> ExpandedName<'a> {
        target.as_element().unwrap().name.expanded()
    }

    #[inline]
    fn create_element(
        &self,
        name: QualName,
        attrs: Vec<Attribute>,
        _flags: ElementFlags,
    ) -> NodeRef {
        NodeRef::new_element(
            name,
            attrs.into_iter().map(|attr| {
                let Attribute {
                    name: QualName { prefix, ns, local },
                    value,
                } = attr;
                let value = String::from(value);
                (
                    attributes::ExpandedName { ns, local },
                    attributes::Attribute { prefix, value },
                )
            }),
        )
    }

    #[inline]
    fn create_comment(&self, text: StrTendril) -> NodeRef {
        NodeRef::new_comment(text)
    }

    #[inline]
    fn create_pi(&self, target: StrTendril, data: StrTendril) -> NodeRef {
        NodeRef::new_processing_instruction(target, data)
    }

    #[inline]
    fn append(&self, parent: &NodeRef, child: NodeOrText<NodeRef>) {
        match child {
            NodeOrText::AppendNode(node) => parent.append(node),
            NodeOrText::AppendText(text) => {
                if let Some(last_child) = parent.last_child() {
                    if let Some(existing) = last_child.as_text() {
                        existing.borrow_mut().push_str(&text);
                        return;
                    }
                }
                parent.append(NodeRef::new_text(text))
            }
        }
    }

    #[inline]
    fn append_before_sibling(&self, sibling: &NodeRef, child: NodeOrText<NodeRef>) {
        match child {
            NodeOrText::AppendNode(node) => sibling.insert_before(node),
            NodeOrText::AppendText(text) => {
                if let Some(previous_sibling) = sibling.previous_sibling() {
                    if let Some(existing) = previous_sibling.as_text() {
                        existing.borrow_mut().push_str(&text);
                        return;
                    }
                }
                sibling.insert_before(NodeRef::new_text(text))
            }
        }
    }

    #[inline]
    fn append_doctype_to_document(
        &self,
        name: StrTendril,
        public_id: StrTendril,
        system_id: StrTendril,
    ) {
        self.document_node
            .append(NodeRef::new_doctype(name, public_id, system_id))
    }

    #[inline]
    fn add_attrs_if_missing(&self, target: &NodeRef, attrs: Vec<Attribute>) {
        let element = target.as_element().unwrap();
        let mut attributes = element.attributes.borrow_mut();

        for Attribute {
            name: QualName { prefix, ns, local },
            value,
        } in attrs
        {
            attributes
                .map
                .entry(attributes::ExpandedName { ns, local })
                .or_insert_with(|| {
                    let value = String::from(value);
                    attributes::Attribute { prefix, value }
                });
        }
    }

    #[inline]
    fn remove_from_parent(&self, target: &NodeRef) {
        target.detach()
    }

    #[inline]
    fn reparent_children(&self, node: &NodeRef, new_parent: &NodeRef) {
        for child in node.children() {
            new_parent.append(child)
        }
    }

    #[inline]
    fn mark_script_already_started(&self, _node: &NodeRef) {
        // No-op: Script execution tracking is only relevant in browser environments.
        // Server-side HTML parsing and manipulation doesn't need to track whether
        // scripts have been executed, so this TreeSink method is intentionally empty.
    }

    #[inline]
    fn get_template_contents(&self, target: &NodeRef) -> NodeRef {
        target
            .as_element()
            .unwrap()
            .template_contents
            .clone()
            .unwrap()
    }

    fn append_based_on_parent_node(
        &self,
        element: &NodeRef,
        prev_element: &NodeRef,
        child: NodeOrText<NodeRef>,
    ) {
        if element.parent().is_some() {
            self.append_before_sibling(element, child)
        } else {
            self.append(prev_element, child)
        }
    }
}

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

    /// Tests that create_pi creates a processing instruction node.
    ///
    /// Verifies the TreeSink implementation can create PI nodes even though
    /// the HTML5 parser doesn't normally generate them.
    #[test]
    fn create_pi() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        let pi = sink.create_pi(
            StrTendril::from("xml-stylesheet"),
            StrTendril::from("href=\"style.css\""),
        );

        let pi_data = pi.as_processing_instruction().expect("Should be a PI node");
        let (target, data) = &*pi_data.borrow();
        assert_eq!(target, "xml-stylesheet");
        assert_eq!(data, "href=\"style.css\"");
    }

    /// Tests append_before_sibling with a node.
    ///
    /// Verifies that nodes can be inserted before a sibling in the tree.
    #[test]
    fn append_before_sibling_with_node() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        let parent = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("div")),
            std::iter::empty(),
        );
        let sibling = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("span")),
            std::iter::empty(),
        );
        let new_node = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("p")),
            std::iter::empty(),
        );

        parent.append(sibling.clone());
        sink.append_before_sibling(&sibling, NodeOrText::AppendNode(new_node.clone()));

        // Verify the new node is before the sibling
        assert_eq!(parent.children().count(), 2);
        let first = parent.first_child().unwrap();
        assert_eq!(first.as_element().unwrap().name.local.as_ref(), "p");
        let second = first.next_sibling().unwrap();
        assert_eq!(second.as_element().unwrap().name.local.as_ref(), "span");
    }

    /// Tests append_before_sibling with text that gets coalesced.
    ///
    /// Verifies that text nodes are merged with previous text siblings
    /// when inserting before an element.
    #[test]
    fn append_before_sibling_with_text_coalesce() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        let parent = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("div")),
            std::iter::empty(),
        );
        let text1 = NodeRef::new_text("Hello ");
        let sibling = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("span")),
            std::iter::empty(),
        );

        parent.append(text1.clone());
        parent.append(sibling.clone());

        // Append text before the span - should coalesce with previous text
        sink.append_before_sibling(&sibling, NodeOrText::AppendText(StrTendril::from("World")));

        // Should have coalesced into the first text node
        assert_eq!(parent.children().count(), 2);
        let first = parent.first_child().unwrap();
        let text_content: &str = &first.as_text().unwrap().borrow();
        assert_eq!(text_content, "Hello World");
    }

    /// Tests append_before_sibling with text creating a new node.
    ///
    /// Verifies that a new text node is created when there's no previous
    /// text sibling to coalesce with.
    #[test]
    fn append_before_sibling_with_text_new_node() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        let parent = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("div")),
            std::iter::empty(),
        );
        let element = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("p")),
            std::iter::empty(),
        );
        let sibling = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("span")),
            std::iter::empty(),
        );

        parent.append(element);
        parent.append(sibling.clone());

        // Append text before the span - previous sibling is element, not text
        sink.append_before_sibling(&sibling, NodeOrText::AppendText(StrTendril::from("Hello")));

        // Should have created a new text node
        assert_eq!(parent.children().count(), 3);
        let children: Vec<_> = parent.children().collect();
        assert_eq!(children[0].as_element().unwrap().name.local.as_ref(), "p");
        let text_content: &str = &children[1].as_text().unwrap().borrow();
        assert_eq!(text_content, "Hello");
        assert_eq!(
            children[2].as_element().unwrap().name.local.as_ref(),
            "span"
        );
    }

    /// Tests add_attrs_if_missing adds new attributes.
    ///
    /// Verifies that attributes not already present are added to an element.
    #[test]
    fn add_attrs_if_missing_adds_new() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        let element = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("div")),
            vec![(
                attributes::ExpandedName {
                    ns: ns!(),
                    local: local_name!("id"),
                },
                attributes::Attribute {
                    prefix: None,
                    value: "test".to_string(),
                },
            )],
        );

        let new_attrs = vec![Attribute {
            name: QualName::new(None, ns!(), local_name!("class")),
            value: StrTendril::from("container"),
        }];

        sink.add_attrs_if_missing(&element, new_attrs);

        let attrs = element.as_element().unwrap().attributes.borrow();
        assert_eq!(attrs.get("id"), Some("test"));
        assert_eq!(attrs.get("class"), Some("container"));
    }

    /// Tests add_attrs_if_missing doesn't overwrite existing attributes.
    ///
    /// Verifies that existing attributes are preserved when adding new ones.
    #[test]
    fn add_attrs_if_missing_preserves_existing() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        let element = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("div")),
            vec![(
                attributes::ExpandedName {
                    ns: ns!(),
                    local: local_name!("id"),
                },
                attributes::Attribute {
                    prefix: None,
                    value: "original".to_string(),
                },
            )],
        );

        let new_attrs = vec![
            Attribute {
                name: QualName::new(None, ns!(), local_name!("id")),
                value: StrTendril::from("should-not-replace"),
            },
            Attribute {
                name: QualName::new(None, ns!(), local_name!("class")),
                value: StrTendril::from("container"),
            },
        ];

        sink.add_attrs_if_missing(&element, new_attrs);

        let attrs = element.as_element().unwrap().attributes.borrow();
        // Original id should be preserved
        assert_eq!(attrs.get("id"), Some("original"));
        // New class should be added
        assert_eq!(attrs.get("class"), Some("container"));
    }

    /// Tests parse_error callback when handler is set.
    ///
    /// Verifies that parse error callbacks are invoked when provided.
    #[test]
    fn parse_error_with_callback() {
        use std::sync::{Arc, Mutex};

        let error_messages = Arc::new(Mutex::new(Vec::new()));
        let error_messages_clone = Arc::clone(&error_messages);

        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(Some(Box::new(move |msg: Cow<'static, str>| {
                error_messages_clone.lock().unwrap().push(msg.into_owned());
            }))),
        };

        sink.parse_error(Cow::Borrowed("Test error 1"));
        sink.parse_error(Cow::Borrowed("Test error 2"));

        let messages = error_messages.lock().unwrap();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0], "Test error 1");
        assert_eq!(messages[1], "Test error 2");
    }

    /// Tests parse_error without callback doesn't panic.
    ///
    /// Verifies that parse errors are handled gracefully when no callback
    /// is provided.
    #[test]
    fn parse_error_without_callback() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        // Should not panic
        sink.parse_error(Cow::Borrowed("This error is ignored"));
    }

    /// Tests append_based_on_parent_node when element has parent.
    ///
    /// Verifies that the method delegates to append_before_sibling when
    /// the element has a parent.
    #[test]
    fn append_based_on_parent_node_with_parent() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        let parent = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("div")),
            std::iter::empty(),
        );
        let element = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("span")),
            std::iter::empty(),
        );
        let prev_element = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("p")),
            std::iter::empty(),
        );

        parent.append(element.clone());

        let new_node = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("b")),
            std::iter::empty(),
        );

        // Element has a parent, so should use append_before_sibling
        sink.append_based_on_parent_node(
            &element,
            &prev_element,
            NodeOrText::AppendNode(new_node.clone()),
        );

        // New node should be inserted before element in parent
        let children: Vec<_> = parent.children().collect();
        assert_eq!(children.len(), 2);
        assert_eq!(children[0].as_element().unwrap().name.local.as_ref(), "b");
        assert_eq!(
            children[1].as_element().unwrap().name.local.as_ref(),
            "span"
        );
    }

    /// Tests append_based_on_parent_node when element has no parent.
    ///
    /// Verifies that the method delegates to append when the element
    /// has no parent.
    #[test]
    fn append_based_on_parent_node_without_parent() {
        let sink = Sink {
            document_node: NodeRef::new_document(),
            on_parse_error: RefCell::new(None),
        };

        let element = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("span")),
            std::iter::empty(),
        );
        let prev_element = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("p")),
            std::iter::empty(),
        );

        let new_node = NodeRef::new_element(
            QualName::new(None, ns!(html), local_name!("b")),
            std::iter::empty(),
        );

        // Element has no parent, so should use append to prev_element
        sink.append_based_on_parent_node(
            &element,
            &prev_element,
            NodeOrText::AppendNode(new_node.clone()),
        );

        // New node should be appended to prev_element
        let children: Vec<_> = prev_element.children().collect();
        assert_eq!(children.len(), 1);
        assert_eq!(children[0].as_element().unwrap().name.local.as_ref(), "b");
    }
}