Skip to main content

muffy_document/document/
node.rs

1use super::element::Element;
2use alloc::sync::Arc;
3use html5ever::ns;
4use markup5ever_rcdom::NodeData;
5
6/// A node.
7#[derive(Debug, Eq, PartialEq)]
8pub enum Node {
9    /// An element.
10    Element(Element),
11    /// A text.
12    Text(String),
13}
14
15impl Node {
16    pub(crate) fn from_markup5ever(node: &markup5ever_rcdom::Node) -> Option<Self> {
17        match &node.data {
18            NodeData::Element { name, attrs, .. } => Some(Self::Element(Element::new(
19                name.local.to_string(),
20                attrs
21                    .borrow()
22                    .iter()
23                    // Namespace declarations on foreign elements are not semantic attributes.
24                    // TODO Consider keeping namespace prefixes.
25                    .filter(|attribute| attribute.name.ns != ns!(xmlns))
26                    .map(|attribute| {
27                        (
28                            attribute.name.local.to_string(),
29                            attribute.value.to_string(),
30                        )
31                    })
32                    .collect(),
33                node.children
34                    .borrow()
35                    .iter()
36                    .flat_map(|node| Self::from_markup5ever(node))
37                    .map(Arc::new)
38                    .collect(),
39            ))),
40            NodeData::Text { contents } => Some(Self::Text(contents.borrow().to_string())),
41            NodeData::Comment { .. }
42            | NodeData::Document
43            | NodeData::Doctype { .. }
44            | NodeData::ProcessingInstruction { .. } => None,
45        }
46    }
47}