Skip to main content

gpui_deck/
toggle.rs

1//! A controlled pressed button composed from the existing Button primitive.
2//! Derived from GPUI Kit v0.9.0's toggle contract; GPUI Deck delegates native
3//! activation, focus, disabled behavior, and geometry to Button.
4
5use std::rc::Rc;
6
7use gpui::{
8    AnyElement, App, ClickEvent, ElementId, FocusHandle, InteractiveElement, Interactivity,
9    IntoElement, ParentElement, RenderOnce, SharedString, StatefulInteractiveElement,
10    StyleRefinement, Styled, Toggled, Window, prelude::FluentBuilder as _,
11};
12
13use crate::Button;
14
15type ChangeHandler = Rc<dyn Fn(bool, &ClickEvent, &mut Window, &mut App)>;
16
17/// An unstyled toggle whose pressed value belongs to the application.
18///
19/// Activation requests the inverse of [`Self::pressed`]. Store the requested
20/// value and render it back to accept a change. The existing [`Button`] owns
21/// pointer and keyboard activation, focus, disabled handling, and layout geometry.
22#[derive(IntoElement)]
23pub struct Toggle {
24    button: Button,
25    pressed: bool,
26    on_change: Option<ChangeHandler>,
27}
28
29impl Toggle {
30    pub fn new(id: impl Into<ElementId>) -> Self {
31        Self {
32            button: Button::new(id),
33            pressed: false,
34            on_change: None,
35        }
36    }
37
38    /// Sets the controlled pressed state without requesting a change.
39    pub fn pressed(mut self, pressed: bool) -> Self {
40        self.pressed = pressed;
41        self
42    }
43
44    pub fn disabled(mut self, disabled: bool) -> Self {
45        self.button = self.button.disabled(disabled);
46        self
47    }
48
49    /// Keep this name stable; the pressed metadata describes the current state.
50    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
51        self.button = self.button.accessibility_label(label);
52        self
53    }
54
55    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
56        self.button = self.button.track_focus(focus);
57        self
58    }
59
60    pub fn tab_index(mut self, tab_index: isize) -> Self {
61        self.button = self.button.tab_index(tab_index);
62        self
63    }
64
65    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
66        self.button = self.button.tab_stop(tab_stop);
67        self
68    }
69
70    pub fn on_change(
71        mut self,
72        handler: impl Fn(bool, &ClickEvent, &mut Window, &mut App) + 'static,
73    ) -> Self {
74        self.on_change = Some(Rc::new(handler));
75        self
76    }
77}
78
79impl Styled for Toggle {
80    fn style(&mut self) -> &mut StyleRefinement {
81        self.button.style()
82    }
83}
84
85impl ParentElement for Toggle {
86    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
87        self.button.extend(elements);
88    }
89}
90
91impl InteractiveElement for Toggle {
92    fn interactivity(&mut self) -> &mut Interactivity {
93        self.button.interactivity()
94    }
95
96    crate::button::forward_hover_styles!(button);
97}
98
99impl StatefulInteractiveElement for Toggle {
100    crate::button::forward_active_styles!(button);
101}
102
103impl RenderOnce for Toggle {
104    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
105        let pressed = self.pressed;
106        self.button
107            .aria_toggled(if pressed {
108                Toggled::True
109            } else {
110                Toggled::False
111            })
112            .when_some(self.on_change, |button, on_change| {
113                button.on_click(move |event, window, cx| {
114                    on_change(!pressed, event, window, cx);
115                })
116            })
117            .render(window, cx)
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use std::cell::RefCell;
124
125    use gpui::{
126        Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, Role,
127        TestAppContext, accesskit, px,
128    };
129
130    use super::*;
131
132    #[gpui::test]
133    fn activation_requests_the_inverse_without_changing_controlled_state(cx: &mut TestAppContext) {
134        struct Harness {
135            pressed: bool,
136            focus: FocusHandle,
137            requests: Rc<RefCell<Vec<bool>>>,
138        }
139        impl Render for Harness {
140            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
141                let requests = self.requests.clone();
142                Toggle::new("toggle")
143                    .debug_selector(|| "toggle".into())
144                    .pressed(self.pressed)
145                    .track_focus(&self.focus)
146                    .accessibility_label("Unknown progress")
147                    .w(px(160.))
148                    .h(px(32.))
149                    .on_change(move |next, _, _, _| requests.borrow_mut().push(next))
150                    .child("Unknown progress")
151            }
152        }
153        let requests = Rc::new(RefCell::new(Vec::new()));
154        let (view, cx) = cx.add_window_view({
155            let requests = requests.clone();
156            move |_, cx| Harness {
157                pressed: false,
158                focus: cx.focus_handle(),
159                requests,
160            }
161        });
162        cx.update(|window, cx| {
163            window.activate_window();
164            window.draw(cx).clear(cx);
165        });
166        let point = cx.debug_bounds("toggle").unwrap().center();
167        cx.simulate_click(point, Modifiers::default());
168        cx.simulate_click(point, Modifiers::default());
169        assert_eq!(*requests.borrow(), [true, true]);
170        view.update(cx, |view, cx| {
171            assert!(
172                !view.pressed,
173                "a request does not mutate the application's value"
174            );
175            view.pressed = true;
176            cx.notify();
177        });
178        cx.update(|window, cx| window.draw(cx).clear(cx));
179        let keystroke =
180            cx.update(|_, cx| Keystroke::parse_with_os("space", cx.platform_info().os).unwrap());
181        cx.simulate_event(KeyDownEvent {
182            keystroke: keystroke.clone(),
183            is_held: false,
184            prefer_character_input: false,
185        });
186        cx.simulate_event(KeyUpEvent { keystroke });
187        assert_eq!(*requests.borrow(), [true, true, false]);
188        cx.update(|window, cx| {
189            let view = view.read(cx);
190            assert!(view.pressed);
191            let element = Toggle::new("native-toggle")
192                .pressed(view.pressed)
193                .track_focus(&view.focus)
194                .accessibility_label("Unknown progress")
195                .render(window, cx)
196                .into_element();
197            assert_eq!(element.a11y_role(), Some(Role::Button));
198            let mut node = accesskit::Node::new(Role::Button);
199            element.write_a11y_info(&mut node);
200            assert_eq!(node.toggled(), Some(Toggled::True));
201            assert_eq!(node.label(), Some("Unknown progress"));
202        });
203    }
204}