Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions packages/yew/src/html/component/children.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use std::fmt;

use crate::html::Html;
use crate::virtual_dom::{VChild, VNode};
use crate::virtual_dom::VChild;
use crate::Properties;

/// A type used for accepting children elements in Component::Properties.
Expand Down Expand Up @@ -163,7 +163,7 @@ impl<T: PartialEq> PartialEq for ChildrenRenderer<T> {

impl<T> ChildrenRenderer<T>
where
T: Clone + Into<VNode>,
T: Clone,
{
/// Create children
pub fn new(children: Vec<T>) -> Self {
Expand All @@ -186,6 +186,28 @@ where
// This way `self.iter().next()` only has to clone a single node.
self.children.iter().cloned()
}

/// Convert the children elements to another object (if there are any).
///
/// ```
/// # let children = Children::new(Vec::new());
/// # use yew::{classes, html, Children};
/// children.map(|children| {
/// html! {
/// <div class={classes!("container")}>
/// {children}
/// </div>
/// }
/// })
/// # ;
/// ```
pub fn map<OUT: Default>(&self, closure: impl FnOnce(&Self) -> OUT) -> OUT {
if self.is_empty() {
Default::default()
} else {
closure(self)
}
}
}

impl<T> Default for ChildrenRenderer<T> {
Expand Down Expand Up @@ -218,3 +240,18 @@ pub struct ChildrenProps {
#[prop_or_default]
pub children: Children,
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn children_map() {
let children = Children::new(vec![]);
let res = children.map(|children| Some(children.clone()));
assert!(res.is_none());
let children = Children::new(vec![Default::default()]);
let res = children.map(|children| Some(children.clone()));
assert!(res.is_some());
}
}
9 changes: 9 additions & 0 deletions packages/yew/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ impl<IN: Into<OUT>, OUT> From<ChildrenRenderer<IN>> for NodeSeq<IN, OUT> {
}
}

impl<IN: Into<OUT> + Clone, OUT> From<&ChildrenRenderer<IN>> for NodeSeq<IN, OUT> {
fn from(val: &ChildrenRenderer<IN>) -> Self {
Self(
val.iter().map(|x| x.into()).collect(),
PhantomData::default(),
)
}
}

impl<IN, OUT> IntoIterator for NodeSeq<IN, OUT> {
type IntoIter = std::vec::IntoIter<Self::Item>;
type Item = OUT;
Expand Down