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
//! The core crate for [`html-node`](https://docs.rs/html-node).

#![warn(clippy::cargo)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

/// HTTP Server integrations.
mod http;

/// [`Node`] variant definitions.
mod node;

/// Pretty printing utilities.
#[cfg(feature = "pretty")]
pub mod pretty;

/// Typed HTML Nodes.
#[cfg(feature = "typed")]
pub mod typed;

use std::fmt::{self, Display, Formatter};

pub use self::node::*;
#[cfg(feature = "typed")]
use self::typed::TypedElement;

/// An HTML node.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Node {
    /// A comment.
    ///
    /// ```html
    /// <!-- I'm a comment! -->
    /// ```
    Comment(Comment),

    /// A doctype.
    ///
    /// ```html
    /// <!DOCTYPE html>
    /// ```
    Doctype(Doctype),

    /// A fragment.
    ///
    /// ```html
    /// <>
    ///     I'm in a fragment!
    /// </>
    /// ```
    Fragment(Fragment),

    /// An element.
    ///
    /// ```html
    /// <div class="container">
    ///     I'm in an element!
    /// </div>
    /// ```
    Element(Element),

    /// A text node.
    ///
    /// ```html
    /// <div>
    ///     I'm a text node!
    /// </div>
    /// ```
    Text(Text),

    /// An unsafe text node.
    ///
    /// # Warning
    ///
    /// [`Node::UnsafeText`] is not escaped when rendered, and as such, can
    /// allow for XSS attacks. Use with caution!
    UnsafeText(UnsafeText),
}

impl Node {
    /// A [`Node::Fragment`] with no children.
    pub const EMPTY: Self = Self::Fragment(Fragment::EMPTY);

    /// Create a new [`Node`] from a [`TypedElement`].
    #[cfg(feature = "typed")]
    pub fn from_typed<E: TypedElement>(element: E, children: Option<Vec<Self>>) -> Self {
        element.into_node(children)
    }

    /// Wrap the node in a pretty-printing wrapper.
    #[cfg(feature = "pretty")]
    #[must_use]
    pub fn pretty(self) -> pretty::Pretty {
        self.into()
    }

    /// Borrow the children of the node, if it is an element (with children) or
    /// a fragment.
    #[must_use]
    pub fn as_children(&self) -> Option<&[Self]> {
        match self {
            Self::Fragment(fragment) => Some(&fragment.children),
            Self::Element(element) => element.children.as_deref(),
            _ => None,
        }
    }

    /// Iterate over the children of the node.
    pub fn children_iter(&self) -> impl Iterator<Item = &Self> {
        self.as_children().unwrap_or_default().iter()
    }

    /// The children of the node, if it is an element (with children) or
    /// a fragment.
    #[must_use]
    pub fn children(self) -> Option<Vec<Self>> {
        match self {
            Self::Fragment(fragment) => Some(fragment.children),
            Self::Element(element) => element.children,
            _ => None,
        }
    }

    /// Iterate over the children of the node, consuming it.
    pub fn into_children(self) -> impl Iterator<Item = Self> {
        self.children().unwrap_or_default().into_iter()
    }

    /// Try to get this node as a [`Comment`], if it is one.
    #[must_use]
    pub const fn as_comment(&self) -> Option<&Comment> {
        if let Self::Comment(comment) = self {
            Some(comment)
        } else {
            None
        }
    }

    /// Try to get this node as a [`Doctype`], if it is one.
    #[must_use]
    pub const fn as_doctype(&self) -> Option<&Doctype> {
        if let Self::Doctype(doctype) = self {
            Some(doctype)
        } else {
            None
        }
    }

    /// Try to get this node as a [`Fragment`], if it is one.
    #[must_use]
    pub const fn as_fragment(&self) -> Option<&Fragment> {
        if let Self::Fragment(fragment) = self {
            Some(fragment)
        } else {
            None
        }
    }

    /// Try to get this node as an [`Element`], if it is one.
    #[must_use]
    pub const fn as_element(&self) -> Option<&Element> {
        if let Self::Element(element) = self {
            Some(element)
        } else {
            None
        }
    }

    /// Try to get this node as a [`Text`], if it is one.
    #[must_use]
    pub const fn as_text(&self) -> Option<&Text> {
        if let Self::Text(text) = self {
            Some(text)
        } else {
            None
        }
    }

    /// Try to get this node as an [`UnsafeText`], if it is one.
    #[must_use]
    pub const fn as_unsafe_text(&self) -> Option<&UnsafeText> {
        if let Self::UnsafeText(text) = self {
            Some(text)
        } else {
            None
        }
    }
}

impl Default for Node {
    fn default() -> Self {
        Self::EMPTY
    }
}

impl Display for Node {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self {
            Self::Comment(comment) => comment.fmt(f),
            Self::Doctype(doctype) => doctype.fmt(f),
            Self::Fragment(fragment) => fragment.fmt(f),
            Self::Element(element) => element.fmt(f),
            Self::Text(text) => text.fmt(f),
            Self::UnsafeText(unsafe_text) => unsafe_text.fmt(f),
        }
    }
}

impl<I, N> From<I> for Node
where
    I: IntoIterator<Item = N>,
    N: Into<Self>,
{
    fn from(iter: I) -> Self {
        Self::Fragment(iter.into())
    }
}

impl From<Comment> for Node {
    fn from(comment: Comment) -> Self {
        Self::Comment(comment)
    }
}

impl From<Doctype> for Node {
    fn from(doctype: Doctype) -> Self {
        Self::Doctype(doctype)
    }
}

impl From<Fragment> for Node {
    fn from(fragment: Fragment) -> Self {
        Self::Fragment(fragment)
    }
}

impl From<Element> for Node {
    fn from(element: Element) -> Self {
        Self::Element(element)
    }
}

impl From<Text> for Node {
    fn from(text: Text) -> Self {
        Self::Text(text)
    }
}

impl From<UnsafeText> for Node {
    fn from(text: UnsafeText) -> Self {
        Self::UnsafeText(text)
    }
}