Skip to main content

glory_ui/
control.rs

1use std::cell::RefCell;
2use std::rc::Rc;
3
4use glory_core::Vary;
5use glory_render::{Descriptor, Props};
6
7use crate::app::{Error, Mounted, Result, Scope, Widget};
8
9type Factory = Box<dyn FnMut() -> Box<dyn Widget>>;
10pub struct When {
11    condition: Option<Vary<bool>>,
12    yes: Option<Factory>,
13    no: Option<Factory>,
14}
15pub fn when<W: Widget>(
16    condition: impl Into<Vary<bool>>,
17    mut yes: impl FnMut() -> W + 'static,
18) -> When {
19    When {
20        condition: Some(condition.into()),
21        yes: Some(Box::new(move || Box::new(yes()))),
22        no: None,
23    }
24}
25impl When {
26    pub fn otherwise<W: Widget>(mut self, mut no: impl FnMut() -> W + 'static) -> Self {
27        self.no = Some(Box::new(move || Box::new(no())));
28        self
29    }
30}
31struct Branch {
32    state: crate::branch::Branch<Mounted>,
33    yes: Factory,
34    no: Option<Factory>,
35}
36impl Widget for When {
37    fn build(&mut self, scope: &Scope) -> Result {
38        let anchor = scope.create(Descriptor::new(Props::Group))?;
39        let content = scope.child_in(anchor)?;
40        let parent = content.weak();
41        let session = Rc::downgrade(&scope.session()?);
42        let condition = self.condition.take().ok_or(Error::Gone)?;
43        let state = Rc::new(RefCell::new(Branch {
44            state: Default::default(),
45            yes: self.yes.take().ok_or(Error::Gone)?,
46            no: self.no.take(),
47        }));
48        scope.retain(content)?;
49        scope.retain(state.clone())?;
50        scope.structural(move || {
51            let Some(session) = session.upgrade() else {
52                return;
53            };
54            let Some(parent) = parent.upgrade() else {
55                return;
56            };
57            let show = match condition.try_get() {
58                Ok(show) => show,
59                Err(error) => {
60                    session.report(error.into());
61                    return;
62                }
63            };
64            let mut state = state.borrow_mut();
65            let Branch { state, yes, no } = &mut *state;
66            if let Err(error) = state.update(show, |show| {
67                if show {
68                    parent.mount_with(yes).map(Some)
69                } else {
70                    no.as_mut()
71                        .map(|factory| parent.mount_with(factory))
72                        .transpose()
73                }
74            }) {
75                session.report(error);
76            }
77        });
78        Ok(())
79    }
80}