Skip to main content

gpui_base/
toggle.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ClickEvent, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
5    IntoElement, MouseButton, ParentElement, Refineable as _, RenderOnce, Role, SharedString,
6    Stateful, StatefulInteractiveElement, StyleRefinement, Styled, Toggled, Window, div,
7    prelude::FluentBuilder as _, relative,
8};
9use smallvec::SmallVec;
10
11use crate::{StateStyle, StyledExt as _, TestSupportExt as _, a11y_disabled::A11yDisabledExt as _};
12
13type ChangeHandler = Rc<dyn Fn(bool, &ClickEvent, &mut Window, &mut App)>;
14
15/// An unstyled, controlled toggle button.
16///
17/// This primitive owns activation, focus, and accessibility behavior. The
18/// application owns all layout, visual states, sizes, and variants.
19#[derive(IntoElement)]
20pub struct Toggle {
21    id: ElementId,
22    base: Stateful<Div>,
23    style: StyleRefinement,
24    semantic_styles: ToggleStyles,
25    pressed: bool,
26    disabled: bool,
27    children: SmallVec<[AnyElement; 2]>,
28    on_change: Option<ChangeHandler>,
29    accessibility_label: Option<SharedString>,
30    tab_index: isize,
31    tab_stop: bool,
32    tracked_focus: Option<FocusHandle>,
33}
34
35/// Semantic root styles supported by [`Toggle`].
36#[derive(Default)]
37pub struct ToggleStyles {
38    pressed: StyleRefinement,
39    disabled: StyleRefinement,
40}
41
42impl ToggleStyles {
43    pub fn pressed(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
44        self.pressed
45            .refine(&build(StateStyle::default()).into_refinement());
46        self
47    }
48
49    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
50        self.disabled
51            .refine(&build(StateStyle::default()).into_refinement());
52        self
53    }
54}
55
56impl Toggle {
57    pub fn new(id: impl Into<ElementId>) -> Self {
58        let id = id.into();
59        Self {
60            base: div().id(id.clone()),
61            id,
62            style: StyleRefinement::default(),
63            semantic_styles: ToggleStyles::default(),
64            pressed: false,
65            disabled: false,
66            children: SmallVec::new(),
67            on_change: None,
68            accessibility_label: None,
69            tab_index: 0,
70            tab_stop: true,
71            tracked_focus: None,
72        }
73    }
74
75    pub fn pressed(mut self, pressed: bool) -> Self {
76        self.pressed = pressed;
77        self
78    }
79
80    pub fn disabled(mut self, disabled: bool) -> Self {
81        self.disabled = disabled;
82        self
83    }
84
85    /// Configures application-owned styles for the toggle's semantic states.
86    pub fn styles(mut self, build: impl FnOnce(ToggleStyles) -> ToggleStyles) -> Self {
87        self.semantic_styles = build(self.semantic_styles);
88        self
89    }
90
91    fn resolved_style(&self) -> StyleRefinement {
92        crate::state_style::resolve_style(
93            &self.style,
94            [
95                self.pressed.then_some(&self.semantic_styles.pressed),
96                self.disabled.then_some(&self.semantic_styles.disabled),
97            ]
98            .into_iter()
99            .flatten(),
100        )
101    }
102
103    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
104        self.accessibility_label = Some(label.into());
105        self
106    }
107
108    /// Handles a request to change the controlled pressed state.
109    pub fn on_change(
110        mut self,
111        handler: impl Fn(bool, &ClickEvent, &mut Window, &mut App) + 'static,
112    ) -> Self {
113        self.on_change = Some(Rc::new(handler));
114        self
115    }
116
117    pub fn tab_index(mut self, tab_index: isize) -> Self {
118        self.tab_index = tab_index;
119        self
120    }
121
122    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
123        self.tab_stop = tab_stop;
124        self
125    }
126
127    pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
128        self.tracked_focus = Some(focus_handle.clone());
129        self
130    }
131
132    fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
133        window
134            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
135            .read(cx)
136            .clone()
137    }
138}
139
140impl Styled for Toggle {
141    fn style(&mut self) -> &mut StyleRefinement {
142        &mut self.style
143    }
144}
145
146impl ParentElement for Toggle {
147    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
148        self.children.extend(elements);
149    }
150}
151
152impl InteractiveElement for Toggle {
153    fn interactivity(&mut self) -> &mut Interactivity {
154        self.base.interactivity()
155    }
156}
157
158impl StatefulInteractiveElement for Toggle {}
159
160impl RenderOnce for Toggle {
161    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
162        let focus_handle = self
163            .tracked_focus
164            .clone()
165            .unwrap_or_else(|| self.focus_handle(window, cx));
166        let pressed = self.pressed;
167        let disabled = self.disabled;
168        let style = self.resolved_style();
169        let on_change = self.on_change;
170
171        self.base
172            .test_support()
173            .role(Role::Button)
174            // Match Button's neutral control geometry: a fixed-size toggle
175            // centers ordinary content, while callers still own its size,
176            // spacing and visual treatment.
177            .flex()
178            .items_center()
179            .justify_center()
180            .line_height(relative(1.))
181            .aria_toggled(if pressed {
182                Toggled::True
183            } else {
184                Toggled::False
185            })
186            .when_some(self.accessibility_label, |this, label| {
187                this.aria_label(label)
188            })
189            // Keep the current focus in the dispatch tree when activation
190            // disables this control, so Tab can still leave in either direction.
191            .when(!disabled || focus_handle.is_focused(window), |this| {
192                this.track_focus(
193                    &focus_handle
194                        .tab_index(self.tab_index)
195                        .tab_stop(self.tab_stop && !disabled),
196                )
197            })
198            .when(disabled, |this| {
199                this.on_mouse_down(MouseButton::Left, |_, _, cx| {
200                    cx.stop_propagation();
201                })
202            })
203            .when_some(
204                (!disabled).then_some(on_change).flatten(),
205                |this, on_change| {
206                    this.on_click(move |event, window, cx| {
207                        on_change(!pressed, event, window, cx);
208                    })
209                },
210            )
211            .children(self.children)
212            .refine_style(&style)
213            .a11y_disabled(disabled)
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use crate::ElementExt as _;
221    use std::{
222        cell::{Cell, RefCell},
223        rc::Rc,
224        sync::{Arc, Mutex},
225    };
226
227    use gpui::{
228        Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
229        TestAppContext, VisualTestContext, accesskit, canvas, point, px,
230    };
231
232    struct Harness {
233        pressed: bool,
234        disabled: bool,
235        changes: Rc<RefCell<Vec<bool>>>,
236        keyboard_changes: Rc<Cell<usize>>,
237    }
238
239    impl Render for Harness {
240        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
241            let changes = self.changes.clone();
242            let keyboard_changes = self.keyboard_changes.clone();
243            Toggle::new("toggle")
244                .pressed(self.pressed)
245                .disabled(self.disabled)
246                .size(px(100.))
247                .on_change(move |pressed, event, _, _| {
248                    changes.borrow_mut().push(pressed);
249                    if matches!(event, ClickEvent::Keyboard(_)) {
250                        keyboard_changes.set(keyboard_changes.get() + 1);
251                    }
252                })
253        }
254    }
255
256    fn harness(
257        cx: &mut TestAppContext,
258        pressed: bool,
259        disabled: bool,
260    ) -> (
261        &mut VisualTestContext,
262        Rc<RefCell<Vec<bool>>>,
263        Rc<Cell<usize>>,
264    ) {
265        let changes = Rc::new(RefCell::new(Vec::new()));
266        let keyboard_changes = Rc::new(Cell::new(0));
267        let (_, cx) = cx.add_window_view({
268            let changes = changes.clone();
269            let keyboard_changes = keyboard_changes.clone();
270            move |_, _| Harness {
271                pressed,
272                disabled,
273                changes,
274                keyboard_changes,
275            }
276        });
277        cx.update(|window, cx| window.draw(cx).clear(cx));
278        (cx, changes, keyboard_changes)
279    }
280
281    #[gpui::test]
282    fn pointer_requests_inverse_controlled_state_once(cx: &mut TestAppContext) {
283        for (pressed, expected) in [(false, true), (true, false)] {
284            let (cx, changes, _) = harness(cx, pressed, false);
285            cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
286            assert_eq!(changes.borrow().as_slice(), &[expected]);
287        }
288    }
289
290    #[gpui::test]
291    fn enter_and_space_use_one_native_keyboard_click_each(cx: &mut TestAppContext) {
292        let (cx, changes, keyboard_changes) = harness(cx, false, false);
293        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
294        changes.borrow_mut().clear();
295        cx.update(|window, cx| window.draw(cx).clear(cx));
296
297        for key in ["enter", "space"] {
298            let keystroke = Keystroke::parse(key).unwrap();
299            cx.simulate_event(KeyDownEvent {
300                keystroke: keystroke.clone(),
301                is_held: false,
302                prefer_character_input: false,
303            });
304            cx.simulate_event(KeyUpEvent { keystroke });
305        }
306        assert_eq!(changes.borrow().as_slice(), &[true, true]);
307        assert_eq!(keyboard_changes.get(), 2);
308    }
309
310    #[gpui::test]
311    fn disabled_toggle_is_inert(cx: &mut TestAppContext) {
312        let (cx, changes, _) = harness(cx, false, true);
313        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
314        cx.simulate_keystrokes("enter space");
315        assert!(changes.borrow().is_empty());
316    }
317
318    #[gpui::test]
319    fn fixed_height_toggle_centers_ordinary_child_geometry(cx: &mut TestAppContext) {
320        type Captured = Arc<
321            Mutex<(
322                Option<gpui::Bounds<gpui::Pixels>>,
323                Option<gpui::Bounds<gpui::Pixels>>,
324            )>,
325        >;
326
327        struct AlignmentProbe(Captured);
328
329        impl Render for AlignmentProbe {
330            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
331                let root_capture = self.0.clone();
332                let child_capture = self.0.clone();
333                Toggle::new("alignment-toggle")
334                    .w(px(120.))
335                    .h(px(40.))
336                    .child(
337                        div()
338                            .w(px(48.))
339                            .h(px(12.))
340                            .on_prepaint(move |bounds, _, _| {
341                                child_capture.lock().unwrap().1 = Some(bounds);
342                            }),
343                    )
344                    .on_prepaint(move |bounds, _, _| {
345                        root_capture.lock().unwrap().0 = Some(bounds);
346                    })
347            }
348        }
349
350        let captured = Arc::new(Mutex::new((None, None)));
351        let (_, context) = cx.add_window_view({
352            let captured = captured.clone();
353            move |_, _| AlignmentProbe(captured)
354        });
355        context.update(|window, cx| window.draw(cx).clear(cx));
356
357        let (root, child) = *captured.lock().unwrap();
358        assert_eq!(
359            child.expect("child bounds").center(),
360            root.expect("toggle bounds").center()
361        );
362    }
363
364    #[test]
365    fn state_styling_and_children_are_application_owned() {
366        let _ = Toggle::new("styled")
367            .child("Label")
368            .styles(|styles| {
369                styles
370                    .pressed(|style| style.opacity(0.8))
371                    .disabled(|style| style.opacity(0.5))
372            })
373            .hover(|style| style.opacity(0.9))
374            .active(|style| style.opacity(0.8))
375            .focus_visible(|style| style.opacity(0.7));
376    }
377
378    #[test]
379    fn semantic_root_styles_follow_toggle_priority() {
380        let styled = |toggle: Toggle| {
381            toggle.styles(|styles| {
382                styles
383                    .pressed(|style| style.opacity(0.8))
384                    .disabled(|style| style.opacity(0.5))
385            })
386        };
387
388        assert_eq!(styled(Toggle::new("normal")).resolved_style().opacity, None);
389        assert_eq!(
390            styled(Toggle::new("pressed").pressed(true))
391                .resolved_style()
392                .opacity,
393            Some(0.8)
394        );
395        assert_eq!(
396            styled(Toggle::new("pressed-disabled").pressed(true).disabled(true))
397                .resolved_style()
398                .opacity,
399            Some(0.5)
400        );
401        assert_eq!(
402            styled(
403                Toggle::new("state-over-instance")
404                    .pressed(true)
405                    .disabled(true)
406                    .opacity(0.9),
407            )
408            .resolved_style()
409            .opacity,
410            Some(0.5)
411        );
412    }
413
414    #[gpui::test]
415    fn accessibility_exposes_button_role_toggled_state_and_action(cx: &mut TestAppContext) {
416        type Captured = Arc<Mutex<Option<(accesskit::Node, accesskit::Node)>>>;
417        struct Probe(Captured);
418        impl Render for Probe {
419            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
420                let captured = self.0.clone();
421                canvas(
422                    move |_, window, cx| {
423                        let mut info = |toggle: Toggle| {
424                            let mut node = accesskit::Node::new(Role::Button);
425                            toggle
426                                .render(window, cx)
427                                .into_element()
428                                .write_a11y_info(&mut node);
429                            node
430                        };
431                        let enabled = info(
432                            Toggle::new("enabled")
433                                .pressed(true)
434                                .accessibility_label("Bold")
435                                .on_change(|_, _, _, _| {}),
436                        );
437                        let disabled = info(
438                            Toggle::new("disabled")
439                                .disabled(true)
440                                .on_change(|_, _, _, _| {}),
441                        );
442                        *captured.lock().unwrap() = Some((enabled, disabled));
443                    },
444                    |_, _, _, _| {},
445                )
446            }
447        }
448        let captured: Captured = Arc::new(Mutex::new(None));
449        let result = captured.clone();
450        let (_, cx) = cx.add_window_view(move |_, _| Probe(captured));
451        cx.update(|window, cx| window.draw(cx).clear(cx));
452        let (enabled, disabled) = result.lock().unwrap().take().unwrap();
453        assert_eq!(enabled.role(), Role::Button);
454        assert_eq!(enabled.label(), Some("Bold"));
455        assert_eq!(enabled.toggled(), Some(Toggled::True));
456        assert!(enabled.supports_action(accesskit::Action::Click));
457        assert_eq!(disabled.toggled(), Some(Toggled::False));
458        assert!(!disabled.supports_action(accesskit::Action::Click));
459    }
460}