pochoir-parser 0.12.2

HTML parser for the pochoir template engine
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
use pochoir_common::Spanned;
use pochoir_template_engine::{Escaping, TemplateBlock};
use selectors::{
    context::{MatchingForInvalidation, NeedsSelectorFlags, SelectorCaches},
    matching,
    parser::SelectorList,
};
use std::{borrow::Cow, fmt};

use super::{build_selector_list, selection::InnerSelector, Tree, TreeNode, TreeRefId};
use crate::{Error, Node, OwnedTree, ParsedNode, Result};

/// A reference to a node in the tree.
#[derive(Clone, Copy)]
pub struct TreeRef<'a, 'b> {
    /// A unique ID identifying the node in the tree.
    pub id: TreeRefId,

    /// The tree owning this node.
    pub tree: &'b Tree<'a>,
}

impl<'a, 'b> TreeRef<'a, 'b> {
    #[allow(clippy::panic)]
    fn inner(&self) -> &TreeNode<'a> {
        self.tree.nodes.get(&self.id).unwrap_or_else(|| {
            panic!(
                "failed to find the current node (id {:?}) in the tree",
                self.id
            )
        })
    }

    pub fn id(&self) -> TreeRefId {
        self.id
    }

    /// Get an immutable reference to the underlying [`ParsedNode`] containing the [`Node`] and the
    /// location of the span of text where it was defined.
    ///
    /// # Panics
    ///
    /// Panics if the node does not exist in the tree (it could have been removed).
    pub fn spanned_data(&self) -> &ParsedNode<'a> {
        &self.inner().data
    }

    /// Get an immutable reference to the underlying [`Node`].
    ///
    /// # Panics
    ///
    /// Panics if the node does not exist in the tree (it could have been removed).
    pub fn data(&self) -> &Node<'a> {
        &self.inner().data
    }

    /// Get a reference to the parent of this node.
    #[must_use]
    pub fn parent(&self) -> Self {
        Self {
            id: self.inner().parent,
            tree: self.tree,
        }
    }

    /// Search all parents of the node until it finds a node matching the provided CSS selector.
    ///
    /// Returns `None` if the selector is invalid or if a node matching the selector could not be
    /// found.
    ///
    /// This method is equivalent to the [`Element.closest`](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest) method in Javascript.
    pub fn closest(&self, selector: &str) -> Option<Self> {
        let mut tree_ref = *self;
        let selector_list = build_selector_list(selector).ok()?;

        loop {
            if tree_ref.is_matching(&selector_list) {
                return Some(tree_ref);
            } else if tree_ref.id == TreeRefId::Root {
                return None;
            }

            tree_ref = tree_ref.parent();
        }
    }

    /// Get a reference to the previous sibling of this node.
    pub fn prev_sibling(&self) -> Option<Self> {
        let parent = self.parent();
        let mut children = parent.children().peekable();

        let mut id = None;
        while let Some(c) = children.next() {
            if children.peek().is_some_and(|c| c.id == self.id) {
                id = Some(c.id);
                break;
            }
        }

        id.map(|id| Self {
            id,
            tree: self.tree,
        })
    }

    /// Get a reference to the next sibling of this node.
    pub fn next_sibling(&self) -> Option<Self> {
        let parent = self.parent();
        let mut children = parent.children().peekable();

        let mut id = None;
        while let Some(c) = children.next() {
            if c.id == self.id {
                id = children.peek().map(|c| c.id);
                break;
            }
        }

        id.map(|id| Self {
            id,
            tree: self.tree,
        })
    }

    /// Get a list of references of the children of this node.
    pub fn children<'c>(&'c self) -> impl Iterator<Item = TreeRef<'a, 'b>> + 'c {
        self.inner().children.iter().map(|id| self.tree.get(*id))
    }

    /// Get a cloned list of IDs of this node children.
    pub fn children_id(&self) -> Vec<TreeRefId> {
        self.inner().children.clone()
    }

    /// Search the first node matching the CSS selector in the tree, relatively to this node.
    ///
    /// The traversal order used is the same as in the [official DOM specification](https://dom.spec.whatwg.org/#concept-tree-order)
    /// ie preorder, depth-first.
    ///
    /// It is similar to the `document.querySelector` function in JavaScript.
    ///
    /// # Errors
    ///
    /// Returns [`selectors::parser::SelectorParseError`] if the CSS selector is not a valid CSS selector
    /// or `Ok(None)` if no node matching the CSS selector is found in the tree
    pub fn select<'c>(
        &self,
        selector: &'c str,
    ) -> std::result::Result<Option<TreeRef<'_, '_>>, crate::error::SelectorParseError<'c>> {
        let selector_list = build_selector_list(selector)?;
        Ok(self
            .traverse_depth()
            .find(|tree_ref| tree_ref.is_matching(&selector_list)))
    }

    /// Select several nodes in the tree, relatively to this node, using a CSS selector.
    ///
    /// It is similar to the `document.querySelectorAll` function in JavaScript.
    ///
    /// Returns an empty `Vec` if the selector is not a valid CSS selector.
    pub fn select_all(&self, selector: &str) -> Vec<TreeRef<'_, '_>> {
        if let Ok(selector_list) = build_selector_list(selector) {
            self.traverse_depth()
                .filter(|tree_ref| tree_ref.is_matching(&selector_list))
                .collect()
        } else {
            vec![]
        }
    }

    /// Get the element name of the [`TreeRef`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::BadNodeType`] if the underlying node is not a [`Node::Element`].
    ///
    /// [`Node::Element`]: crate::Node::Element
    pub fn name(&self) -> Result<Cow<'a, str>> {
        if let Node::Element(ref name, _) = self.data() {
            Ok(name.clone())
        } else {
            Err(Spanned::new(Error::BadNodeType {
                expected: "Element",
                found: self.data().node_type(),
            }))
        }
    }

    /// Get the text of the [`TreeRef`].
    ///
    /// Returns the concatenated text content of child nodes if it is a [`Node::Element`].
    ///
    /// Returns the text content if it is a [`Node::TemplateBlock(TemplateBlock::RawText(_))`](`Node::TemplateBlock`).
    ///
    /// All template expressions and statements just return their raw content with no spaces inside
    /// their delimiters (will return `{{expr}}` even if it was `{{ expr }}`, `{!expr!}` event if
    /// it was `{! expr !}` and `{%stmt%}` even if it was `{% stmt %}`).
    ///
    /// [`Node::Element`]: crate::Node::Element
    /// [`Node::Text`]: crate::Node::Text
    pub fn text(&self) -> Cow<'a, str> {
        match self.data() {
            Node::Element(_, _) => {
                let children = self.children();
                Cow::Owned(children.into_iter().map(|child| child.text()).collect())
            }
            Node::TemplateBlock(block) => Cow::Owned(match block {
                TemplateBlock::RawText(t) => t.to_string(),
                TemplateBlock::Expr(t, is_escaped) => {
                    if *is_escaped {
                        format!("{{{{{t}}}}}")
                    } else {
                        format!("{{!{t}!}}")
                    }
                }
                TemplateBlock::Stmt(t) => format!("{{%{t}%}}"),
            }),
            _ => Cow::Borrowed(""),
        }
    }

    /// Get the value of an attribute belonging to a [`Node::Element`].
    ///
    /// All template expressions and statements just return their raw content with no spaces inside
    /// their delimiters (will return `{{expr}}` even if it was `{{ expr }}`, `{!expr!}` event if
    /// it was `{! expr !}` and `{%stmt%}` even if it was `{% stmt %}`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::BadNodeType`] if the underlying node is not a [`Node::Element`].
    ///
    /// Returns `None` if the attribute is not present.
    ///
    /// Returns `Some("")` if the attribute is present but does not have a value (e.g. in `<input
    /// type="checkbox" checked>`, the `checked` HTML attribute is present but does not have a value).
    ///
    /// Returns `Some(value)` if the attribute is present and does have a value.
    pub fn attr(&self, name: &str) -> Result<Option<String>> {
        if let Node::Element(_, ref attrs) = self.data() {
            Ok(attrs.get(Cow::Borrowed(name)).map(|a| {
                a.iter()
                    .map(|b| match &**b {
                        TemplateBlock::RawText(t) => t.to_string(),
                        TemplateBlock::Expr(t, is_escaped) => {
                            if *is_escaped {
                                format!("{{{{{t}}}}}")
                            } else {
                                format!("{{!{t}!}}")
                            }
                        }
                        TemplateBlock::Stmt(t) => format!("{{%{t}%}}"),
                    })
                    .collect::<String>()
            }))
        } else {
            Err(Spanned::new(Error::BadNodeType {
                expected: "Element",
                found: self.data().node_type(),
            }))
        }
    }

    /// Get the value of an attribute belonging to a [`Node::Element`].
    ///
    /// Template expressions and statements can be returned.
    ///
    /// # Errors
    ///
    /// Returns [`Error::BadNodeType`] if the underlying node is not a [`Node::Element`].
    ///
    /// Returns `None` if the attribute is not present.
    pub fn attr_spanned(&self, name: &str) -> Result<Option<Vec<Spanned<TemplateBlock<'_>>>>> {
        if let Node::Element(_, ref attrs) = self.data() {
            Ok(attrs.get(Cow::Borrowed(name)).cloned())
        } else {
            Err(Spanned::new(Error::BadNodeType {
                expected: "Element",
                found: self.data().node_type(),
            }))
        }
    }

    /// Get all attributes belonging to a [`Node::Element`].
    ///
    /// All template expressions and statements just return their raw content with no spaces inside
    /// their delimiters (will return `{{expr}}` even if it was `{{ expr }}`, `{!expr!}` event if
    /// it was `{! expr !}` and `{%stmt%}` even if it was `{% stmt %}`).
    ///
    /// An empty attribute value means that an attribute key was given without a value. See
    /// [`TreeRef::attr`] for more information.
    ///
    /// # Errors
    ///
    /// Returns [`Error::BadNodeType`] if the underlying node is not a [`Node::Element`].
    pub fn attrs(&self) -> Result<impl Iterator<Item = (&Cow<'_, str>, String)>> {
        if let Node::Element(_, ref attrs) = self.data() {
            Ok(attrs.iter().map(|(k, v)| {
                (
                    &**k,
                    v.iter()
                        .map(|b| match &**b {
                            TemplateBlock::RawText(t) => t.to_string(),
                            TemplateBlock::Expr(t, is_escaped) => {
                                if *is_escaped {
                                    format!("{{{{{t}}}}}")
                                } else {
                                    format!("{{!{t}!}}")
                                }
                            }
                            TemplateBlock::Stmt(t) => format!("{{%{t}%}}"),
                        })
                        .collect::<String>(),
                )
            }))
        } else {
            Err(Spanned::new(Error::BadNodeType {
                expected: "Element",
                found: self.data().node_type(),
            }))
        }
    }

    /// Get all attributes belonging to a [`Node::Element`].
    ///
    /// Template expressions and statements can be returned.
    ///
    /// # Errors
    ///
    /// Returns [`Error::BadNodeType`] if the underlying node is not a [`Node::Element`].
    pub fn attrs_spanned(&self) -> Result<impl Iterator<Item = &crate::Attr<'_>>> {
        if let Node::Element(_, ref attrs) = self.data() {
            Ok(attrs.iter())
        } else {
            Err(Spanned::new(Error::BadNodeType {
                expected: "Element",
                found: self.data().node_type(),
            }))
        }
    }

    pub fn sub_tree(&self) -> Tree<'a> {
        let mut tree = Tree::new(self.tree.file_path());

        // Prevent any ID collision
        tree.next_id = self.tree.next_id;

        for tree_ref in self.traverse_depth() {
            let parent_id = if tree_ref.parent().id() == self.id() {
                TreeRefId::Root
            } else {
                tree_ref.parent().id()
            };

            tree.insert_with_id(
                tree_ref.id(),
                parent_id,
                tree_ref.children_id(),
                tree_ref.spanned_data().clone(),
            );

            if parent_id == TreeRefId::Root {
                tree.get_mut(TreeRefId::Root)
                    .inner_mut()
                    .children
                    .push(tree_ref.id());
            }
        }
        tree
    }

    pub fn traverse_breadth(&self) -> impl Iterator<Item = TreeRef<'a, '_>> {
        let parent = self.tree.get(self.id);

        super::traverse::TraverseBreadthIter {
            children: parent.children().collect(),
            index: 0,
        }
    }

    pub fn traverse_depth(&self) -> impl Iterator<Item = TreeRef<'a, '_>> {
        let mut queue: Vec<TreeRef> = self.tree.get(self.id).children().collect();
        queue.reverse();

        super::traverse::TraverseDepthIter { queue }
    }

    pub fn is_matching(&self, selector_list: &SelectorList<InnerSelector>) -> bool {
        let mut nth_index_cache = SelectorCaches::default();
        let mut ctx = matching::MatchingContext::new(
            matching::MatchingMode::Normal,
            None,
            &mut nth_index_cache,
            matching::QuirksMode::NoQuirks,
            NeedsSelectorFlags::No,
            MatchingForInvalidation::No,
        );

        matching::matches_selector_list(selector_list, self, &mut ctx)
    }
}

