Skip to main content

gpui_component/
switch.rs

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