Skip to content

Omit conditional elements without an else branch when present in children #3274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
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
34 changes: 33 additions & 1 deletion packages/yew-macro/src/html_tree/html_if.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use boolinator::Boolinator;
use proc_macro2::TokenStream;
use quote::{quote_spanned, ToTokens};
use quote::{quote, quote_spanned, ToTokens};
use syn::buffer::Cursor;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
Expand Down Expand Up @@ -139,3 +139,35 @@ impl ToTokens for HtmlRootBracedOrIf {
}
}
}

pub struct HtmlIfIterItem<'a>(pub &'a HtmlIf);

impl<'a> ToNodeIterator for HtmlIfIterItem<'a> {
fn to_node_iterator_stream(&self) -> Option<TokenStream> {
let HtmlIf {
if_token,
cond,
then_branch,
else_branch,
..
} = &self.0;

if else_branch.is_none() {
// This slightly awkward syntax is necessary to defeat stable's
// [`clippy::manual_map`] lint.
let new_tokens = quote_spanned! {if_token.span()=>
if #cond {
let _x = ::std::convert::Into::into(#then_branch);
::std::option::Option::Some(_x)
} else {
::std::option::Option::None
}
};

Some(new_tokens)
} else {
let new_tokens = self.0.to_node_iterator_stream().unwrap();
Some(quote! { ::std::option::Option::Some(#new_tokens) })
}
}
}
50 changes: 41 additions & 9 deletions packages/yew-macro/src/html_tree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,23 +237,55 @@ impl HtmlChildrenTree {

pub fn to_build_vec_token_stream(&self) -> TokenStream {
let Self(children) = self;

if self.only_single_node_children() {
// optimize for the common case where all children are single nodes (only using literal
// html).
let children_into = children
.iter()
.map(|child| quote_spanned! {child.span()=> ::std::convert::Into::into(#child) });
return quote! {
::std::vec![#(#children_into),*]
};
let children_into = children.iter().map(|child| {
if let HtmlTree::If(if_clause) = child {
html_if::HtmlIfIterItem(if_clause.as_ref())
.to_node_iterator_stream()
.unwrap()
} else {
quote_spanned! {child.span()=> ::std::option::Option::Some(::std::convert::Into::into(#child)) }
}
});

return quote! {{
use ::std::iter::IntoIterator;
use ::std::iter::Iterator;
[#(#children_into),*].into_iter().filter(|x: &::std::option::Option<_>| x.is_some()).map(|x| x.unwrap()).collect::<::std::vec::Vec<_>>()
}};
}

let vec_ident = Ident::new("__yew_v", Span::mixed_site());
let add_children_streams = children.iter().map(|child| {
if let Some(node_iterator_stream) = child.to_node_iterator_stream() {
quote! {
::std::iter::Extend::extend(&mut #vec_ident, #node_iterator_stream);
if let HtmlTree::If(if_clause) = child {
let tokens = html_if::HtmlIfIterItem(if_clause.as_ref())
.to_node_iterator_stream()
.unwrap();

quote! {
if let ::std::option::Option::Some(iter) = #tokens {
::std::iter::Extend::extend(&mut #vec_ident, iter)
} else {
#vec_ident
}
}
} else {
quote! {
::std::iter::Extend::extend(&mut #vec_ident, #node_iterator_stream);
}
}
} else if let HtmlTree::If(if_clause) = child {
let tokens = html_if::HtmlIfIterItem(if_clause.as_ref())
.to_node_iterator_stream()
.unwrap();

quote_spanned! {child.span()=>
if let ::std::option::Option::Some(iter) = ::std::convert::Into::into(#tokens) {
#vec_ident.push(iter)
}
}
} else {
quote_spanned! {child.span()=>
Expand Down
3 changes: 1 addition & 2 deletions packages/yew/src/dom_bundle/btag/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1175,7 +1175,6 @@ mod tests_without_browser {
},
html! {
<div>
<></>
</div>
},
);
Expand Down Expand Up @@ -1265,7 +1264,7 @@ mod tests_without_browser {
}
</div>
},
html! { <div><></></div> },
html! { <div></div> },
);
}
}
89 changes: 89 additions & 0 deletions packages/yew/tests/children.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#![cfg(not(target_arch = "wasm32"))]

use yew::prelude::*;

#[tokio::test]
async fn conditional_children_are_omitted() {
#[derive(Properties, PartialEq)]
pub struct Props {
#[prop_or_default]
pub children: Children,
}

#[function_component]
pub fn Problem(p: &Props) -> Html {
html! {
<div class="container">
{
for p.children.iter().enumerate().map(|(i, x)| {
html! {
<div>
<span>{x}</span>
<span>{i}</span>
</div>
}
})
}
</div>
}
}

#[function_component]
fn App() -> Html {
let b = false;
html! {
<Problem>
<span>{ "A" }</span>
<span>{ "B" }</span>
if b {
<span>{ "C" }</span>
}
<span>{ "D" }</span>
</Problem>
}
}

let mut s = String::new();
yew::ServerRenderer::<App>::new()
.render_to_string(&mut s)
.await;

assert_eq!(
s,
"<!--<[children::conditional_children_are_omitted::{{closure}}::App]>--><!\
--<[children::conditional_children_are_omitted::{{closure}}::Problem]>--><div \
class=\"container\"><div><span><span>A</span></span><span>0</span></\
div><div><span><span>B</span></span><span>1</span></div><div><span><span>D</span></\
span><span>2</span></div></div><!--</\
[children::conditional_children_are_omitted::{{closure}}::Problem]>--><!--</\
[children::conditional_children_are_omitted::{{closure}}::App]>-->"
);
}

#[tokio::test]
async fn conditional_children_are_omitted_in_non_only_single_node_children_case() {
#[function_component]
fn App() -> Html {
let b = true;
let a = Some(());
let chtml = html! {
<div></div>
};
html! {
<>
{ chtml }
if a.is_some() || b { <></> }
</>
}
}

let mut s = String::new();
yew::ServerRenderer::<App>::new()
.render_to_string(&mut s)
.await;

assert_eq!(
s,
"<!--<[children::conditional_children_are_omitted_in_non_only_single_node_children_case::{{closure}}::App]>--><div></div><!--</[children::conditional_children_are_omitted_in_non_only_single_node_children_case::{{closure}}::App]>-->"
);
}