use crate::{
hydration::HydrationKey, ComponentRepr, HydrationCtx, IntoView, View,
};
use leptos_reactive::Scope;
pub trait IntoFragment {
fn into_fragment(self, cx: Scope) -> Fragment;
}
impl<I, V> IntoFragment for I
where
I: IntoIterator<Item = V>,
V: IntoView,
{
fn into_fragment(self, cx: Scope) -> Fragment {
self.into_iter().map(|v| v.into_view(cx)).collect()
}
}
#[derive(Debug, Clone)]
pub struct Fragment {
id: HydrationKey,
pub nodes: Vec<View>,
#[cfg(debug_assertions)]
pub(crate) view_marker: Option<String>,
}
impl FromIterator<View> for Fragment {
fn from_iter<T: IntoIterator<Item = View>>(iter: T) -> Self {
Fragment::new(iter.into_iter().collect())
}
}
impl From<View> for Fragment {
fn from(view: View) -> Self {
Fragment::new(vec![view])
}
}
impl Fragment {
pub fn new(nodes: Vec<View>) -> Self {
Self::new_with_id(HydrationCtx::id(), nodes)
}
pub fn lazy(nodes: impl FnOnce() -> Vec<View>) -> Self {
Self::new_with_id(HydrationCtx::id(), nodes())
}
pub fn new_with_id(id: HydrationKey, nodes: Vec<View>) -> Self {
Self {
id,
nodes,
#[cfg(debug_assertions)]
view_marker: None,
}
}
pub fn as_children(&self) -> &[View] {
&self.nodes
}
pub fn id(&self) -> &HydrationKey {
&self.id
}
#[cfg(debug_assertions)]
pub fn with_view_marker(mut self, marker: impl Into<String>) -> Self {
self.view_marker = Some(marker.into());
self
}
}
impl IntoView for Fragment {
#[cfg_attr(debug_assertions, instrument(level = "trace", name = "</>", skip_all, fields(children = self.nodes.len())))]
fn into_view(self, cx: leptos_reactive::Scope) -> View {
let mut frag = ComponentRepr::new_with_id("", self.id.clone());
#[cfg(debug_assertions)]
{
frag.view_marker = self.view_marker;
}
frag.children = self.nodes;
frag.into_view(cx)
}
}