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
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
use std::cell::{Ref, RefCell, RefMut};
use std::collections::HashMap;
use std::fmt;
use std::rc::{Rc, Weak};

use crate::{is_void_element, Html, IterableNodes};

/// Strong link
type Link = Rc<RefCell<DomNodeData>>;

type WeakLink = Weak<RefCell<DomNodeData>>;

/// Based on https://docs.rs/rctree/latest/rctree/struct.Node.html
pub struct DomNode(Link);

pub struct WeakDomNode(WeakLink);

#[derive(Debug, Clone, PartialEq)]
pub enum DomNodeKind {
    Text {
        text: String,
    },
    Element {
        tag: String,
        attributes: HashMap<String, String>,
    },
}

struct DomNodeData {
    kind: DomNodeKind,
    parent: Option<WeakLink>,
    first_child: Option<Link>,
    last_child: Option<WeakLink>,
    previous_sibling: Option<WeakLink>,
    next_sibling: Option<Link>,
}

/// Cloning a `Node` only increments a reference count. It does not copy the data.
impl Clone for DomNode {
    fn clone(&self) -> Self {
        DomNode(Rc::clone(&self.0))
    }
}

impl PartialEq for DomNode {
    fn eq(&self, other: &DomNode) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

impl fmt::Debug for DomNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.kind(), f)
    }
}

impl DomNode {
    /// Creates a new node
    pub fn new(kind: DomNodeKind) -> DomNode {
        DomNode(Rc::new(RefCell::new(DomNodeData {
            kind,
            parent: None,
            first_child: None,
            last_child: None,
            previous_sibling: None,
            next_sibling: None,
        })))
    }

    pub fn create_element(tag: impl Into<String>) -> DomNode {
        Self::new(DomNodeKind::Element {
            tag: tag.into(),
            attributes: HashMap::new(),
        })
    }

    pub fn create_element_with_attributes(
        tag: impl Into<String>,
        attributes: HashMap<String, String>,
    ) -> DomNode {
        Self::new(DomNodeKind::Element {
            tag: tag.into(),
            attributes,
        })
    }

    pub fn create_text(text: impl Into<String>) -> DomNode {
        Self::new(DomNodeKind::Text { text: text.into() })
    }

    pub fn get_attribute(&self, attribute: &str) -> Option<String> {
        match &*self.kind() {
            DomNodeKind::Text { .. } => None,
            DomNodeKind::Element { attributes, .. } => attributes.get(attribute).cloned(),
        }
    }

    pub fn set_attribute(&mut self, key: &str, value: &str) {
        if let DomNodeKind::Element { attributes, .. } = &mut *self.kind_mut() {
            attributes.insert(key.into(), value.into());
        }
    }

    /// Returns a weak referece to a node.
    pub fn downgrade(&self) -> WeakDomNode {
        WeakDomNode(Rc::downgrade(&self.0))
    }

    /// Returns a parent node, unless this node is the root of the tree.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutably borrowed.
    pub fn parent(&self) -> Option<DomNode> {
        Some(DomNode(self.0.borrow().parent.as_ref()?.upgrade()?))
    }

    /// Returns a first child of this node, unless it has no child.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutably borrowed.
    pub fn first_child(&self) -> Option<DomNode> {
        Some(DomNode(self.0.borrow().first_child.as_ref()?.clone()))
    }

    /// Returns a last child of this node, unless it has no child.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutably borrowed.
    pub fn last_child(&self) -> Option<DomNode> {
        Some(DomNode(self.0.borrow().last_child.as_ref()?.upgrade()?))
    }

    /// Returns the previous sibling of this node, unless it is a first child.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutably borrowed.
    pub fn previous_sibling(&self) -> Option<DomNode> {
        Some(DomNode(
            self.0.borrow().previous_sibling.as_ref()?.upgrade()?,
        ))
    }

    /// Returns the next sibling of this node, unless it is a last child.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutably borrowed.
    pub fn next_sibling(&self) -> Option<DomNode> {
        Some(DomNode(self.0.borrow().next_sibling.as_ref()?.clone()))
    }

