Skip to main content

gpui_material_components/
selection.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, Axis, BorderStyle, Div, ElementId, FocusHandle, Hsla,
5    InteractiveElement, IntoElement, ParentElement, PathBuilder, RenderOnce, SharedString,
6    StatefulInteractiveElement, Styled, Window, canvas, div, point, prelude::FluentBuilder, px,
7    quad,
8};
9use gpui_base::{
10    Checkbox as BaseCheckbox, Radio as BaseRadio, RadioGroup as BaseRadioGroup,
11    Switch as BaseSwitch, TestSupportExt,
12};
13use gpui_material_foundation::{animate, color, move_roving_focus, window_material_theme};
14use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed, StateLayer};
15
16use crate::action::{Change, FeedbackState, ripple_ink, ripple_state, ripple_target};
17
18pub use gpui_base::CheckboxState;
19
20type CheckboxChange = Rc<dyn Fn(CheckboxState, &mut Window, &mut App)>;
21type RadioChange = Rc<dyn Fn(&ElementId, &mut Window, &mut App)>;
22
23fn tone(role: ColorRole, window: &Window, cx: &App) -> Hsla {
24    color(window_material_theme(window, cx).colors.color(role))
25}
26
27fn selection_tone(selected: bool, disabled: bool, window: &Window, cx: &App) -> Hsla {
28    if disabled {
29        tone(ColorRole::OnSurface, window, cx).opacity(0.38)
30    } else if selected {
31        tone(ColorRole::Primary, window, cx)
32    } else {
33        tone(ColorRole::OnSurfaceVariant, window, cx)
34    }
35}
36
37fn row(direction: Direction) -> Div {
38    div()
39        .flex()
40        .items_center()
41        .gap_2()
42        .when(direction == Direction::Rtl, Styled::flex_row_reverse)
43}
44
45fn selection_target(
46    id: SharedString,
47    indicator: impl IntoElement,
48    accent: Hsla,
49    enabled: bool,
50    ripple: Rc<std::cell::RefCell<FeedbackState>>,
51    direction: Direction,
52    reduced_motion: bool,
53) -> Div {
54    let static_pressed = enabled && reduced_motion && ripple.borrow().pressed();
55    div()
56        .size(px(48.))
57        .flex_none()
58        .flex()
59        .items_center()
60        .justify_center()
61        .child(
62            div()
63                .id("selection-indicator")
64                .relative()
65                .size(px(40.))
66                .rounded_full()
67                .flex()
68                .items_center()
69                .justify_center()
70                .when(enabled, |target| {
71                    let hover = id.clone();
72                    target
73                        .when(static_pressed, |target| {
74                            target.bg(accent.opacity(StateLayer::Pressed.opacity()))
75                        })
76                        .when(!static_pressed, |target| {
77                            target.group_hover(hover, |style| {
78                                style.bg(accent.opacity(StateLayer::Hover.opacity()))
79                            })
80                        })
81                        .when(reduced_motion, |target| {
82                            target.group_active(id, |style| {
83                                style.bg(accent.opacity(StateLayer::Pressed.opacity()))
84                            })
85                        })
86                })
87                .child(ripple_ink(
88                    ripple,
89                    accent,
90                    gpui_material_theme::CornerRole::Full.shape(),
91                    direction,
92                ))
93                .child(indicator),
94        )
95}
96
97fn focus_style(color: Hsla) -> impl FnOnce(gpui::StyleRefinement) -> gpui::StyleRefinement {
98    move |style| style.border_color(color)
99}
100
101/// Controlled Material checkbox. Mixed activation requests Checked.
102#[derive(IntoElement)]
103pub struct Checkbox {
104    id: ElementId,
105    label: SharedString,
106    state: CheckboxState,
107    error: bool,
108    disabled: bool,
109    on_change: Option<CheckboxChange>,
110}
111
112impl Checkbox {
113    pub fn new(
114        id: impl Into<ElementId>,
115        label: impl Into<SharedString>,
116        state: CheckboxState,
117    ) -> Self {
118        Self {
119            id: id.into(),
120            label: label.into(),
121            state,
122            error: false,
123            disabled: false,
124            on_change: None,
125        }
126    }
127
128    pub fn error(mut self, error: bool) -> Self {
129        self.error = error;
130        self
131    }
132
133    pub fn disabled(mut self, disabled: bool) -> Self {
134        self.disabled = disabled;
135        self
136    }
137
138    pub fn on_change(
139        mut self,
140        handler: impl Fn(CheckboxState, &mut Window, &mut App) + 'static,
141    ) -> Self {
142        self.on_change = Some(Rc::new(handler));
143        self
144    }
145
146    /// Derives a parent value from its children. An empty set is unchecked.
147    pub fn aggregate(children: impl IntoIterator<Item = CheckboxState>) -> CheckboxState {
148        let mut children = children.into_iter();
149        let first = children.next().unwrap_or_default();
150        if children.all(|child| child == first) {
151            first
152        } else {
153            CheckboxState::Indeterminate
154        }
155    }
156}
157
158impl RenderOnce for Checkbox {
159    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
160        let checked = self.state != CheckboxState::Unchecked;
161        let accent = if self.error && !self.disabled {
162            tone(ColorRole::Error, window, cx)
163        } else {
164            selection_tone(checked, self.disabled, window, cx)
165        };
166        let on_accent = tone(
167            if self.disabled {
168                ColorRole::Surface
169            } else if self.error {
170                ColorRole::OnError
171            } else {
172                ColorRole::OnPrimary
173            },
174            window,
175            cx,
176        );
177        let motion = window_material_theme(window, cx).motion;
178        let reduced = self.disabled || cx.reduce_motion();
179        let effects = motion.spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
180        let spatial = motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
181        let draw = animate(
182            (self.id.clone(), "check-draw"),
183            f32::from(checked),
184            spatial,
185            window,
186            cx,
187        )
188        .clamp(0., 1.);
189        let mixed = animate(
190            (self.id.clone(), "check-shape"),
191            f32::from(self.state == CheckboxState::Indeterminate),
192            effects,
193            window,
194            cx,
195        )
196        .clamp(0., 1.);
197        let fill = animate(
198            (self.id.clone(), "check-fill"),
199            f32::from(checked),
200            effects,
201            window,
202            cx,
203        )
204        .clamp(0., 1.);
205        let inactive = if self.error && !self.disabled {
206            accent
207        } else {
208            selection_tone(false, self.disabled, window, cx)
209        };
210        let border = crate::motion::mix(inactive, accent, fill);
211        let indicator = canvas(
212            |_, _, _| (),
213            move |bounds, _, window, _| {
214                let stroke = px(2.);
215                // The outline and mark share the outer box coordinates, as in Compose.
216                window.paint_quad(quad(
217                    bounds,
218                    px(2.),
219                    accent.opacity(fill),
220                    stroke,
221                    border,
222                    BorderStyle::Solid,
223                ));
224                if draw == 0. {
225                    return;
226                }
227                let side = bounds.size.width;
228                let start = point(side * 0.2, side * 0.5);
229                let knee = point(side * (0.4 + 0.1 * mixed), side * (0.7 - 0.2 * mixed));
230                let end = point(side * 0.8, side * (0.3 + 0.2 * mixed));
231                let first = f32::from(knee.x - start.x).hypot(f32::from(knee.y - start.y));
232                let second = f32::from(end.x - knee.x).hypot(f32::from(end.y - knee.y));
233                let distance = (first + second) * draw;
234                let mut path = PathBuilder::stroke(stroke);
235                path.move_to(bounds.origin + start);
236                if distance <= first {
237                    path.line_to(bounds.origin + start + (knee - start) * (distance / first));
238                } else {
239                    path.line_to(bounds.origin + knee);
240                    path.line_to(
241                        bounds.origin + knee + (end - knee) * ((distance - first) / second),
242                    );
243                }
244                if let Ok(path) = path.build() {
245                    window.paint_path(path, on_accent);
246                }
247            },
248        )
249        .size(px(18.))
250        .flex_none();
251        let direction = window_material_theme(window, cx).layout.direction;
252        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
253        let group: SharedString = format!("material-checkbox/{}", self.id).into();
254        let label = self.label;
255        let control = BaseCheckbox::new(self.id)
256            .when(!self.disabled, |control| {
257                ripple_target(control, ripple.clone())
258            })
259            .state(self.state)
260            .when(self.error, |control| {
261                control.a11y_synthetic_children(|node| {
262                    node.parent_node()
263                        .set_invalid(gpui::accesskit::Invalid::True);
264                })
265            })
266            .disabled(self.disabled)
267            .accessibility_label(label.clone())
268            .group(group.clone())
269            .border_2()
270            .border_color(gpui::transparent_black())
271            .rounded_md()
272            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
273            .child(
274                row(direction)
275                    .child(selection_target(
276                        group,
277                        indicator,
278                        accent,
279                        !self.disabled,
280                        ripple,
281                        direction,
282                        cx.reduce_motion(),
283                    ))
284                    .child(label),
285            );
286        match self.on_change {
287            Some(handler) if !self.disabled => {
288                let change = handler.clone();
289                let next = if self.state == CheckboxState::Checked {
290                    CheckboxState::Unchecked
291                } else {
292                    CheckboxState::Checked
293                };
294                control
295                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
296                        change(next, window, cx)
297                    })
298                    .on_change(move |value, _, window, cx| handler(value, window, cx))
299            }
300            _ => control,
301        }
302    }
303}
304
305/// A radio option. A group owns the tab stop and the caller owns selection.
306#[derive(IntoElement)]
307pub struct Radio {
308    id: ElementId,
309    label: SharedString,
310    selected: bool,
311    disabled: bool,
312    on_select: Option<crate::action::Activate>,
313}
314
315impl Radio {
316    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
317        Self {
318            id: id.into(),
319            label: label.into(),
320            selected: false,
321            disabled: false,
322            on_select: None,
323        }
324    }
325
326    pub fn selected(mut self, selected: bool) -> Self {
327        self.selected = selected;
328        self
329    }
330
331    pub fn disabled(mut self, disabled: bool) -> Self {
332        self.disabled = disabled;
333        self
334    }
335
336    pub fn on_select(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
337        self.on_select = Some(Rc::new(handler));
338        self
339    }
340
341    fn render_control(
342        self,
343        focus: Option<&FocusHandle>,
344        position: Option<(usize, usize)>,
345        tab_stop: bool,
346        window: &mut Window,
347        cx: &mut App,
348    ) -> BaseRadio {
349        let motion = window_material_theme(window, cx).motion;
350        let reduced = self.disabled || cx.reduce_motion();
351        let dot = animate(
352            (self.id.clone(), "radio-dot"),
353            f32::from(self.selected),
354            motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced),
355            window,
356            cx,
357        )
358        .clamp(0., 1.);
359        let tint = animate(
360            (self.id.clone(), "radio-color"),
361            f32::from(self.selected),
362            motion.spec(MotionKind::Effects, MotionSpeed::Fast, reduced),
363            window,
364            cx,
365        )
366        .clamp(0., 1.);
367        let accent = crate::motion::mix(
368            selection_tone(false, self.disabled, window, cx),
369            selection_tone(true, self.disabled, window, cx),
370            tint,
371        );
372        let indicator = div()
373            .size(px(20.))
374            .rounded_full()
375            .border_2()
376            .border_color(accent)
377            .flex()
378            .items_center()
379            .justify_center()
380            .child(div().size(px(10. * dot)).rounded_full().bg(accent));
381        let direction = window_material_theme(window, cx).layout.direction;
382        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
383        let group: SharedString = format!("material-radio/{}", self.id).into();
384        let radio = BaseRadio::new(self.id)
385            .when(!self.disabled, |control| {
386                ripple_target(control, ripple.clone())
387            })
388            .checked(self.selected)
389            .disabled(self.disabled)
390            .tab_stop(tab_stop)
391            .accessibility_label(self.label.clone())
392            .group(group.clone())
393            .border_2()
394            .border_color(gpui::transparent_black())
395            .rounded_md()
396            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
397            .child(
398                row(direction)
399                    .child(selection_target(
400                        group,
401                        indicator,
402                        accent,
403                        !self.disabled,
404                        ripple,
405                        direction,
406                        cx.reduce_motion(),
407                    ))
408                    .child(div().min_w_0().truncate().child(self.label)),
409            )
410            .when_some(focus, |radio, focus| radio.track_focus(focus))
411            .when_some(position, |radio, (position, size)| {
412                radio.set_position(position, size)
413            });
414        match self.on_select {
415            Some(handler) if !self.disabled => {
416                let select = handler.clone();
417                radio
418                    .when(!self.selected, |radio| {
419                        radio.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
420                            select(window, cx)
421                        })
422                    })
423                    .on_change(move |_, _, window, cx| handler(window, cx))
424            }
425            _ => radio,
426        }
427    }
428}
429
430impl RenderOnce for Radio {
431    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
432        self.render_control(None, None, true, window, cx)
433    }
434}
435
436/// A controlled single-selection group with one Tab stop and directional navigation.
437#[derive(IntoElement)]
438pub struct RadioGroup {
439    id: ElementId,
440    label: SharedString,
441    selected: Option<ElementId>,
442    options: Vec<Radio>,
443    axis: Axis,
444    on_select: Option<RadioChange>,
445}
446
447impl RadioGroup {
448    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
449        Self {
450            id: id.into(),
451            label: label.into(),
452            selected: None,
453            options: Vec::new(),
454            axis: Axis::Vertical,
455            on_select: None,
456        }
457    }
458
459    pub fn selected(mut self, selected: impl Into<ElementId>) -> Self {
460        self.selected = Some(selected.into());
461        self
462    }
463
464    pub fn options(mut self, options: impl IntoIterator<Item = Radio>) -> Self {
465        self.options.extend(options);
466        self
467    }
468
469    pub fn axis(mut self, axis: Axis) -> Self {
470        self.axis = axis;
471        self
472    }
473
474    pub fn on_select(
475        mut self,
476        handler: impl Fn(&ElementId, &mut Window, &mut App) + 'static,
477    ) -> Self {
478        self.on_select = Some(Rc::new(handler));
479        self
480    }
481}
482
483impl RenderOnce for RadioGroup {
484    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
485        let direction = window_material_theme(window, cx).layout.direction;
486        let current = self
487            .options
488            .iter()
489            .position(|item| !item.disabled && Some(&item.id) == self.selected.as_ref());
490        let tab_stop = current.or_else(|| self.options.iter().position(|item| !item.disabled));
491        let size = self.options.len();
492        let focus: Vec<_> = self
493            .options
494            .iter()
495            .map(|item| {
496                let id = ElementId::from((self.id.clone(), "radio-focus"));
497                window.with_id(id, |window| {
498                    window
499                        .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
500                        .read(cx)
501                        .clone()
502                })
503            })
504            .collect();
505        let navigation: Vec<_> = self
506            .options
507            .iter()
508            .zip(&focus)
509            .map(|(item, focus)| (item.id.clone(), focus.clone(), !item.disabled))
510            .collect();
511        let change = self.on_select.clone();
512        let selected = self.selected.clone();
513        let axis = self.axis;
514        let group = BaseRadioGroup::new(self.id.clone())
515            .axis(axis)
516            .aria_label(self.label)
517            .flex()
518            .gap_1()
519            .when(axis == Axis::Vertical, Styled::flex_col)
520            .when(axis == Axis::Horizontal, Styled::flex_wrap)
521            .when(
522                axis == Axis::Horizontal && direction == Direction::Rtl,
523                Styled::flex_row_reverse,
524            )
525            .on_key_down(move |event, window, cx| {
526                let items: Vec<_> = navigation
527                    .iter()
528                    .map(|(_, focus, enabled)| (focus, *enabled))
529                    .collect();
530                let Some(ix) =
531                    move_roving_focus(&items, &event.keystroke.key, axis, direction, window, cx)
532                else {
533                    return;
534                };
535                cx.stop_propagation();
536                if let Some(change) = &change
537                    && Some(&navigation[ix].0) != selected.as_ref()
538                {
539                    change(&navigation[ix].0, window, cx);
540                }
541            });
542
543        group.children(self.options.into_iter().zip(&focus).enumerate().map(
544            |(ix, (mut radio, focus))| {
545                let option_id = radio.id.clone();
546                radio.id = ElementId::from((self.id.clone(), option_id.to_string()));
547                radio.selected = Some(&option_id) == self.selected.as_ref();
548                let handler = self.on_select.clone();
549                radio.on_select = handler.map(|handler| {
550                    let callback: crate::action::Activate =
551                        Rc::new(move |window, cx| handler(&option_id, window, cx));
552                    callback
553                });
554                radio.render_control(
555                    Some(focus),
556                    Some((ix + 1, size)),
557                    Some(ix) == tab_stop,
558                    window,
559                    cx,
560                )
561            },
562        ))
563    }
564}
565
566/// Material switch. The caller owns the checked state and optional thumb icons.
567#[derive(IntoElement)]
568pub struct Switch {
569    id: ElementId,
570    label: SharedString,
571    checked: bool,
572    disabled: bool,
573    checked_icon: Option<AnyElement>,
574    unchecked_icon: Option<AnyElement>,
575    on_change: Option<Change>,
576}
577
578impl Switch {
579    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, checked: bool) -> Self {
580        Self {
581            id: id.into(),
582            label: label.into(),
583            checked,
584            disabled: false,
585            checked_icon: None,
586            unchecked_icon: None,
587            on_change: None,
588        }
589    }
590
591    pub fn disabled(mut self, disabled: bool) -> Self {
592        self.disabled = disabled;
593        self
594    }
595
596    pub fn checked_icon(mut self, icon: impl IntoElement) -> Self {
597        self.checked_icon = Some(icon.into_any_element());
598        self
599    }
600
601    pub fn unchecked_icon(mut self, icon: impl IntoElement) -> Self {
602        self.unchecked_icon = Some(icon.into_any_element());
603        self
604    }
605
606    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
607        self.on_change = Some(Rc::new(handler));
608        self
609    }
610}
611
612impl RenderOnce for Switch {
613    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
614        use ColorRole::*;
615        let theme = window_material_theme(window, cx);
616        let direction = theme.layout.direction;
617        let motion = theme.motion.spec(
618            MotionKind::Spatial,
619            MotionSpeed::Fast,
620            self.disabled || cx.reduce_motion(),
621        );
622        let tint = animate(
623            (self.id.clone(), "switch-color"),
624            f32::from(self.checked),
625            window_material_theme(window, cx).motion.spec(
626                MotionKind::Effects,
627                MotionSpeed::Fast,
628                self.disabled || cx.reduce_motion(),
629            ),
630            window,
631            cx,
632        )
633        .clamp(0., 1.);
634        let outline = tone(Outline, window, cx);
635        // Compose precomposites disabled switch pigments over surface. Keeping
636        // these translucent lets the track bleed through the handle and icon.
637        let disabled_tone = |role, opacity| {
638            tone(Surface, window, cx).blend(tone(role, window, cx).opacity(opacity))
639        };
640        let (track, thumb, outline) = if self.disabled {
641            (
642                disabled_tone(
643                    if self.checked {
644                        OnSurface
645                    } else {
646                        SurfaceContainerHighest
647                    },
648                    0.12,
649                ),
650                if self.checked {
651                    tone(Surface, window, cx)
652                } else {
653                    disabled_tone(OnSurface, 0.38)
654                },
655                if self.checked {
656                    gpui::transparent_black()
657                } else {
658                    disabled_tone(OnSurface, 0.12)
659                },
660            )
661        } else {
662            (
663                crate::motion::mix(
664                    tone(SurfaceContainerHighest, window, cx),
665                    tone(Primary, window, cx),
666                    tint,
667                ),
668                crate::motion::mix(outline, tone(OnPrimary, window, cx), tint),
669                outline.opacity(1. - tint),
670            )
671        };
672        let icon_color = if self.disabled {
673            disabled_tone(
674                if self.checked {
675                    OnSurface
676                } else {
677                    SurfaceContainerHighest
678                },
679                0.38,
680            )
681        } else {
682            tone(
683                if self.checked {
684                    OnPrimaryContainer
685                } else {
686                    SurfaceContainerHighest
687                },
688                window,
689                cx,
690            )
691        };
692        let icon = if self.checked {
693            self.checked_icon
694        } else {
695            self.unchecked_icon
696        };
697        let normal_size = if self.checked || icon.is_some() {
698            24.
699        } else {
700            16.
701        };
702        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
703        let active = ripple.borrow().pressed();
704        let diameter = animate(
705            (self.id.clone(), "thumb-diameter"),
706            if active { 28. } else { normal_size },
707            if active { MotionSpec::Instant } else { motion },
708            window,
709            cx,
710        )
711        .clamp(16., 28.);
712        let offset = animate(
713            (self.id.clone(), "thumb-offset"),
714            match (active, self.checked) {
715                (true, false) => 2.,
716                (true, true) => 22.,
717                (false, true) => 24.,
718                (false, false) => (32. - normal_size) / 2.,
719            },
720            if active { MotionSpec::Instant } else { motion },
721            window,
722            cx,
723        );
724        // Offset and diameter are sampled independently, including a reversal on release.
725        let offset = px(offset.clamp(2., 50. - diameter));
726        let ink = ripple.clone();
727        let group: SharedString = format!("material-switch/{}", self.id).into();
728        let handle = div()
729            .absolute()
730            .top_0()
731            .h_full()
732            .w(px(diameter))
733            .flex()
734            .items_center()
735            .justify_center()
736            .when(direction == Direction::Ltr, |handle| handle.left(offset))
737            .when(direction == Direction::Rtl, |handle| handle.right(offset))
738            .child(
739                div()
740                    .id((self.id.clone(), "switch-thumb"))
741                    .relative()
742                    .test_support()
743                    .size(px(diameter))
744                    .rounded_full()
745                    .bg(thumb)
746                    .text_color(icon_color)
747                    .text_size(px(16.))
748                    .flex()
749                    .items_center()
750                    .justify_center()
751                    .child(
752                        div()
753                            .id("switch-state-layer")
754                            .absolute()
755                            .size(px(40.))
756                            .left(px((diameter - 40.) / 2.))
757                            .top(px((diameter - 40.) / 2.))
758                            .rounded_full()
759                            .when(!self.disabled, |layer| {
760                                let accent = tone(
761                                    if self.checked { Primary } else { OnSurface },
762                                    window,
763                                    cx,
764                                );
765                                let static_pressed = active && cx.reduce_motion();
766                                layer
767                                    .when(static_pressed, |layer| {
768                                        layer.bg(accent.opacity(StateLayer::Pressed.opacity()))
769                                    })
770                                    .when(!static_pressed, |layer| {
771                                        layer.group_hover(group.clone(), move |style| {
772                                            style.bg(accent.opacity(StateLayer::Hover.opacity()))
773                                        })
774                                    })
775                                    .when(cx.reduce_motion(), |layer| {
776                                        layer.group_active(group.clone(), move |style| {
777                                            style.bg(accent.opacity(StateLayer::Pressed.opacity()))
778                                        })
779                                    })
780                            })
781                            .child(ripple_ink(
782                                ink,
783                                tone(if self.checked { Primary } else { OnSurface }, window, cx),
784                                gpui_material_theme::CornerRole::Full.shape(),
785                                direction,
786                            )),
787                    )
788                    .children(icon),
789            );
790        let track = div()
791            .id((self.id.clone(), "switch-track"))
792            .test_support()
793            .relative()
794            .w(px(52.))
795            .h(px(32.))
796            .rounded_full()
797            .bg(track)
798            .when(outline.a > 0., |track| {
799                track.child(
800                    div()
801                        .absolute()
802                        .inset_0()
803                        .rounded_full()
804                        .border_2()
805                        .border_color(outline),
806                )
807            })
808            .child(handle);
809        let control = BaseSwitch::new(self.id)
810            .checked(self.checked)
811            .disabled(self.disabled)
812            .group(group)
813            .accessibility_label(self.label.clone())
814            .when(!self.disabled, |control| ripple_target(control, ripple))
815            .border_2()
816            .border_color(gpui::transparent_black())
817            .rounded_md()
818            .focus_visible(focus_style(tone(Secondary, window, cx)))
819            .child(
820                row(direction)
821                    .id("switch-row")
822                    .min_h(px(48.))
823                    .px_1()
824                    .child(track)
825                    .child(self.label),
826            );
827        match self.on_change {
828            Some(handler) if !self.disabled => {
829                let change = handler.clone();
830                control
831                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
832                        change(!self.checked, window, cx)
833                    })
834                    .on_change(move |checked, _, window, cx| handler(checked, window, cx))
835            }
836            _ => control,
837        }
838    }
839}