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
use std::rc::Rc;

use crate::{AnyNode, ComponentStatic};

/// One or many [`AnyNode`]s whose order will
/// never change.
/// When `Children` is used as
#[derive(Debug, Clone)]
pub enum Children {
    Single(Box<AnyNode>),
    StaticMultiple(Rc<Vec<AnyNode>>),
}

impl Children {
    #[inline]
    pub fn from_static_nodes<T: IntoIterator<Item = AnyNode>>(nodes: T) -> Self {
        Self::StaticMultiple(Rc::new(Vec::from_iter(nodes)))
    }

    pub fn from_single(node: AnyNode) -> Children {
        Self::Single(Box::new(node))
    }

    /// See [`AnyNode::unsafe_into_js_node_value`] for the safety notes.
    #[inline]
    pub(crate) fn unsafe_into_js_array(self) -> js_sys::Array {
        match self {
            Children::Single(node) => js_sys::Array::of1(&node.unsafe_into_js_node_value()),
            Children::StaticMultiple(arr) => match Rc::try_unwrap(arr) {
                Ok(arr) => js_sys::Array::from_iter(
                    arr.into_iter().map(AnyNode::unsafe_into_js_node_value),
                ),
                Err(arr) => js_sys::Array::from_iter(
                    arr.iter()
                        .map(|v| AnyNode::unsafe_into_js_node_value(v.clone())),
                ),
            },
        }
    }
}

impl super::Node for Children {
    #[inline]
    fn to_node(&self) -> AnyNode {
        self.clone().into_node()
    }

    #[inline]
    fn to_children(&self) -> Option<Children> {
        Some(self.clone())
    }

    /// Returns the single node or wrap multiple nodes in a Fragment
    #[inline]
    fn into_node(self) -> AnyNode {
        match self {
            Children::Single(node) => *node,
            children => AnyNode::Element(
                crate::Fragment::create_element(
                    crate::OptionalChildrenProps {
                        children: Some(children),
                    },
                    None,
                )
                .into(),
            ),
        }
    }

    #[inline]
    fn into_children(self) -> Option<Children> {
        Some(self)
    }
}