    pub fn kind(&self) -> Ref<'_, DomNodeKind> {
        Ref::map(self.0.borrow(), |v| &v.kind)
    }

    pub fn kind_mut(&self) -> RefMut<'_, DomNodeKind> {
        RefMut::map(self.0.borrow_mut(), |v| &mut v.kind)
    }

    /// Returns an iterator of nodes to this node and its ancestors.
    ///
    /// Includes the current node.
    pub fn ancestors(&self) -> Ancestors {
        Ancestors(Some(self.clone()))
    }

    /// Returns an iterator of nodes to this node and the siblings before it.
    ///
    /// Includes the current node.
    pub fn preceding_siblings(&self) -> PrecedingSiblings {
        PrecedingSiblings(Some(self.clone()))
    }

    /// Returns an iterator of nodes to this node and the siblings after it.
    ///
    /// Includes the current node.
    pub fn following_siblings(&self) -> FollowingSiblings {
        FollowingSiblings(Some(self.clone()))
    }

    /// Returns an iterator of nodes to this node's children.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutably borrowed.
    pub fn children(&self) -> Children {
        Children {
            next: self.first_child(),
            next_back: self.last_child(),
        }
    }

    /// Returns `true` if this node has children nodes.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutably borrowed.
    pub fn has_children(&self) -> bool {
        self.first_child().is_some()
    }

    /// Returns an iterator of nodes to this node and its descendants, in tree order.
    ///
    /// Includes the current node.
    pub fn descendants(&self) -> Descendants {
        Descendants(self.traverse())
    }

    /// Returns an iterator of nodes to this node and its descendants, in tree order.
    pub fn traverse(&self) -> Traverse {
        Traverse {
            root: self.clone(),
            next: Some(NodeEdge::Start(self.clone())),
            next_back: Some(NodeEdge::End(self.clone())),
        }
    }

    /// Remove empty tags or invalid html in a way that makes sense
    pub fn sanitize_children(&mut self) {
        for mut c in self.children() {
            c.sanitize_children();
        }

        // can't remove while borrowing in c.kind() so getting remove flag instead
        let should_remove = match &*self.kind() {
            DomNodeKind::Text { text } if text.is_empty() => true,
            // remove paragraph if no children
            DomNodeKind::Element { tag, .. } if tag == "p" && self.first_child().is_none() => true,
            // remove paragraph if text children are only whitespace
            DomNodeKind::Element { tag, .. } if tag == "p" => self.children().all(|c| {
                if let DomNodeKind::Text { text } = &*c.kind() {
                    text.chars().all(|c| c == ' ')
                } else {
                    false
                }
            }),
            _ => false,
        };
        if should_remove {
            self.detach();
            return;
        }

        match &mut *self.kind_mut() {
            // only single whitespace as text
            DomNodeKind::Text { text } if text.chars().all(|c| c == ' ') => *text = " ".into(),
            _ => {}
        };
    }

    pub fn get_elements_by_tag_name(&self, tag: &str) -> Vec<DomNode> {
        self.descendants()
            .filter(|d| {
                if let DomNodeKind::Element { tag: t, .. } = &*d.kind() {
                    if t == tag {
                        return true;
                    }
                }
                false
            })
            .collect()
    }

    pub fn get_element_by_id(&self, id: &str) -> Option<DomNode> {
        self.descendants().find(|d| {
            if let DomNodeKind::Element { attributes, .. } = &*d.kind() {
                if let Some(element_id) = attributes.get("id") {
                    return element_id == id;
                }
            }
            false
        })
    }

    /// Returns the text content of this node and all its descendants.
    pub fn inner_text(&self) -> String {
        let mut text = String::new();
        for descendant in self.descendants() {
            if let DomNodeKind::Text { text: t } = &*descendant.kind() {
                text.push_str(t);
            }
        }
        text
    }

    /// Detaches a node from its parent and siblings. Children are not affected.
    ///
    /// # Panics
    ///
    /// Panics if the node or one of its adjoining nodes is currently borrowed.
    pub fn detach(&self) {
        self.0.borrow_mut().detach();
    }

    /// Appends a new child to this node, after existing children.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed.
    pub fn append_child(&self, new_child: impl Into<IterableNodes>) {
        let iter: IterableNodes = new_child.into();
        for c in iter.0 {
            assert!(*self != c, "a node cannot be appended to itself");

            let mut self_borrow = self.0.borrow_mut();
            let mut last_child_opt = None;
            {
                let mut new_child_borrow = c.0.borrow_mut();
                new_child_borrow.detach();
                new_child_borrow.parent = Some(Rc::downgrade(&self.0));
                if let Some(last_child_weak) = self_borrow.last_child.take() {
                    if let Some(last_child_strong) = last_child_weak.upgrade() {
                        new_child_borrow.previous_sibling = Some(last_child_weak);
                        last_child_opt = Some(last_child_strong);
                    }
                }
                self_borrow.last_child = Some(Rc::downgrade(&c.0));
            }

            if let Some(last_child_strong) = last_child_opt {
                let mut last_child_borrow = last_child_strong.borrow_mut();
                debug_assert!(last_child_borrow.next_sibling.is_none());
                last_child_borrow.next_sibling = Some(c.0);
            } else {
                // No last child
                debug_assert!(self_borrow.first_child.is_none());
                self_borrow.first_child = Some(c.0);
            }
        }
    }

    /// Prepends a new child to this node, before existing children.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed.
    pub fn prepend(&self, new_child: DomNode) {
        assert!(*self != new_child, "a node cannot be prepended to itself");

        let mut self_borrow = self.0.borrow_mut();
        {
            let mut new_child_borrow = new_child.0.borrow_mut();
            new_child_borrow.detach();
            new_child_borrow.parent = Some(Rc::downgrade(&self.0));
            match self_borrow.first_child.take() {
                Some(first_child_strong) => {
                    {
                        let mut first_child_borrow = first_child_strong.borrow_mut();
                        debug_assert!(first_child_borrow.previous_sibling.is_none());
                        first_child_borrow.previous_sibling = Some(Rc::downgrade(&new_child.0));
                    }
                    new_child_borrow.next_sibling = Some(first_child_strong);
                }
                None => {
                    debug_assert!(self_borrow.first_child.is_none());
                    self_borrow.last_child = Some(Rc::downgrade(&new_child.0));
                }
            }
        }
        self_borrow.first_child = Some(new_child.0);
    }

    /// Inserts a new sibling after this node.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new sibling, or one of their adjoining nodes is currently borrowed.
    pub fn insert_after(&self, new_sibling: DomNode) {
        assert!(
            *self != new_sibling,
            "a node cannot be inserted after itself"
        );

        let mut self_borrow = self.0.borrow_mut();
        {
            let mut new_sibling_borrow = new_sibling.0.borrow_mut();
            new_sibling_borrow.detach();
            new_sibling_borrow.parent = self_borrow.parent.clone();
            new_sibling_borrow.previous_sibling = Some(Rc::downgrade(&self.0));
            match self_borrow.next_sibling.take() {
                Some(next_sibling_strong) => {
                    {
                        let mut next_sibling_borrow = next_sibling_strong.borrow_mut();
                        debug_assert!({
                            let weak = next_sibling_borrow.previous_sibling.as_ref().unwrap();
                            Rc::ptr_eq(&weak.upgrade().unwrap(), &self.0)
                        });
                        next_sibling_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
                    }
                    new_sibling_borrow.next_sibling = Some(next_sibling_strong);
                }
                None => {
                    if let Some(parent_ref) = self_borrow.parent.as_ref() {
                        if let Some(parent_strong) = parent_ref.upgrade() {
                            let mut parent_borrow = parent_strong.borrow_mut();
                            parent_borrow.last_child = Some(Rc::downgrade(&new_sibling.0));
                        }
                    }
                }
            }
        }
        self_borrow.next_sibling = Some(new_sibling.0);
    }

    /// Inserts a new sibling before this node.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new sibling, or one of their adjoining nodes is currently borrowed.
    pub fn insert_before(&self, new_sibling: DomNode) {
        assert!(
            *self != new_sibling,
            "a node cannot be inserted before itself"
        );

        let mut self_borrow = self.0.borrow_mut();
        let mut previous_sibling_opt = None;
        {
            let mut new_sibling_borrow = new_sibling.0.borrow_mut();
            new_sibling_borrow.detach();
            new_sibling_borrow.parent = self_borrow.parent.clone();
            new_sibling_borrow.next_sibling = Some(self.0.clone());
            if let Some(previous_sibling_weak) = self_borrow.previous_sibling.take() {
                if let Some(previous_sibling_strong) = previous_sibling_weak.upgrade() {
                    new_sibling_borrow.previous_sibling = Some(previous_sibling_weak);
                    previous_sibling_opt = Some(previous_sibling_strong);
                }
            }
            self_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
        }

        if let Some(previous_sibling_strong) = previous_sibling_opt {
            let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
            debug_assert!({
                let rc = previous_sibling_borrow.next_sibling.as_ref().unwrap();
                Rc::ptr_eq(rc, &self.0)
            });
            previous_sibling_borrow.next_sibling = Some(new_sibling.0);
        } else {
            // No previous sibling.
            if let Some(parent_ref) = self_borrow.parent.as_ref() {
                if let Some(parent_strong) = parent_ref.upgrade() {
                    let mut parent_borrow = parent_strong.borrow_mut();
                    parent_borrow.first_child = Some(new_sibling.0);
                }
            }
        }
    }

    pub fn from_html(html: Html) -> Option<Self> {
        match html {
            Html::Comment { .. } => None,
            Html::Text { text } => Some(DomNode::create_text(text)),
            Html::Element {
                tag,
                attributes,
                children,
            } => {
                let node = DomNode::create_element_with_attributes(tag, attributes);
                for c in children {
                    if let Some(n) = DomNode::from_html(c) {
                        node.append_child(n);
                    }
                }
                Some(node)
            }
        }
    }
}

