css_inline/html/
node.rs

1use super::attributes::Attributes;
2use html5ever::{tendril::StrTendril, QualName};
3use std::num::NonZeroUsize;
4
5/// Single node in the DOM.
6#[derive(Debug)]
7pub(crate) struct Node {
8    pub(crate) parent: Option<NodeId>,
9    pub(crate) next_sibling: Option<NodeId>,
10    pub(crate) previous_sibling: Option<NodeId>,
11    pub(crate) first_child: Option<NodeId>,
12    pub(crate) last_child: Option<NodeId>,
13    /// Data specific to the type of node.
14    pub(crate) data: NodeData,
15}
16
17impl Node {
18    #[inline]
19    pub(crate) fn new(data: NodeData) -> Node {
20        Node {
21            parent: None,
22            previous_sibling: None,
23            next_sibling: None,
24            first_child: None,
25            last_child: None,
26            data,
27        }
28    }
29    #[inline]
30    pub(crate) fn as_element(&self) -> Option<&ElementData> {
31        match &self.data {
32            NodeData::Element { element: data, .. } => Some(data),
33            _ => None,
34        }
35    }
36    #[inline]
37    pub(crate) fn as_element_mut(&mut self) -> Option<&mut ElementData> {
38        match &mut self.data {
39            NodeData::Element { element: data, .. } => Some(data),
40            _ => None,
41        }
42    }
43    #[inline]
44    pub(crate) fn as_text(&self) -> Option<&str> {
45        match &self.data {
46            NodeData::Text { text } => Some(&**text),
47            _ => None,
48        }
49    }
50}
51
52/// `NodeId` is a unique identifier for each `Node` in the document.
53#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
54pub(crate) struct NodeId(NonZeroUsize);
55
56impl NodeId {
57    #[inline]
58    pub(super) fn new(value: usize) -> NodeId {
59        NodeId(NonZeroUsize::new(value).expect("Value is zero"))
60    }
61    #[inline]
62    pub(super) fn document_id() -> NodeId {
63        NodeId::new(1)
64    }
65    #[inline]
66    pub(super) fn get(self) -> usize {
67        self.0.get()
68    }
69}
70
71/// Data associated with a `Node`.
72#[derive(Debug)]
73pub(crate) enum NodeData {
74    Document,
75    Doctype {
76        name: StrTendril,
77    },
78    Text {
79        text: StrTendril,
80    },
81    Comment {
82        text: StrTendril,
83    },
84    Element {
85        element: ElementData,
86        inlining_ignored: bool,
87    },
88    ProcessingInstruction {
89        target: StrTendril,
90        data: StrTendril,
91    },
92}
93
94#[derive(Debug)]
95pub(crate) struct ElementData {
96    /// The name (tag) of the element.
97    pub(crate) name: QualName,
98    /// The attributes associated with the element.
99    pub(crate) attributes: Attributes,
100}
101
102impl ElementData {
103    #[inline]
104    pub(crate) fn new(name: QualName, attributes: Vec<html5ever::Attribute>) -> ElementData {
105        ElementData {
106            name,
107            attributes: Attributes::new(attributes),
108        }
109    }
110}