Skip to main content

gpui_base/
switch.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 _,
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 binary control that owns switch interaction and semantics.
16///
17/// The checked value is controlled by the application. Activation reports the
18/// next value through [`Switch::on_change`]; the application must render that
19/// value back through [`Switch::checked`]. Children and all visual states remain
20/// application-owned.
21#[derive(IntoElement)]
22pub struct Switch {
23    id: ElementId,
24    base: Stateful<Div>,
25    style: StyleRefinement,
26    semantic_styles: SwitchStyles,
27    checked: bool,
28    disabled: bool,
29    children: SmallVec<[AnyElement; 2]>,
30    on_change: Option<ChangeHandler>,
31    accessibility_label: Option<SharedString>,
32    tab_index: isize,
33    tab_stop: bool,
34    provided_focus_handle: Option<FocusHandle>,
35}
36
37/// Semantic root styles supported by [`Switch`].
38#[derive(Default)]
39pub struct SwitchStyles {
40    checked: StyleRefinement,
41    disabled: StyleRefinement,
42}
43
44impl SwitchStyles {
45    pub fn checked(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
46        self.checked
47            .refine(&build(StateStyle::default()).into_refinement());
48        self
49    }
50
51    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
52        self.disabled
53            .refine(&build(StateStyle::default()).into_refinement());
54        self
55    }
56}
57
58/// An unstyled switch track with typed checked and disabled state projection.
59#[derive(IntoElement)]
60pub struct SwitchTrack {
61    base: Stateful<Div>,
62    style: StyleRefinement,
63    semantic_styles: SwitchTrackStyles,
64    checked: bool,
65    disabled: bool,
66    children: SmallVec<[AnyElement; 1]>,
67}
68
69/// Semantic styles supported by [`SwitchTrack`].
70#[derive(Default)]
71pub struct SwitchTrackStyles {
72    checked: StyleRefinement,
73    disabled: StyleRefinement,
74}
75
76impl SwitchTrackStyles {
77    pub fn checked(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
78        self.checked
79            .refine(&build(StateStyle::default()).into_refinement());
80        self
81    }
82
83    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
84        self.disabled
85            .refine(&build(StateStyle::default()).into_refinement());
86        self
87    }
88}
89
90impl SwitchTrack {
91    pub fn new(id: impl Into<ElementId>) -> Self {
92        Self {
93            base: div().id(id),
94            style: StyleRefinement::default(),
95            semantic_styles: SwitchTrackStyles::default(),
96            checked: false,
97            disabled: false,
98            children: SmallVec::new(),
99        }
100    }
101
102    pub fn checked(mut self, checked: bool) -> Self {
103        self.checked = checked;
104        self
105    }
106
107    pub fn disabled(mut self, disabled: bool) -> Self {
108        self.disabled = disabled;
109        self
110    }
111
112    pub fn styles(mut self, build: impl FnOnce(SwitchTrackStyles) -> SwitchTrackStyles) -> Self {
113        self.semantic_styles = build(self.semantic_styles);
114        self
115    }
116
117    fn resolved_style(&self) -> StyleRefinement {
118        crate::state_style::resolve_style(
119            &self.style,
120            [
121                self.checked.then_some(&self.semantic_styles.checked),
122                self.disabled.then_some(&self.semantic_styles.disabled),
123            ]
124            .into_iter()
125            .flatten(),
126        )
127    }
128}
129
130impl Styled for SwitchTrack {
131    fn style(&mut self) -> &mut StyleRefinement {
132        &mut self.style
133    }
134}
135
136impl ParentElement for SwitchTrack {
137    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
138        self.children.extend(elements);
139    }
140}
141
142impl InteractiveElement for SwitchTrack {
143    fn interactivity(&mut self) -> &mut Interactivity {
144        self.base.interactivity()
145    }
146}
147
148impl StatefulInteractiveElement for SwitchTrack {}
149
150impl RenderOnce for SwitchTrack {
151    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
152        let style = self.resolved_style();
153        self.base.children(self.children).refine_style(&style)
154    }
155}
156
157/// An unstyled switch thumb with typed checked and disabled state projection.
158#[derive(IntoElement)]
159pub struct SwitchThumb {
160    base: Div,
161    style: StyleRefinement,
162    semantic_styles: SwitchThumbStyles,
163    checked: bool,
164    disabled: bool,
165    children: SmallVec<[AnyElement; 1]>,
166}
167
168/// Semantic styles supported by [`SwitchThumb`].
169#[derive(Default)]
170pub struct SwitchThumbStyles {
171    checked: StyleRefinement,
172    disabled: StyleRefinement,
173}
174
175impl SwitchThumbStyles {
176    pub fn checked(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
177        self.checked
178            .refine(&build(StateStyle::default()).into_refinement());
179        self
180    }
181
182    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
183        self.disabled
184            .refine(&build(StateStyle::default()).into_refinement());
185        self
186    }
187}
188
189impl SwitchThumb {
190    pub fn new(checked: bool) -> Self {
191        Self {
192            base: div(),
193            style: StyleRefinement::default(),
194            semantic_styles: SwitchThumbStyles::default(),
195            checked,
196            disabled: false,
197            children: SmallVec::new(),
198        }
199    }
200
201    pub fn disabled(mut self, disabled: bool) -> Self {
202        self.disabled = disabled;
203        self
204    }
205
206    pub fn styles(mut self, build: impl FnOnce(SwitchThumbStyles) -> SwitchThumbStyles) -> Self {
207        self.semantic_styles = build(self.semantic_styles);
208        self
209    }
210
211    fn resolved_style(&self) -> StyleRefinement {
212        crate::state_style::resolve_style(
213            &self.style,
214            [
215                self.checked.then_some(&self.semantic_styles.checked),
216                self.disabled.then_some(&self.semantic_styles.disabled),
217            ]
218            .into_iter()
219            .flatten(),
220        )
221    }
222}
223
224impl Styled for SwitchThumb {
225    fn style(&mut self) -> &mut StyleRefinement {
226        &mut self.style
227    }
228}
229
230impl ParentElement for SwitchThumb {
231    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
232        self.children.extend(elements);
233    }
234}
235
236impl RenderOnce for SwitchThumb {
237    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
238        let style = self.resolved_style();
239        self.base.children(self.children).refine_style(&style)
240    }
241}
242
243impl Switch {
244    pub fn new(id: impl Into<ElementId>) -> Self {
245        let id = id.into();
246        Self {
247            base: div().id(id.clone()),
248            id,
249            style: StyleRefinement::default(),
250            semantic_styles: SwitchStyles::default(),
251            checked: false,
252            disabled: false,
253            children: SmallVec::new(),
254            on_change: None,
255            accessibility_label: None,
256            tab_index: 0,
257            tab_stop: true,
258            provided_focus_handle: None,
259        }
260    }
261
262    /// Sets the application-controlled checked value.
263    pub fn checked(mut self, checked: bool) -> Self {
264        self.checked = checked;
265        self
266    }
267
268    /// Sets whether pointer and keyboard activation are ignored.
269    pub fn disabled(mut self, disabled: bool) -> Self {
270        self.disabled = disabled;
271        self
272    }
273
274    /// Configures application-owned styles for the switch's semantic states.
275    pub fn styles(mut self, build: impl FnOnce(SwitchStyles) -> SwitchStyles) -> Self {
276        self.semantic_styles = build(self.semantic_styles);
277        self
278    }
279
280    fn resolved_style(&self) -> StyleRefinement {
281        crate::state_style::resolve_style(
282            &self.style,
283            [
284                self.checked.then_some(&self.semantic_styles.checked),
285                self.disabled.then_some(&self.semantic_styles.disabled),
286            ]
287            .into_iter()
288            .flatten(),
289        )
290    }
291
292    /// Handles activation with the next checked value and its input event.
293    pub fn on_change(
294        mut self,
295        handler: impl Fn(bool, &ClickEvent, &mut Window, &mut App) + 'static,
296    ) -> Self {
297        self.on_change = Some(Rc::new(handler));
298        self
299    }
300
301    /// Sets the name exposed to accessibility clients.
302    ///
303    /// A switch without text children has no accessible name, so set this
304    /// whenever it is drawn without visible text.
305    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
306        self.accessibility_label = Some(label.into());
307        self
308    }
309
310    /// Sets the focus traversal index. Use this within a GPUI tab group.
311    pub fn tab_index(mut self, tab_index: isize) -> Self {
312        self.tab_index = tab_index;
313        self
314    }
315
316    /// Sets whether the switch participates in keyboard focus traversal.
317    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
318        self.tab_stop = tab_stop;
319        self
320    }
321
322    /// Uses a caller-owned focus handle instead of creating keyed state.
323    pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
324        self.provided_focus_handle = Some(focus_handle.clone());
325        self
326    }
327
328    fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
329        self.provided_focus_handle.clone().unwrap_or_else(|| {
330            window
331                .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
332                .read(cx)
333                .clone()
334        })
335    }
336}
337
338impl Styled for Switch {
339    fn style(&mut self) -> &mut StyleRefinement {
340        &mut self.style
341    }
342}
343
344impl ParentElement for Switch {
345    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
346        self.children.extend(elements);
347    }
348}
349
350impl InteractiveElement for Switch {
351    fn interactivity(&mut self) -> &mut Interactivity {
352        self.base.interactivity()
353    }
354}
355
356impl StatefulInteractiveElement for Switch {}
357
358impl RenderOnce for Switch {
359    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
360        let focus_handle = self.focus_handle(window, cx);
361        let checked = self.checked;
362        let disabled = self.disabled;
363        let style = self.resolved_style();
364
365        self.base
366            .test_support()
367            .role(Role::Switch)
368            .aria_toggled(if checked {
369                Toggled::True
370            } else {
371                Toggled::False
372            })
373            .when_some(self.accessibility_label, |this, label| {
374                this.aria_label(label)
375            })
376            // Keep the current focus in the dispatch tree when activation
377            // disables this control, so Tab can still leave in either direction.
378            .when(!disabled || focus_handle.is_focused(window), |this| {
379                this.track_focus(
380                    &focus_handle
381                        .tab_index(self.tab_index)
382                        .tab_stop(self.tab_stop && !disabled),
383                )
384            })
385            .when(disabled, |this| {
386                this.on_mouse_down(MouseButton::Left, |_, _, cx| {
387                    cx.stop_propagation();
388                })
389            })
390            .when_some(
391                (!disabled).then_some(self.on_change).flatten(),
392                |this, on_change| {
393                    this.on_click(move |event, window, cx| {
394                        on_change(!checked, event, window, cx);
395                    })
396                },
397            )
398            .children(self.children)
399            .refine_style(&style)
400            .a11y_disabled(disabled)
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407    use std::{
408        cell::Cell,
409        rc::Rc,
410        sync::{Arc, Mutex},
411    };
412
413    use gpui::{
414        Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
415        TestAppContext, VisualTestContext, accesskit, canvas, point, px,
416    };
417
418    #[test]
419    fn track_projects_checked_disabled_and_instance_style_priority() {
420        let normal_color = gpui::hsla(0.0, 0.0, 0.2, 1.0);
421        let checked_color = gpui::hsla(0.6, 0.7, 0.5, 1.0);
422        let disabled_color = gpui::hsla(0.6, 0.7, 0.5, 0.5);
423        let track = |checked, disabled| {
424            SwitchTrack::new(("track", usize::from(checked) * 2 + usize::from(disabled)))
425                .checked(checked)
426                .disabled(disabled)
427                .when(!checked, |this| this.bg(normal_color))
428                .styles(|styles| {
429                    styles
430                        .checked(|style| style.bg(checked_color))
431                        .disabled(|style| style.when(checked, |style| style.bg(disabled_color)))
432                })
433        };
434
435        assert_eq!(
436            track(false, false).resolved_style().background,
437            Some(normal_color.into())
438        );
439        assert_eq!(
440            track(false, true).resolved_style().background,
441            Some(normal_color.into())
442        );
443        assert_eq!(
444            track(true, false).resolved_style().background,
445            Some(checked_color.into())
446        );
447        assert_eq!(
448            track(true, true).resolved_style().background,
449            Some(disabled_color.into())
450        );
451        // Semantic states layer over the instance chain, so an instance
452        // background does not defeat the disabled state.
453        assert_eq!(
454            track(true, true)
455                .bg(normal_color)
456                .resolved_style()
457                .background,
458            Some(disabled_color.into())
459        );
460    }
461
462    #[test]
463    fn track_identity_is_scoped_to_its_switch() {
464        fn track(switch_id: &'static str) -> SwitchTrack {
465            SwitchTrack::new((ElementId::from(switch_id), "track"))
466        }
467
468        let first = track("first-switch");
469        let second = track("second-switch");
470
471        assert_eq!(
472            gpui::Element::id(&first.base),
473            Some((ElementId::from("first-switch"), "track").into())
474        );
475        assert_eq!(
476            gpui::Element::id(&second.base),
477            Some((ElementId::from("second-switch"), "track").into())
478        );
479        assert_ne!(
480            gpui::Element::id(&first.base),
481            gpui::Element::id(&second.base)
482        );
483    }
484
485    #[test]
486    fn thumb_projects_checked_disabled_and_instance_style_priority() {
487        let checked_color = gpui::hsla(0.6, 0.7, 0.5, 1.0);
488        let disabled_color = gpui::hsla(0.1, 0.2, 0.3, 0.5);
489        let thumb = |checked, disabled| {
490            SwitchThumb::new(checked)
491                .disabled(disabled)
492                .styles(|styles| {
493                    styles
494                        .checked(|style| style.bg(checked_color))
495                        .disabled(|style| style.bg(disabled_color))
496                })
497        };
498
499        assert_eq!(
500            thumb(true, false).resolved_style().background,
501            Some(checked_color.into())
502        );
503        assert_eq!(
504            thumb(true, true).resolved_style().background,
505            Some(disabled_color.into())
506        );
507        assert_eq!(
508            thumb(true, true)
509                .bg(checked_color)
510                .resolved_style()
511                .background,
512            Some(disabled_color.into())
513        );
514    }
515
516    struct SwitchHarness {
517        checked: bool,
518        disabled: bool,
519        toggles: Rc<Cell<usize>>,
520        keyboard_events: Rc<Cell<usize>>,
521        last_value: Rc<Cell<bool>>,
522        parent_clicks: Rc<Cell<usize>>,
523    }
524
525    impl Render for SwitchHarness {
526        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
527            let toggles = self.toggles.clone();
528            let keyboard_events = self.keyboard_events.clone();
529            let last_value = self.last_value.clone();
530            let parent_clicks = self.parent_clicks.clone();
531
532            div()
533                .id("switch-parent")
534                .tab_group()
535                .size(px(100.))
536                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
537                .child(
538                    Switch::new("switch")
539                        .checked(self.checked)
540                        .disabled(self.disabled)
541                        .size_full()
542                        .on_change(move |value, event, _, _| {
543                            toggles.set(toggles.get() + 1);
544                            last_value.set(value);
545                            if matches!(event, ClickEvent::Keyboard(_)) {
546                                keyboard_events.set(keyboard_events.get() + 1);
547                            }
548                        }),
549                )
550        }
551    }
552
553    fn harness(
554        cx: &mut TestAppContext,
555        checked: bool,
556        disabled: bool,
557    ) -> (
558        &mut VisualTestContext,
559        Rc<Cell<usize>>,
560        Rc<Cell<usize>>,
561        Rc<Cell<bool>>,
562        Rc<Cell<usize>>,
563    ) {
564        let toggles = Rc::new(Cell::new(0));
565        let keyboard_events = Rc::new(Cell::new(0));
566        let last_value = Rc::new(Cell::new(checked));
567        let parent_clicks = Rc::new(Cell::new(0));
568        let (_, cx) = cx.add_window_view({
569            let toggles = toggles.clone();
570            let keyboard_events = keyboard_events.clone();
571            let last_value = last_value.clone();
572            let parent_clicks = parent_clicks.clone();
573            move |_, _| SwitchHarness {
574                checked,
575                disabled,
576                toggles,
577                keyboard_events,
578                last_value,
579                parent_clicks,
580            }
581        });
582        cx.update(|window, cx| window.draw(cx).clear(cx));
583        (cx, toggles, keyboard_events, last_value, parent_clicks)
584    }
585
586    fn activate_key(cx: &mut VisualTestContext, key: &str) {
587        let keystroke =
588            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
589        cx.simulate_event(KeyDownEvent {
590            keystroke: keystroke.clone(),
591            is_held: false,
592            prefer_character_input: false,
593        });
594        cx.simulate_event(KeyUpEvent { keystroke });
595    }
596
597    #[gpui::test]
598    fn pointer_reports_the_next_value_once(cx: &mut TestAppContext) {
599        let (cx, toggles, keyboard_events, last_value, _) = harness(cx, false, false);
600
601        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
602
603        assert_eq!(toggles.get(), 1);
604        assert_eq!(keyboard_events.get(), 0);
605        assert!(last_value.get());
606    }
607
608    #[gpui::test]
609    fn enter_and_space_report_one_native_keyboard_activation_each(cx: &mut TestAppContext) {
610        let (cx, toggles, keyboard_events, last_value, _) = harness(cx, false, false);
611        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
612        toggles.set(0);
613        cx.update(|window, cx| {
614            assert!(window.focused(cx).is_some());
615            window.draw(cx).clear(cx);
616        });
617
618        activate_key(cx, "enter");
619        activate_key(cx, "space");
620
621        assert_eq!(toggles.get(), 2);
622        assert_eq!(keyboard_events.get(), 2);
623        assert!(last_value.get());
624    }
625
626    #[gpui::test]
627    fn disabled_switch_is_inert_and_blocks_parent_activation(cx: &mut TestAppContext) {
628        let (cx, toggles, _, _, parent_clicks) = harness(cx, false, true);
629
630        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
631        activate_key(cx, "enter");
632        activate_key(cx, "space");
633
634        assert_eq!(toggles.get(), 0);
635        assert_eq!(parent_clicks.get(), 0);
636    }
637
638    #[test]
639    fn application_owned_state_styles_are_available() {
640        let _ = Switch::new("states")
641            .styles(|styles| {
642                styles
643                    .checked(|style| style.opacity(0.8))
644                    .disabled(|style| style.opacity(0.5))
645            })
646            .hover(|style| style.opacity(0.9))
647            .active(|style| style.opacity(0.8))
648            .focus_visible(|style| style.opacity(0.7));
649    }
650
651    #[test]
652    fn semantic_root_styles_follow_switch_priority() {
653        let styled = |switch: Switch| {
654            switch.styles(|styles| {
655                styles
656                    .checked(|style| style.opacity(0.8))
657                    .disabled(|style| style.opacity(0.5))
658            })
659        };
660
661        assert_eq!(styled(Switch::new("normal")).resolved_style().opacity, None);
662        assert_eq!(
663            styled(Switch::new("checked").checked(true))
664                .resolved_style()
665                .opacity,
666            Some(0.8)
667        );
668        assert_eq!(
669            styled(Switch::new("checked-disabled").checked(true).disabled(true))
670                .resolved_style()
671                .opacity,
672            Some(0.5)
673        );
674        assert_eq!(
675            styled(
676                Switch::new("state-over-instance")
677                    .checked(true)
678                    .disabled(true)
679                    .opacity(0.9),
680            )
681            .resolved_style()
682            .opacity,
683            Some(0.5)
684        );
685    }
686
687    #[gpui::test]
688    fn accessibility_exposes_switch_role_label_and_toggled_state(cx: &mut TestAppContext) {
689        type Captured = Arc<Mutex<Option<(accesskit::Node, accesskit::Node)>>>;
690
691        struct A11yProbe {
692            captured: Captured,
693        }
694
695        impl Render for A11yProbe {
696            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
697                let captured = self.captured.clone();
698                canvas(
699                    move |_, window, cx| {
700                        let mut info = |switch: Switch| {
701                            let mut node = accesskit::Node::new(Role::Switch);
702                            switch
703                                .render(window, cx)
704                                .into_element()
705                                .write_a11y_info(&mut node);
706                            node
707                        };
708                        let enabled = info(
709                            Switch::new("enabled")
710                                .checked(true)
711                                .accessibility_label("Airplane mode")
712                                .on_change(|_, _, _, _| {}),
713                        );
714                        let disabled = info(
715                            Switch::new("disabled")
716                                .checked(false)
717                                .disabled(true)
718                                .accessibility_label("Airplane mode")
719                                .on_change(|_, _, _, _| {}),
720                        );
721                        *captured.lock().unwrap() = Some((enabled, disabled));
722                    },
723                    |_, _, _, _| {},
724                )
725            }
726        }
727
728        let captured: Captured = Arc::new(Mutex::new(None));
729        let result = captured.clone();
730        let (_, cx) = cx.add_window_view(move |_, _| A11yProbe { captured });
731        cx.update(|window, cx| window.draw(cx).clear(cx));
732        let (enabled, disabled) = result.lock().unwrap().take().unwrap();
733
734        assert_eq!(enabled.role(), Role::Switch);
735        assert_eq!(enabled.label(), Some("Airplane mode"));
736        assert_eq!(enabled.toggled(), Some(Toggled::True));
737        assert!(enabled.supports_action(accesskit::Action::Click));
738
739        assert_eq!(disabled.role(), Role::Switch);
740        assert_eq!(disabled.toggled(), Some(Toggled::False));
741        assert!(!disabled.supports_action(accesskit::Action::Click));
742        assert!(!enabled.is_disabled());
743        assert!(disabled.is_disabled());
744    }
745}