/// Escapes HTML special characters in text content
fn escape_html(text: &str) -> String {
    text.chars()
        .map(|c| match c {
            '&' => "&amp;".to_string(),
            '<' => "&lt;".to_string(),
            '>' => "&gt;".to_string(),
            '"' => "&quot;".to_string(),
            '\'' => "&#39;".to_string(),
            _ => c.to_string(),
        })
        .collect()
}
impl std::fmt::Display for DomNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &*self.kind() {
            DomNodeKind::Text { text } => write!(f, "{}", escape_html(text)),
            DomNodeKind::Element { tag, attributes } => {
                let attributes = attributes
                    .iter()
                    .map(|(k, v)| {
                        if !v.is_empty() {
                            format!(r#"{k}="{v}""#)
                        } else {
                            k.into()
                        }
                    })
                    .collect::<Vec<String>>()
                    .join(" ");

                let spacing = if !attributes.is_empty() {
                    String::from(" ")
                } else {
                    String::new()
                };

                let children: Vec<DomNode> = self.children().collect();
                if children.is_empty() && is_void_element(tag) {
                    return write!(f, "<{tag}{spacing}{}/>", attributes);
                }

                let mut content = String::new();

                for c in children {
                    content += &format!("{}", c);
                }

                write!(f, "<{tag}{spacing}{}>{}</{tag}>", attributes, content)
            }
        }
    }
}

