Skip to content

Commit

Permalink
Add more fluent if/else API
Browse files Browse the repository at this point in the history
  • Loading branch information
fwcd committed Sep 9, 2024
1 parent de52cad commit e8fc62d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
4 changes: 2 additions & 2 deletions examples/fizz_buzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
}),
))
Expand Down
13 changes: 12 additions & 1 deletion nuit-core/src/compose/view/aggregation/if.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,38 @@ use crate::{View, Node, Context, Event, IdPath, Id, IdentifyExt};
/// on a boolean condition.
#[derive(Debug, Clone, PartialEq, Eq, Bind)]
pub struct If<T, F> {
condition: bool,
then_view: Option<T>,
else_view: Option<F>,
}

impl<T> If<T, ()> {
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<T, F> If<T, F> {
#[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<G>(self, else_view: impl FnOnce() -> G) -> If<T, G> {
If {
condition: self.condition,
then_view: self.then_view,
else_view: if !self.condition { Some(else_view()) } else { None },
}
}
}

impl<T, F> View for If<T, F> where T: View, F: View {
Expand Down

0 comments on commit e8fc62d

Please sign in to comment.