html_node_core/node/
fragment.rs

1use std::fmt::{self, Display, Formatter};
2
3use super::write_children;
4use crate::Node;
5
6/// A fragment.
7///
8/// ```html
9/// <>
10///     I'm in a fragment!
11/// </>
12/// ```
13#[derive(Debug, Clone, PartialEq, Eq)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub struct Fragment {
16    /// The children of the fragment.
17    ///
18    /// ```html
19    /// <>
20    ///     <!-- I'm a child! -->
21    ///     <child>I'm another child!</child>
22    /// </>
23    pub children: Vec<Node>,
24}
25
26impl Fragment {
27    /// A fragment with no children.
28    pub const EMPTY: Self = Self {
29        children: Vec::new(),
30    };
31}
32
33impl Default for Fragment {
34    fn default() -> Self {
35        Self::EMPTY
36    }
37}
38
39impl Display for Fragment {
40    /// Format the fragment's childrent as HTML elements.
41    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
42        write_children(f, &self.children, true)
43    }
44}
45
46impl<N> FromIterator<N> for Fragment
47where
48    N: Into<Node>,
49{
50    /// Create a new fragment from an iterator of anything that
51    /// can be converted into a [`crate::Node`].
52    fn from_iter<I>(iter: I) -> Self
53    where
54        I: IntoIterator<Item = N>,
55    {
56        Self {
57            children: iter.into_iter().map(Into::into).collect(),
58        }
59    }
60}
61
62impl<I, N> From<I> for Fragment
63where
64    I: IntoIterator<Item = N>,
65    N: Into<Node>,
66{
67    /// Create a new fragment from any iterator of anything that
68    /// can be converted into a [`crate::Node`].
69    fn from(iter: I) -> Self {
70        Self::from_iter(iter)
71    }
72}