Skip to main content

euv_ui/component/switch/view/
impl.rs

1use super::*;
2
3/// Inherent implementation of [`EuvSwitchState`].
4impl EuvSwitchState {
5    /// Creates a state handle for the given checked signal.
6    ///
7    /// The handle is a thin wrapper: it never owns the signal, it only
8    /// gives the view a place to hang [`Self::toggle`] and
9    /// [`Self::on_toggle`] without threading bare signals around.
10    ///
11    /// # Arguments
12    ///
13    /// - `Signal<bool>` - The checked-state signal to wrap.
14    ///
15    /// # Returns
16    ///
17    /// - `EuvSwitchState` - The state handle.
18    pub fn new(checked: Signal<bool>) -> Self {
19        Self { checked }
20    }
21
22    /// Flips the checked state of the switch.
23    ///
24    /// The click handler is a no-op while the switch is disabled, so a
25    /// disabled switch can never be flipped by a stray click.
26    pub fn toggle(&self) {
27        let current: bool = self.get_checked().get();
28        self.get_checked().set(!current);
29    }
30
31    /// Builds a click handler that toggles the switch.
32    ///
33    /// # Arguments
34    ///
35    /// - `Signal<bool>` - The disabled signal consulted on every click.
36    ///
37    /// # Returns
38    ///
39    /// - `Option<Rc<dyn Fn(Event)>>` - A click handler toggling the
40    ///   checked signal, or ignoring the event while disabled.
41    pub fn on_toggle(&self, disabled: Signal<bool>) -> Option<Rc<dyn Fn(Event)>> {
42        let state: EuvSwitchState = *self;
43        Some(Rc::new(move |_: Event| {
44            if disabled.get() {
45                return;
46            }
47            state.toggle();
48        }))
49    }
50}