/// Cloning a `WeakNode` only increments a reference count. It does not copy the data.
impl Clone for WeakDomNode {
    fn clone(&self) -> Self {
        WeakDomNode(Weak::clone(&self.0))
    }
}

impl fmt::Debug for WeakDomNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("(WeakNode)")
    }
}

impl WeakDomNode {
    /// Attempts to upgrade the WeakNode to a Node.
    pub fn upgrade(&self) -> Option<DomNode> {
        self.0.upgrade().map(DomNode)
    }
}

impl DomNodeData {
    /// Detaches a node from its parent and siblings. Children are not affected.
    fn detach(&mut self) {
        let parent_weak = self.parent.take();
        let previous_sibling_weak = self.previous_sibling.take();
        let next_sibling_strong = self.next_sibling.take();

        let previous_sibling_opt = previous_sibling_weak
            .as_ref()
            .and_then(|weak| weak.upgrade());

        if let Some(next_sibling_ref) = next_sibling_strong.as_ref() {
            let mut next_sibling_borrow = next_sibling_ref.borrow_mut();
            next_sibling_borrow.previous_sibling = previous_sibling_weak;
        } else if let Some(parent_ref) = parent_weak.as_ref() {
            if let Some(parent_strong) = parent_ref.upgrade() {
                let mut parent_borrow = parent_strong.borrow_mut();
                parent_borrow.last_child = previous_sibling_weak;
            }
        }

        if let Some(previous_sibling_strong) = previous_sibling_opt {
            let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
            previous_sibling_borrow.next_sibling = next_sibling_strong;
        } else if let Some(parent_ref) = parent_weak.as_ref() {
            if let Some(parent_strong) = parent_ref.upgrade() {
                let mut parent_borrow = parent_strong.borrow_mut();
                parent_borrow.first_child = next_sibling_strong;
            }
        }
    }
}

