From e8fc62d34d6cfcba63839a87b2fb0588c3cecd79 Mon Sep 17 00:00:00 2001 From: fwcd Date: Mon, 9 Sep 2024 18:02:07 +0200 Subject: [PATCH] Add more fluent if/else API --- examples/fizz_buzz.rs | 4 ++-- nuit-core/src/compose/view/aggregation/if.rs | 13 ++++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/examples/fizz_buzz.rs b/examples/fizz_buzz.rs index f486cb9..4b13d31 100644 --- a/examples/fizz_buzz.rs +++ b/examples/fizz_buzz.rs @@ -24,12 +24,12 @@ impl View for FizzBuzzView { Button::with_text("Increment", clone!(count => move || { count.set(count.get() + 1); })), - If::new_or_else(fizz || buzz, || { + If::new(fizz || buzz, || { HStack::from(( If::new(fizz, || Text::new("Fizz")), If::new(buzz, || Text::new("Buzz")), )) - }, || { + }).or_else(|| { Text::new(format!("{}", self.count.get())) }), )) diff --git a/nuit-core/src/compose/view/aggregation/if.rs b/nuit-core/src/compose/view/aggregation/if.rs index 4d1475a..2d1eba3 100644 --- a/nuit-core/src/compose/view/aggregation/if.rs +++ b/nuit-core/src/compose/view/aggregation/if.rs @@ -6,6 +6,7 @@ use crate::{View, Node, Context, Event, IdPath, Id, IdentifyExt}; /// on a boolean condition. #[derive(Debug, Clone, PartialEq, Eq, Bind)] pub struct If { + condition: bool, then_view: Option, else_view: Option, } @@ -13,20 +14,30 @@ pub struct If { impl If { pub fn new(condition: bool, then_view: impl FnOnce() -> T) -> Self { Self { + condition, then_view: if condition { Some(then_view()) } else { None }, else_view: None, } } } +#[allow(clippy::if_not_else)] impl If { - #[allow(clippy::if_not_else)] pub fn new_or_else(condition: bool, then_view: impl FnOnce() -> T, else_view: impl FnOnce() -> F) -> Self { Self { + condition, then_view: if condition { Some(then_view()) } else { None }, else_view: if !condition { Some(else_view()) } else { None }, } } + + pub fn or_else(self, else_view: impl FnOnce() -> G) -> If { + If { + condition: self.condition, + then_view: self.then_view, + else_view: if !self.condition { Some(else_view()) } else { None }, + } + } } impl View for If where T: View, F: View {