nuit_core/compose/view/aggregation/
if.rs

1use nuit_derive::Bind;
2
3use crate::{View, Node, Context, Event, IdPath, Id, IdentifyExt};
4
5/// A conditional view that can take on one of at most two branches, depending
6/// on a boolean condition.
7#[derive(Debug, Clone, PartialEq, Eq, Bind)]
8pub struct If<T, F> {
9    then_view: Option<T>,
10    else_view: Option<F>,
11}
12
13impl<T> If<T, ()> {
14    pub fn new(condition: bool, then_view: impl FnOnce() -> T) -> Self {
15        Self {
16            then_view: if condition { Some(then_view()) } else { None },
17            else_view: None,
18        }
19    }
20}
21
22impl<T, F> If<T, F> {
23    pub fn new_or_else(condition: bool, then_view: impl FnOnce() -> T, else_view: impl FnOnce() -> F) -> Self {
24        Self {
25            then_view: if condition { Some(then_view()) } else { None },
26            else_view: if !condition { Some(else_view()) } else { None },
27        }
28    }
29}
30
31impl<T, F> View for If<T, F> where T: View, F: View {
32    fn fire(&self, event: &Event, event_path: &IdPath, context: &Context) {
33        if let Some(head) = event_path.head() {
34            match head {
35                Id::Index(0) => {
36                    if let Some(ref then_view) = self.then_view {
37                        then_view.fire(event, &event_path.tail(), &context.child(0))
38                    }
39                },
40                Id::Index(1) => {
41                    if let Some(ref else_view) = self.else_view {
42                        else_view.fire(event, &event_path.tail(), &context.child(1))
43                    }
44                },
45                i => panic!("Cannot fire event for child id {} on HStack which only has two childs", i)
46            }
47        }
48    }
49
50    fn render(&self, context: &Context) -> Node {
51        if let Some(ref then_view) = self.then_view {
52            Node::Child { wrapped: Box::new(then_view.render(&context.child(0)).identify(0)) }
53        } else if let Some(ref else_view) = self.else_view {
54            Node::Child { wrapped: Box::new(else_view.render(&context.child(1)).identify(1)) }
55        } else {
56            Node::Empty {}
57        }
58    }
59}