impl Drop for DomNodeData {
    fn drop(&mut self) {
        // Collect all descendant nodes and detach them to prevent the stack overflow.

        let mut stack = Vec::new();
        if let Some(first_child) = self.first_child.as_ref() {
            // Create `Node` from `NodeData`.
            let first_child = DomNode(first_child.clone());
            // Iterate `self` children, without creating yet another `Node`.
            for child1 in first_child.following_siblings() {
                for child2 in child1.descendants() {
                    stack.push(child2);
                }
            }
        }

        for node in stack {
            node.detach();
        }
    }
}

macro_rules! impl_node_iterator {
    ($name: ident, $next: expr) => {
        impl Iterator for $name {
            type Item = DomNode;

            /// # Panics
            ///
            /// Panics if the node about to be yielded is currently mutably borrowed.
            fn next(&mut self) -> Option<Self::Item> {
                match self.0.take() {
                    Some(node) => {
                        self.0 = $next(&node);
                        Some(node)
                    }
                    None => None,
                }
            }
        }
    };
}

/// An iterator of nodes to the ancestors a given node.
pub struct Ancestors(Option<DomNode>);
impl_node_iterator!(Ancestors, |node: &DomNode| node.parent());

/// An iterator of nodes to the siblings before a given node.
pub struct PrecedingSiblings(Option<DomNode>);
impl_node_iterator!(PrecedingSiblings, |node: &DomNode| node.previous_sibling());

/// An iterator of nodes to the siblings after a given node.
pub struct FollowingSiblings(Option<DomNode>);
impl_node_iterator!(FollowingSiblings, |node: &DomNode| node.next_sibling());

/// A double ended iterator of nodes to the children of a given node.
pub struct Children {
    next: Option<DomNode>,
    next_back: Option<DomNode>,
}

impl Children {
    // true if self.next_back's next sibling is self.next
    fn finished(&self) -> bool {
        match self.next_back {
            Some(ref next_back) => next_back.next_sibling() == self.next,
            _ => true,
        }
    }
}

impl Iterator for Children {
    type Item = DomNode;

    /// # Panics
    ///
    /// Panics if the node about to be yielded is currently mutably borrowed.
    fn next(&mut self) -> Option<Self::Item> {
        if self.finished() {
            return None;
        }

        match self.next.take() {
            Some(node) => {
                self.next = node.next_sibling();
                Some(node)
            }
            None => None,
        }
    }
}

impl DoubleEndedIterator for Children {
    /// # Panics
    ///
    /// Panics if the node about to be yielded is currently mutably borrowed.
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.finished() {
            return None;
        }

        match self.next_back.take() {
            Some(node) => {
                self.next_back = node.previous_sibling();
                Some(node)
            }
            None => None,
        }
    }
}

/// An iterator of nodes to a given node and its descendants, in tree order.
pub struct Descendants(Traverse);