impl PartialEq for TreeRef<'_, '_> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl fmt::Debug for TreeRef<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TreeRef")
            .field("id", &self.id)
            .field("__inner_node", &self.data())
            .finish()
    }
}

/// A mutable reference to a node in the tree.
pub struct TreeRefMut<'a, 'b> {
    /// A unique ID identifying the node in the tree.
    pub id: TreeRefId,

    /// The tree owning this node.
    pub tree: &'b mut Tree<'a>,
}

impl<'a, 'b> TreeRefMut<'a, 'b> {
    #[allow(clippy::panic)]
    fn inner(&self) -> &TreeNode<'a> {
        self.tree.nodes.get(&self.id).unwrap_or_else(|| {
            panic!(
                "failed to find the current node (id {:?}) in the tree (mutable)",
                self.id
            )
        })
    }

    #[allow(clippy::panic)]
    fn inner_mut(&mut self) -> &mut TreeNode<'a> {
        self.tree.nodes.get_mut(&self.id).unwrap_or_else(|| {
            panic!(
                "failed to find the current node (id {:?}) in the tree (mutable)",
                self.id
            )
        })
    }

    pub fn id(&self) -> TreeRefId {
        self.id
    }

    pub fn as_ref(&self) -> TreeRef<'a, '_> {
        TreeRef {
            id: self.id,
            tree: self.tree,
        }
    }

    /// Get a mutable reference to the underlying [`Node`].
    ///
    /// # Panics
    ///
    /// Panics if the node does not exist in the tree (it could have been removed).
    pub fn data(&mut self) -> &mut Node<'a> {
        &mut self.inner_mut().data
    }

    /// Get an mutable reference to the underlying [`ParsedNode`] containing the [`Node`] and the
    /// location of the span of text where it was defined.
    ///
    /// # Panics
    ///
    /// Panics if the node does not exist in the tree (it could have been removed).
    pub fn spanned_data(&mut self) -> &mut ParsedNode<'a> {
        &mut self.inner_mut().data
    }

    /// Get a reference to the parent of this node.
    pub fn parent(&mut self) -> TreeRefMut<'a, '_> {
        TreeRefMut {
            id: self.inner().parent,
            tree: self.tree,
        }
    }

    /// Get a reference to the previous sibling of this node.
    pub fn prev_sibling(&'b mut self) -> Option<Self> {
        let parent = self.as_ref().parent();
        let mut children = parent.children().peekable();

        let mut id = None;
        while let Some(c) = children.next() {
            if children.peek().is_some_and(|c| c.id == self.id) {
                id = Some(c.id);
                break;
            }
        }

        drop(children);
        id.map(|id| Self {
            id,
            tree: self.tree,
        })
    }

    /// Get a reference to the next sibling of this node.
    pub fn next_sibling(&'b mut self) -> Option<Self> {
        let parent = self.as_ref().parent();
        let mut children = parent.children().peekable();

        let mut id = None;
        while let Some(c) = children.next() {
            if c.id == self.id {
                id = children.peek().map(|c| c.id);
                break;
            }
        }

        drop(children);
        id.map(|id| Self {
            id,
            tree: self.tree,
        })
    }

    /// Set the text of the [`TreeRef`] while escaping the content using the provided [`Escaping`]
    /// variant (if you are lazy, you can use [`Escaping::default`] as a safe default).
    ///
    /// Replaces **all the children** with the provided text if it is a [`Node::Element`].
    ///
    /// Updates the text content if it is a [`Node::TemplateBlock(TemplateBlock::RawText(_))`](`Node::TemplateBlock`).
    ///
    /// Does nothing if the node is neither a [`Node::Element`] nor a [`Node::TemplateBlock(TemplateBlock::RawText(_))`](`Node::TemplateBlock`).
    ///
    /// [`Node::Element`]: crate::Node::Element
    /// [`Node::Text`]: crate::Node::Text
    pub fn set_text<T: Into<Cow<'a, str>>>(&mut self, new_text: T, escaping: Escaping) {
        match self.as_ref().data() {
            Node::Element(..) => {
                // Remove all the children of this node
                let children = self.as_ref().children_id();

                for child in children {
                    self.tree.get_mut(child).remove();
                }

                // Escape the text
                let new_text_escaped = escaping.escape(new_text.into());

                // Append a new text node and add it to the list of children
                self.tree.insert(
                    self.id,
                    Spanned::new(Node::TemplateBlock(TemplateBlock::RawText(
                        new_text_escaped,
                    ))),
                );
            }
            Node::TemplateBlock(_) => {
                if let Node::TemplateBlock(TemplateBlock::RawText(ref mut t)) = self.data() {
                    *t = new_text.into();
                }
            }
            _ => (),
        }
    }

    /// Set the value of an attribute belonging to a [`Node::Element`].
    ///
    /// The value of the attribute will be updated if it already exists or a new entry will be
    /// inserted.
    ///
    /// The second argument should be `""` (an empty string) if the attribute has no value.
    ///
    /// This method does nothing if not called on a [`Node::Element`].
    pub fn set_attr<A: Into<Cow<'a, str>>, B: Into<Cow<'a, str>>>(
        &mut self,
        key: A,
        val: B,
        escaping: Escaping,
    ) {
        if let Node::Element(_, ref mut attrs) = self.tree.get_mut(self.id).data() {
            attrs.insert(
                key.into(),
                vec![Spanned::new(TemplateBlock::RawText(
                    escaping.escape(val.into()),
                ))],
            );
        }
    }

    /// Remove an attribute belonging to a [`Node::Element`].
    ///
    /// This method does nothing if the attribute key does not exist.
    pub fn remove_attr<'c, A: Into<Cow<'c, str>>>(&mut self, key: A) {
        if let Node::Element(_, ref mut attrs) = self.tree.get_mut(self.id).data() {
            attrs.remove(key.into());
        }
    }

    /// Replace the current [`Node`] with one or more [`Node`]s of a [`Tree`].
    ///
    /// This function consumes the [`TreeRefMut`] to avoid using a node that was removed.
    ///
    /// # Panics
    ///
    /// This function panics if the node is not found in its parent children. If it happens, it is
    /// a bug in `pochoir-parser` not a bug in your code.
    pub fn replace_node(self, tree: &Tree<'a>) {
        // Get the index of the current node in its parent children
        let current_index = self
            .as_ref()
            .parent()
            .inner()
            .children
            .iter()
            .position(|id| *id == self.id)
            .expect("failed to find the node in its parent children");

        let offset = self.tree.next_id();

        // Remove the node and the reference of it in the parent list of children
        let parent_id = self.as_ref().parent().id();

        let mut inserted_nodes = 0;
        let mut max_offset_node = offset;

        for tree_ref in tree.traverse_depth() {
            let is_root_node = tree_ref.parent().id() == TreeRefId::Root;
            let children = tree_ref.children_id().iter().map(|c| *c + offset).collect();

            self.tree.insert_with_id(
                tree_ref.id + offset,
                if is_root_node {
                    parent_id
                } else {
                    tree_ref.parent().id() + offset
                },
                children,
                tree_ref.spanned_data().clone(),
            );

            if tree_ref.id + offset > max_offset_node {
                max_offset_node = tree_ref.id + offset;
            }

            if is_root_node {
                self.tree
                    .get_mut(parent_id)
                    .inner_mut()
                    .children
                    .insert(current_index + inserted_nodes, tree_ref.id() + offset);

                inserted_nodes += 1;
            }
        }

        self.tree.next_id = max_offset_node + 1;

        self.remove();
    }

    /// Prepend the [`Node`]s of a [`Tree`] to the list of children of the current node.
    pub fn prepend_children(&mut self, tree: &Tree<'a>) {
        let offset = self.tree.next_id();
        let mut inserted_nodes = 0;
        let mut max_offset_node = offset;

        for tree_ref in tree.traverse_depth() {
            let is_root_node = tree_ref.parent().id() == TreeRefId::Root;
            let children = tree_ref.children_id().iter().map(|c| *c + offset).collect();

            self.tree.insert_with_id(
                tree_ref.id + offset,
                if is_root_node {
                    self.id()
                } else {
                    tree_ref.parent().id() + offset
                },
                children,
                tree_ref.spanned_data().clone(),
            );

            if tree_ref.id + offset > max_offset_node {
                max_offset_node = tree_ref.id + offset;
            }

            if is_root_node {
                self.inner_mut()
                    .children
                    .insert(inserted_nodes, tree_ref.id() + offset);

                inserted_nodes += 1;
            }
        }

        self.tree.next_id = max_offset_node + 1;
    }

    /// Append the [`Node`]s of a [`Tree`] to the list of children of the current node.
    pub fn append_children(&mut self, tree: &Tree<'a>) {
        let offset = self.tree.next_id();
        let mut max_offset_node = offset;

        for tree_ref in tree.traverse_depth() {
            let is_root_node = tree_ref.parent().id() == TreeRefId::Root;
            let children = tree_ref.children_id().iter().map(|c| *c + offset).collect();

            self.tree.insert_with_id(
                tree_ref.id + offset,
                if is_root_node {
                    self.id()
                } else {
                    tree_ref.parent().id() + offset
                },
                children,
                tree_ref.spanned_data().clone(),
            );

            if tree_ref.id + offset > max_offset_node {
                max_offset_node = tree_ref.id + offset;
            }

            if is_root_node {
                self.inner_mut().children.push(tree_ref.id() + offset);
            }
        }

        self.tree.next_id = max_offset_node + 1;
    }

    /// Replace the current [`Node`] with one or more [`Node`]s of a [`OwnedTree`].
    ///
    /// This function consumes the [`TreeRefMut`] to avoid using a node that was removed.
    ///
    /// # Panics
    ///
    /// This function panics if the node is not found in its parent children. If it happens, it is
    /// a bug in `pochoir-parser` not a bug in your code.
    pub fn replace_node_owned(self, tree: &OwnedTree) {
        // Get the index of the current node in its parent children
        let current_index = self
            .as_ref()
            .parent()
            .inner()
            .children
            .iter()
            .position(|id| *id == self.id)
            .expect("failed to find the node in its parent children");

        let offset = self.tree.next_id();

        // Remove the node and the reference of it in the parent list of children
        let parent_id = self.as_ref().parent().id();

        let mut inserted_nodes = 0;
        let mut max_offset_node = offset;

        for tree_ref in tree.get_tree().traverse_depth() {
            let is_root_node = tree_ref.parent().id() == TreeRefId::Root;
            let children = tree_ref.children_id().iter().map(|c| *c + offset).collect();

            self.tree.insert_with_id(
                tree_ref.id + offset,
                if is_root_node {
                    parent_id
                } else {
                    tree_ref.parent().id() + offset
                },
                children,
                tree_ref
                    .spanned_data()
                    .clone()
                    .map_spanned(Node::deep_clone),
            );

            if tree_ref.id + offset > max_offset_node {
                max_offset_node = tree_ref.id + offset;
            }

            if is_root_node {
                self.tree
                    .get_mut(parent_id)
                    .inner_mut()
                    .children
                    .insert(current_index + inserted_nodes, tree_ref.id() + offset);

                inserted_nodes += 1;
            }
        }

        self.tree.next_id = max_offset_node + 1;

        self.remove();
    }

    /// Prepend the [`Node`]s of a [`OwnedTree`] to the list of children of the current node.
    pub fn prepend_children_owned(&mut self, tree: &OwnedTree) {
        let offset = self.tree.next_id();
        let mut inserted_nodes = 0;
        let mut max_offset_node = offset;

        for tree_ref in tree.get_tree().traverse_depth() {
            let is_root_node = tree_ref.parent().id() == TreeRefId::Root;
            let children = tree_ref.children_id().iter().map(|c| *c + offset).collect();

            self.tree.insert_with_id(
                tree_ref.id + offset,
                if is_root_node {
                    self.id()
                } else {
                    tree_ref.parent().id() + offset
                },
                children,
                tree_ref
                    .spanned_data()
                    .clone()
                    .map_spanned(Node::deep_clone),
            );

            if tree_ref.id + offset > max_offset_node {
                max_offset_node = tree_ref.id + offset;
            }

            if is_root_node {
                self.inner_mut()
                    .children
                    .insert(inserted_nodes, tree_ref.id() + offset);

                inserted_nodes += 1;
            }
        }

        self.tree.next_id = max_offset_node + 1;
    }

    /// Append the [`Node`]s of a [`OwnedTree`] to the list of children of the current node.
    pub fn append_children_owned(&mut self, tree: &OwnedTree) {
        let offset = self.tree.next_id();
        let mut max_offset_node = offset;

        for tree_ref in tree.get_tree().traverse_depth() {
            let is_root_node = tree_ref.parent().id() == TreeRefId::Root;
            let children = tree_ref.children_id().iter().map(|c| *c + offset).collect();

            self.tree.insert_with_id(
                tree_ref.id + offset,
                if is_root_node {
                    self.id()
                } else {
                    tree_ref.parent().id() + offset
                },
                children,
                tree_ref
                    .spanned_data()
                    .clone()
                    .map_spanned(Node::deep_clone),
            );

            if tree_ref.id + offset > max_offset_node {
                max_offset_node = tree_ref.id + offset;
            }

            if is_root_node {
                self.inner_mut().children.push(tree_ref.id() + offset);
            }
        }

        self.tree.next_id = max_offset_node + 1;
    }

    /// Replace the outer HTML of the [`TreeRefMut`].
    ///
    /// # Errors
    ///
    /// Returns an error if parsing the HTML failed.
    pub fn replace_html<T: Into<Cow<'a, str>>>(self, file_path: &str, html: T) -> Result<()> {
        let html = html.into();

        if let Cow::Borrowed(html) = html {
            let tree = crate::parse(file_path, html)?;
            self.replace_node(&tree);
        } else if let Cow::Owned(html) = html {
            let tree = crate::parse_owned(file_path, &html)?;
            self.replace_node_owned(&tree);
        }
        Ok(())
    }

    /// Prepend HTML as children of the current [`TreeRefMut`].
    ///
    /// # Errors
    ///
    /// Returns an error if parsing the HTML failed.
    pub fn prepend_html<T: Into<Cow<'a, str>>>(&mut self, file_path: &str, html: T) -> Result<()> {
        let html = html.into();

        if let Cow::Borrowed(html) = html {
            let tree = crate::parse(file_path, html)?;
            self.prepend_children(&tree);
        } else if let Cow::Owned(html) = html {
            let tree = crate::parse_owned(file_path, &html)?;
            self.prepend_children_owned(&tree);
        }
        Ok(())
    }

    /// Append HTML as children of the current [`TreeRefMut`].
    ///
    /// # Errors
    ///
    /// Returns an error if parsing the HTML failed.
    pub fn append_html<T: Into<Cow<'a, str>>>(&mut self, file_path: &str, html: T) -> Result<()> {
        let html = html.into();

        if let Cow::Borrowed(html) = html {
            let tree = crate::parse(file_path, html)?;
            self.append_children(&tree);
        } else if let Cow::Owned(html) = html {
            let tree = crate::parse_owned(file_path, &html)?;
            self.append_children_owned(&tree);
        }

        Ok(())
    }

    /// Remove the node from the tree.
    ///
    /// This function consumes the [`TreeRefMut`] to avoid using a node that was removed.
    ///
    /// # Panics
    ///
    /// This function panics if the node is not found in its parent children. If it happens, it is
    /// a bug in `pochoir-parser` not a bug in your code.
    pub fn remove(self) {
        // Remove in parent
        let node = &mut self.tree.get_mut(self.id);
        let parent = &mut node.parent();
        let parent_children = &mut parent.inner_mut().children;
        let index = parent_children
            .iter()
            .position(|c| c == &self.id)
            .expect("failed to find node in parent children");
        parent_children.remove(index);

        // Remove children
        let node = self.tree.get(self.id);
        let children = node.inner().children.clone();

        for child in children {
            self.tree.get_mut(child).remove();
        }

        // Remove from tree
        self.tree.nodes.remove(&self.id);
    }
}

impl PartialEq for TreeRefMut<'_, '_> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl fmt::Debug for TreeRefMut<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TreeRefMut")
            .field("id", &self.id)
            .field("__inner_node", &self.as_ref().data())
            .finish()
    }
}