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