impl Iterator for Descendants {
    type Item = DomNode;

    /// # Panics
    ///
    /// Panics if the node about to be yielded is currently mutably borrowed.
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.0.next() {
                Some(NodeEdge::Start(node)) => return Some(node),
                Some(NodeEdge::End(_)) => {}
                None => return None,
            }
        }
    }
}

/// A node type during traverse.
#[derive(Clone, Debug)]
pub enum NodeEdge {
    /// Indicates that start of a node that has children.
    /// Yielded by `Traverse::next` before the node's descendants.
    /// In HTML or XML, this corresponds to an opening tag like `<div>`
    Start(DomNode),

    /// Indicates that end of a node that has children.
    /// Yielded by `Traverse::next` after the node's descendants.
    /// In HTML or XML, this corresponds to a closing tag like `</div>`
    End(DomNode),
}

// Implement PartialEq manually, because we do not need to require T: PartialEq
impl PartialEq for NodeEdge {
    fn eq(&self, other: &NodeEdge) -> bool {
        match (self, other) {
            (NodeEdge::Start(n1), NodeEdge::Start(n2)) => *n1 == *n2,
            (NodeEdge::End(n1), NodeEdge::End(n2)) => *n1 == *n2,
            _ => false,
        }
    }
}

impl NodeEdge {
    fn next_item(&self, root: &DomNode) -> Option<NodeEdge> {
        match *self {
            NodeEdge::Start(ref node) => match node.first_child() {
                Some(first_child) => Some(NodeEdge::Start(first_child)),
                None => Some(NodeEdge::End(node.clone())),
            },
            NodeEdge::End(ref node) => {
                if *node == *root {
                    None
                } else {
                    match node.next_sibling() {
                        Some(next_sibling) => Some(NodeEdge::Start(next_sibling)),
                        // `node.parent()` here can only be `None`
                        // if the tree has been modified during iteration,
                        // but silently stopping iteration
                        // seems a more sensible behavior than panicking.
                        None => node.parent().map(NodeEdge::End),
                    }
                }
            }
        }
    }

    fn previous_item(&self, root: &DomNode) -> Option<NodeEdge> {
        match *self {
            NodeEdge::End(ref node) => match node.last_child() {
                Some(last_child) => Some(NodeEdge::End(last_child)),
                None => Some(NodeEdge::Start(node.clone())),
            },
            NodeEdge::Start(ref node) => {
                if *node == *root {
                    None
                } else {
                    match node.previous_sibling() {
                        Some(previous_sibling) => Some(NodeEdge::End(previous_sibling)),
                        // `node.parent()` here can only be `None`
                        // if the tree has been modified during iteration,
                        // but silently stopping iteration
                        // seems a more sensible behavior than panicking.
                        None => node.parent().map(NodeEdge::Start),
                    }
                }
            }
        }
    }
}

/// A double ended iterator of nodes to a given node and its descendants,
/// in tree order.
pub struct Traverse {
    root: DomNode,
    next: Option<NodeEdge>,
    next_back: Option<NodeEdge>,
}

impl Traverse {
    // true if self.next_back's next item is self.next
    fn finished(&self) -> bool {
        match self.next_back {
            Some(ref next_back) => next_back.next_item(&self.root) == self.next,
            _ => true,
        }
    }
}

impl Iterator for Traverse {
    type Item = NodeEdge;

    /// # Panics
    ///
    /// Panics if the node about to be yielded is currently mutably borrowed.
    fn next(&mut self) -> Option<Self::Item> {
        if self.finished() {
            return None;
        }

        match self.next.take() {
            Some(item) => {
                self.next = item.next_item(&self.root);
                Some(item)
            }
            None => None,
        }
    }
}

impl DoubleEndedIterator for Traverse {
    /// # Panics
    ///
    /// Panics if the node about to be yielded is currently mutably borrowed.
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.finished() {
            return None;
        }

        match self.next_back.take() {
            Some(item) => {
                self.next_back = item.previous_item(&self.root);
                Some(item)
            }
            None => None,
        }
    }
}