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
//! Result of the [view!](crate::view!) macro.

use std::any::Any;
use std::borrow::Cow;
use std::fmt;
use std::rc::Rc;

use crate::generic_node::GenericNode;
use crate::reactive::{create_memo, ReadSignal};

/// Internal type for [`View`].
#[derive(Clone)]
pub(crate) enum ViewType<G: GenericNode> {
    /// A DOM node.
    Node(G),
    /// A dynamic [`View`].
    Dyn(ReadSignal<View<G>>),
    /// A fragment of [`View`]s.
    #[allow(clippy::redundant_allocation)] // Cannot create a `Rc<[T]>` directly.
    Fragment(Rc<Box<[View<G>]>>),
}

/// Result of the [view!](crate::view!) macro.
#[derive(Clone)]
pub struct View<G: GenericNode> {
    pub(crate) inner: ViewType<G>,
}

impl<G: GenericNode> View<G> {
    /// Create a new [`View`] from a [`GenericNode`].
    pub fn new_node(node: G) -> Self {
        Self {
            inner: ViewType::Node(node),
        }
    }

    /// Create a new [`View`] from a [`FnMut`].
    pub fn new_dyn(f: impl FnMut() -> View<G> + 'static) -> Self {
        let memo = create_memo(f);
        Self {
            inner: ViewType::Dyn(memo),
        }
    }

    /// Create a new [`View`] from a `Vec` of [`GenericNode`]s.
    pub fn new_fragment(fragment: Vec<View<G>>) -> Self {
        Self {
            inner: ViewType::Fragment(Rc::from(fragment.into_boxed_slice())),
        }
    }

    /// Create a new [`View`] with a blank comment node
    pub fn empty() -> Self {
        Self::new_node(G::marker())
    }

    pub fn as_node(&self) -> Option<&G> {
        if let ViewType::Node(v) = &self.inner {
            Some(v)
        } else {
            None
        }
    }

    pub fn as_fragment(&self) -> Option<&[View<G>]> {
        if let ViewType::Fragment(v) = &self.inner {
            Some(v)
        } else {
            None
        }
    }

    pub fn as_dyn(&self) -> Option<&ReadSignal<View<G>>> {
        if let ViewType::Dyn(v) = &self.inner {
            Some(v)
        } else {
            None
        }
    }

    pub fn is_node(&self) -> bool {
        matches!(
            self,
            View {
                inner: ViewType::Node(_)
            }
        )
    }

    pub fn is_fragment(&self) -> bool {
        matches!(
            self,
            View {
                inner: ViewType::Fragment(_)
            }
        )
    }

    pub fn is_dyn(&self) -> bool {
        matches!(
            self,
            View {
                inner: ViewType::Dyn(_)
            }
        )
    }

    /// Returns a `Vec` of nodes.
    pub fn flatten(self) -> Vec<G> {
        match self.inner {
            ViewType::Node(node) => vec![node],
            ViewType::Dyn(lazy) => lazy.get().as_ref().clone().flatten(),
            ViewType::Fragment(fragment) => fragment
                .iter()
                .map(|x| x.clone().flatten())
                .flatten()
                .collect(),
        }
    }
}

impl<G: GenericNode> Default for View<G> {
    fn default() -> Self {
        Self::empty()
    }
}

impl<G: GenericNode> fmt::Debug for View<G> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.inner {
            ViewType::Node(node) => node.fmt(f),
            ViewType::Dyn(lazy) => lazy.get().fmt(f),
            ViewType::Fragment(fragment) => fragment.fmt(f),
        }
    }
}

/// Trait for describing how something should be rendered into DOM nodes.
pub trait IntoView<G: GenericNode> {
    /// Called during the initial render when creating the DOM nodes. Should return a
    /// `Vec` of [`GenericNode`]s.
    fn create(&self) -> View<G>;
}

impl<G: GenericNode> IntoView<G> for View<G> {
    fn create(&self) -> View<G> {
        self.clone()
    }
}

impl<G: GenericNode> IntoView<G> for &View<G> {
    fn create(&self) -> View<G> {
        (*self).clone()
    }
}

impl<T: fmt::Display + 'static, G: GenericNode> IntoView<G> for T {
    fn create(&self) -> View<G> {
        // Workaround for specialization.
        // Inspecting the type is optimized away at compile time.

        macro_rules! specialize_as_ref_to_str {
            ($t: ty) => {{
                if let Some(s) = <dyn Any>::downcast_ref::<$t>(self) {
                    return View::new_node(G::text_node(s.as_ref()));
                }
            }};
            ($t: ty, $($rest: ty),*) => {{
                specialize_as_ref_to_str!($t);
                specialize_as_ref_to_str!($($rest),*);
            }};
        }

        macro_rules! specialize_num_with_lexical {
            ($t: ty) => {{
                if let Some(&n) = <dyn Any>::downcast_ref::<$t>(self) {
                    return View::new_node(G::text_node(&lexical::to_string(n)));
                }
            }};
            ($t: ty, $($rest: ty),*) => {{
                specialize_num_with_lexical!($t);
                specialize_num_with_lexical!($($rest),*);
            }};
        }

        // Strings and string slices.
        specialize_as_ref_to_str!(&str, String, Rc<str>, Rc<String>, Cow<'_, str>);

        // Numbers use lexical.
        specialize_num_with_lexical!(
            i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
        );

        // Generic slow-path.
        let t = self.to_string();
        View::new_node(G::text_node(&t))
    }
}