Skip to main content

gpui_component/
switch.rs

1use crate::{
2    ActiveTheme, Disableable, FocusableExt, Side, Sizable, Size, StyledExt, ThemeStyled as _,
3    text::Text, tooltip::ComponentTooltip,
4};
5use gpui::{
6    App, Background, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement as _,
7    RenderOnce, SharedString, StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _,
8    px,
9};
10use gpui_base::{Switch as BaseSwitch, SwitchThumb, SwitchTrack, spring};
11use std::rc::Rc;
12
13/// A Switch element that can be toggled on or off.
14#[derive(IntoElement)]
15pub struct Switch {
16    id: ElementId,
17    style: StyleRefinement,
18    checked: bool,
19    disabled: bool,
20    label: Option<Text>,
21    /// The announced name, when the visible label is not it.
22    accessibility_label: Option<SharedString>,
23    label_side: Side,
24    on_click: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
25    size: Size,
26    color: Option<Hsla>,
27    tooltip: ComponentTooltip,
28    tab_stop: bool,
29    tab_index: isize,
30    focus_ring_enabled: bool,
31}
32
33impl Switch {
34    /// Create a new Switch element.
35    pub fn new(id: impl Into<ElementId>) -> Self {
36        let id: ElementId = id.into();
37        Self {
38            id: id.clone(),
39            style: StyleRefinement::default(),
40            checked: false,
41            disabled: false,
42            label: None,
43            accessibility_label: None,
44            on_click: None,
45            label_side: Side::Right,
46            size: Size::Medium,
47            color: None,
48            tooltip: ComponentTooltip::default(),
49            tab_stop: true,
50            tab_index: 0,
51            focus_ring_enabled: true,
52        }
53    }
54
55    /// Set the checked state of the switch.
56    pub fn checked(mut self, checked: bool) -> Self {
57        self.checked = checked;
58        self
59    }
60
61    /// Set the label of the switch.
62    pub fn label(mut self, label: impl Into<Text>) -> Self {
63        self.label = Some(label.into());
64        self
65    }
66
67    /// Set the name a screen reader announces, when the visible label is not
68    /// it.
69    ///
70    /// A switch's name comes from its [`label`](Self::label) by default.
71    /// Setting this replaces the announced name without changing what is
72    /// displayed.
73    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
74        self.accessibility_label = Some(label.into());
75        self
76    }
77
78    /// Alias for [`Self::on_change`]. The last callback registered with either name wins.
79    pub fn on_click<F>(self, handler: F) -> Self
80    where
81        F: Fn(&bool, &mut Window, &mut App) + 'static,
82    {
83        self.on_change(handler)
84    }
85
86    /// Handle a requested checked value from pointer or keyboard activation.
87    ///
88    /// This is a controlled value: the owner must write the requested value and
89    /// call `cx.notify()` to render it. Disabled controls do not call the handler.
90    /// This and [`Self::on_click`] share one callback; chaining them replaces
91    /// the previous handler instead of calling both.
92    pub fn on_change<F>(mut self, handler: F) -> Self
93    where
94        F: Fn(&bool, &mut Window, &mut App) + 'static,
95    {
96        self.on_click = Some(Rc::new(handler));
97        self
98    }
99
100    /// Set the background color of the switch when checked.
101    /// Defaults to `cx.theme().primary`.
102    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
103        self.color = Some(color.into());
104        self
105    }
106
107    /// Set tooltip text for the switch.
108    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
109        self.tooltip.text = Some((tooltip.into(), None));
110        self
111    }
112
113    /// Set whether the switch participates in keyboard focus traversal,
114    /// default is true.
115    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
116        self.tab_stop = tab_stop;
117        self
118    }
119
120    /// Set the focus traversal index within a GPUI tab group, default is 0.
121    pub fn tab_index(mut self, tab_index: isize) -> Self {
122        self.tab_index = tab_index;
123        self
124    }
125}
126
127impl Styled for Switch {
128    fn style(&mut self) -> &mut gpui::StyleRefinement {
129        &mut self.style
130    }
131}
132
133impl Sizable for Switch {
134    fn with_size(mut self, size: impl Into<Size>) -> Self {
135        self.size = size.into();
136        self
137    }
138}
139
140impl Disableable for Switch {
141    fn disabled(mut self, disabled: bool) -> Self {
142        self.disabled = disabled;
143        self
144    }
145}
146
147impl FocusableExt for Switch {
148    fn focus_ring(mut self, enabled: bool) -> Self {
149        self.focus_ring_enabled = enabled;
150        self
151    }
152
153    fn is_focus_ring_enabled(&self) -> bool {
154        self.focus_ring_enabled
155    }
156}
157
158impl RenderOnce for Switch {
159    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
160        let checked = self.checked;
161        let on_click = self.on_click.clone();
162        let accessibility_label = self
163            .accessibility_label
164            .clone()
165            .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
166        let focus_handle = window
167            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
168            .read(cx)
169            .clone();
170        let is_focused = focus_handle.is_focused(window);
171
172        let checked_bg = self
173            .color
174            .map(Background::from)
175            .unwrap_or(cx.theme().tokens.primary.into());
176        let unchecked_bg: Background = cx.theme().tokens.switch.into();
177        // GPUI's element opacity multiplies each primitive's alpha instead of
178        // compositing the subtree as one group, so fading the whole control
179        // would let the track show through the thumb. Fading the track alone
180        // lands on the pixels a grouped fade would: the thumb is `background`.
181        let disabled_bg = if checked { checked_bg } else { unchecked_bg }.opacity(0.5);
182        let toggle_bg: Background = cx.theme().tokens.switch_thumb.into();
183        let disabled_label_color = cx.theme().muted_foreground;
184
185        let (bg_width, bg_height) = match self.size {
186            Size::XSmall | Size::Small => (px(28.), px(16.)),
187            _ => (px(36.), px(20.)),
188        };
189        let bar_width = match self.size {
190            Size::XSmall | Size::Small => px(12.),
191            _ => px(16.),
192        };
193        let inset = px(2.);
194        let radius = if cx.theme().radius >= px(4.) {
195            bg_height
196        } else {
197            cx.theme().radius
198        };
199
200        // The thumb's position is geometry, not a semantic state style: a
201        // `checked` style setting `left` outranks the instance style by the
202        // documented precedence, which left the travel visible in one direction
203        // only. The spring owns it end to end and reverses from wherever the
204        // thumb is when the switch is toggled again mid-travel.
205        let thumb_x = spring(
206            (self.id.clone(), "thumb"),
207            if checked {
208                bg_width - bar_width - inset * 2
209            } else {
210                px(0.)
211            },
212            cx.theme().motion_tokens().spring_move,
213            window,
214            cx,
215        );
216
217        div().refine_style(&self.style).child(
218            BaseSwitch::new(self.id.clone())
219                .checked(checked)
220                .disabled(self.disabled)
221                .styles(|styles| {
222                    styles.disabled(|style| {
223                        style.text_color(disabled_label_color).cursor_not_allowed()
224                    })
225                })
226                .when_some(accessibility_label, |this, label| {
227                    this.accessibility_label(label)
228                })
229                .when_some(on_click, |this, on_click| {
230                    this.on_change(move |next, _, window, cx| on_click(&next, window, cx))
231                })
232                .tab_stop(self.tab_stop)
233                .tab_index(self.tab_index)
234                .track_focus(&focus_handle)
235                .h_flex()
236                .gap_2()
237                .items_start()
238                .when(self.label_side.is_left(), |this| this.flex_row_reverse())
239                .child(
240                    // Switch Bar
241                    SwitchTrack::new((self.id.clone(), "track"))
242                        .checked(checked)
243                        .disabled(self.disabled)
244                        .when(cfg!(test), |this| {
245                            this.debug_selector(|| "switch-bar".into())
246                        })
247                        .w(bg_width)
248                        .h(bg_height)
249                        .rounded(radius)
250                        .flex()
251                        .items_center()
252                        // The thumb inset is a 1px border plus 1px padding,
253                        // not a 2px border: the focus ring tints the border
254                        // solid, and that 1px line is what keeps the ring
255                        // visible on an unchecked track. Its 50% halo alone
256                        // lands within a few values of `switch.background`
257                        // in both default modes.
258                        .border_1()
259                        .border_color(cx.theme().transparent)
260                        .p(inset - px(1.))
261                        .when(!checked, |this| this.bg(unchecked_bg))
262                        .styles(|styles| {
263                            styles
264                                .checked(|style| style.bg(checked_bg))
265                                .disabled(|style| style.bg(disabled_bg))
266                        })
267                        // The ring hugs the track, not the row, so the label
268                        // stays outside it.
269                        .when(is_focused && self.focus_ring_enabled, |this| {
270                            this.focus_ring_style(window, cx)
271                        })
272                        .map(|this| self.tooltip.apply(this))
273                        .child(
274                            // Switch Toggle
275                            SwitchThumb::new(checked)
276                                .rounded(radius)
277                                .size(bar_width)
278                                .left(thumb_x)
279                                .bg(toggle_bg),
280                        ),
281                )
282                .when_some(self.label, |this, label| {
283                    this.child(
284                        div()
285                            .when(cfg!(test), |this| {
286                                this.debug_selector(|| "switch-label".into())
287                            })
288                            .line_height(bg_height)
289                            .child(label)
290                            .map(|this| match self.size {
291                                Size::XSmall | Size::Small => this.text_sm(),
292                                _ => this.text_base(),
293                            }),
294                    )
295                }),
296        )
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use std::{cell::Cell, rc::Rc};
303
304    use gpui::{
305        Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
306        StatefulInteractiveElement as _, TestAppContext, VisualTestContext, point,
307    };
308
309    use super::*;
310
311    #[test]
312    fn an_explicit_accessibility_label_replaces_the_visible_one() {
313        let plain = Switch::new("wifi").label("Wi-Fi");
314        assert_eq!(plain.accessibility_label, None);
315        assert!(matches!(
316            &plain.label,
317            Some(Text::String(label)) if label.as_ref() == "Wi-Fi"
318        ));
319
320        let named = Switch::new("wifi")
321            .label("Wi-Fi")
322            .accessibility_label("Toggle Wi-Fi");
323        assert_eq!(
324            named.accessibility_label.as_deref(),
325            Some("Toggle Wi-Fi"),
326            "an explicit name must win over the visible label"
327        );
328        assert!(
329            matches!(
330                &named.label,
331                Some(Text::String(label)) if label.as_ref() == "Wi-Fi"
332            ),
333            "and must not change what is drawn"
334        );
335    }
336
337    struct SwitchHarness {
338        disabled: bool,
339        toggles: Rc<Cell<usize>>,
340        parent_clicks: Rc<Cell<usize>>,
341    }
342
343    impl Render for SwitchHarness {
344        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
345            let toggles = self.toggles.clone();
346            let parent_clicks = self.parent_clicks.clone();
347            div()
348                .id("switch-parent")
349                .tab_group()
350                .size(px(100.))
351                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
352                .child(Switch::new("switch").disabled(self.disabled).on_click(
353                    move |checked, _, _| {
354                        assert!(*checked);
355                        toggles.set(toggles.get() + 1);
356                    },
357                ))
358        }
359    }
360
361    fn harness(
362        cx: &mut TestAppContext,
363        disabled: bool,
364    ) -> (&mut VisualTestContext, Rc<Cell<usize>>, Rc<Cell<usize>>) {
365        cx.update(crate::init);
366        let toggles = Rc::new(Cell::new(0));
367        let parent_clicks = Rc::new(Cell::new(0));
368        let (_, cx) = cx.add_window_view({
369            let toggles = toggles.clone();
370            let parent_clicks = parent_clicks.clone();
371            move |_, _| SwitchHarness {
372                disabled,
373                toggles,
374                parent_clicks,
375            }
376        });
377        cx.update(|window, cx| window.draw(cx).clear(cx));
378        (cx, toggles, parent_clicks)
379    }
380
381    fn activate_key(cx: &mut VisualTestContext, key: &str) {
382        let keystroke = Keystroke::parse(key).unwrap();
383        cx.simulate_event(KeyDownEvent {
384            keystroke: keystroke.clone(),
385            is_held: false,
386            prefer_character_input: false,
387        });
388        cx.simulate_event(KeyUpEvent { keystroke });
389    }
390
391    #[gpui::test]
392    fn canonical_pointer_activation_fires_once_and_focuses(cx: &mut TestAppContext) {
393        let (cx, toggles, _) = harness(cx, false);
394        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
395
396        assert_eq!(toggles.get(), 1);
397        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
398    }
399
400    #[gpui::test]
401    fn canonical_switch_supports_tab_enter_and_space(cx: &mut TestAppContext) {
402        let (cx, toggles, _) = harness(cx, false);
403        cx.update(|window, cx| window.focus_next(cx));
404        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
405
406        activate_key(cx, "enter");
407        activate_key(cx, "space");
408
409        assert_eq!(toggles.get(), 2);
410    }
411
412    #[gpui::test]
413    fn canonical_disabled_switch_is_inert_and_blocks_parent(cx: &mut TestAppContext) {
414        let (cx, toggles, parent_clicks) = harness(cx, true);
415        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
416
417        assert_eq!(toggles.get(), 0);
418        assert_eq!(parent_clicks.get(), 0);
419        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
420    }
421
422    struct FocusRingHarness {
423        disabled: bool,
424        focus_ring: bool,
425    }
426
427    impl Render for FocusRingHarness {
428        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
429            div().id("switch-parent").tab_group().size(px(100.)).child(
430                Switch::new("switch")
431                    .label("Airplane mode")
432                    .disabled(self.disabled)
433                    .focus_ring(self.focus_ring),
434            )
435        }
436    }
437
438    fn focus_ring_harness(
439        cx: &mut TestAppContext,
440        disabled: bool,
441        focus_ring: bool,
442    ) -> &mut VisualTestContext {
443        cx.update(crate::init);
444        let (_, cx) = cx.add_window_view(move |_, _| FocusRingHarness {
445            disabled,
446            focus_ring,
447        });
448        cx.update(|window, cx| window.draw(cx).clear(cx));
449        cx
450    }
451
452    #[gpui::test]
453    fn focus_ring_hugs_the_track_when_the_switch_is_focused(cx: &mut TestAppContext) {
454        let cx = focus_ring_harness(cx, false, true);
455        assert!(
456            cx.debug_bounds("focus-ring").is_none(),
457            "an unfocused switch draws no ring"
458        );
459
460        cx.update(|window, cx| window.focus_next(cx));
461        cx.update(|window, cx| {
462            assert!(window.focused(cx).is_some());
463            window.draw(cx).clear(cx);
464        });
465
466        let ring = cx
467            .debug_bounds("focus-ring")
468            .expect("a focused switch must draw its focus ring");
469        let bar = cx.debug_bounds("switch-bar").unwrap();
470        let label = cx.debug_bounds("switch-label").unwrap();
471        assert!(ring.contains(&bar.origin), "the ring surrounds the track");
472        assert!(
473            ring.right() < label.origin.x,
474            "the ring hugs the track and leaves the label outside"
475        );
476    }
477
478    #[gpui::test]
479    fn focus_ring_can_be_turned_off(cx: &mut TestAppContext) {
480        let cx = focus_ring_harness(cx, false, false);
481        cx.update(|window, cx| window.focus_next(cx));
482        cx.update(|window, cx| {
483            assert!(window.focused(cx).is_some());
484            window.draw(cx).clear(cx);
485        });
486
487        assert!(
488            cx.debug_bounds("focus-ring").is_none(),
489            "`focus_ring(false)` must not draw a ring"
490        );
491    }
492
493    #[gpui::test]
494    fn disabled_switch_takes_no_focus_and_draws_no_ring(cx: &mut TestAppContext) {
495        let cx = focus_ring_harness(cx, true, true);
496        cx.update(|window, cx| window.focus_next(cx));
497        cx.update(|window, cx| {
498            assert!(window.focused(cx).is_none());
499            window.draw(cx).clear(cx);
500        });
501
502        assert!(cx.debug_bounds("focus-ring").is_none());
503    }
504
505    #[gpui::test]
506    fn label_prepaints_with_the_base_switch_content(cx: &mut TestAppContext) {
507        struct LabelHarness;
508
509        impl Render for LabelHarness {
510            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
511                div()
512                    .debug_selector(|| "labeled-switch".into())
513                    .child(Switch::new("switch").label("Airplane mode"))
514            }
515        }
516
517        cx.update(crate::init);
518        let (_, cx) = cx.add_window_view(|_, _| LabelHarness);
519        cx.update(|window, cx| window.draw(cx).clear(cx));
520
521        let bounds = cx
522            .debug_bounds("labeled-switch")
523            .expect("the complete labeled Switch must participate in prepaint");
524        assert!(bounds.size.width > px(36.));
525        let bar = cx
526            .debug_bounds("switch-bar")
527            .expect("the Switch bar must participate in prepaint");
528        let label = cx
529            .debug_bounds("switch-label")
530            .expect("the Switch label must participate in prepaint");
531        assert_eq!(bar.origin.y, label.origin.y);
532    }
533}