Skip to main content

gpui_material_components/
selection.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, Axis, BorderStyle, Bounds, ContentMask, Div, ElementId,
5    Entity, FocusHandle, Hsla, InteractiveElement, IntoElement, ParentElement, Path, PathBuilder,
6    PathStyle, Pixels, RenderOnce, Rgba, SharedString, StatefulInteractiveElement, StrokeOptions,
7    Styled, Window, canvas, div, point, prelude::FluentBuilder, px, 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::{
14    InteractionSource, animate, color, move_roving_focus, window_material_theme,
15};
16use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed, StateLayer};
17
18use crate::action::{
19    Change, FeedbackState, feedback_target, ripple_ink, ripple_state, ripple_target,
20};
21
22pub use gpui_base::CheckboxState;
23
24type CheckboxChange = Rc<dyn Fn(CheckboxState, &mut Window, &mut App)>;
25type RadioChange = Rc<dyn Fn(&ElementId, &mut Window, &mut App)>;
26
27fn tone(role: ColorRole, window: &Window, cx: &App) -> Hsla {
28    color(window_material_theme(window, cx).colors.color(role))
29}
30
31fn selection_tone(selected: bool, disabled: bool, window: &Window, cx: &App) -> Hsla {
32    if disabled {
33        tone(ColorRole::OnSurface, window, cx).opacity(0.38)
34    } else if selected {
35        tone(ColorRole::Primary, window, cx)
36    } else {
37        tone(ColorRole::OnSurfaceVariant, window, cx)
38    }
39}
40
41fn row(direction: Direction) -> Div {
42    div()
43        .flex()
44        .items_center()
45        .gap_2()
46        .when(direction == Direction::Rtl, Styled::flex_row_reverse)
47}
48
49fn selection_target(
50    id: SharedString,
51    indicator: impl IntoElement,
52    accent: Hsla,
53    enabled: bool,
54    ripple: Rc<std::cell::RefCell<FeedbackState>>,
55    direction: Direction,
56    reduced_motion: bool,
57) -> Div {
58    let static_pressed = enabled && reduced_motion && ripple.borrow().pressed();
59    div()
60        .size(px(48.))
61        .flex_none()
62        .flex()
63        .items_center()
64        .justify_center()
65        .child(
66            div()
67                .id("selection-indicator")
68                .relative()
69                .size(px(40.))
70                .rounded_full()
71                .flex()
72                .items_center()
73                .justify_center()
74                .when(enabled, |target| {
75                    let hover = id.clone();
76                    target
77                        .when(static_pressed, |target| {
78                            target.bg(accent.opacity(StateLayer::Pressed.opacity()))
79                        })
80                        .when(!static_pressed, |target| {
81                            target.group_hover(hover, |style| {
82                                style.bg(accent.opacity(StateLayer::Hover.opacity()))
83                            })
84                        })
85                        .when(reduced_motion, |target| {
86                            target.group_active(id, |style| {
87                                style.bg(accent.opacity(StateLayer::Pressed.opacity()))
88                            })
89                        })
90                })
91                .child(ripple_ink(
92                    ripple,
93                    accent,
94                    gpui_material_theme::CornerRole::Full.shape(),
95                    direction,
96                ))
97                .child(indicator),
98        )
99}
100
101fn focus_style(color: Hsla) -> impl FnOnce(gpui::StyleRefinement) -> gpui::StyleRefinement {
102    move |style| style.border_color(color)
103}
104
105/// Optional pigments for one checkbox state. Unset fields use the window theme.
106#[derive(Clone, Copy, Debug, Default, PartialEq)]
107pub struct CheckboxStateColors {
108    pub checkmark: Option<Hsla>,
109    pub box_color: Option<Hsla>,
110    pub border: Option<Hsla>,
111}
112
113/// Per-instance checkbox colors. Disabled entries take precedence over error entries.
114#[derive(Clone, Copy, Debug, Default, PartialEq)]
115pub struct CheckboxColors {
116    pub unchecked: CheckboxStateColors,
117    pub checked: CheckboxStateColors,
118    pub indeterminate: CheckboxStateColors,
119    pub error_unchecked: CheckboxStateColors,
120    pub error_checked: CheckboxStateColors,
121    pub error_indeterminate: CheckboxStateColors,
122    pub disabled_unchecked: CheckboxStateColors,
123    pub disabled_checked: CheckboxStateColors,
124    pub disabled_indeterminate: CheckboxStateColors,
125}
126
127impl CheckboxColors {
128    fn for_state(self, state: CheckboxState, error: bool, disabled: bool) -> CheckboxStateColors {
129        use CheckboxState::{Checked, Indeterminate, Unchecked};
130        match (disabled, error, state) {
131            (true, _, Unchecked) => self.disabled_unchecked,
132            (true, _, Checked) => self.disabled_checked,
133            (true, _, Indeterminate) => self.disabled_indeterminate,
134            (false, true, Unchecked) => self.error_unchecked,
135            (false, true, Checked) => self.error_checked,
136            (false, true, Indeterminate) => self.error_indeterminate,
137            (false, false, Unchecked) => self.unchecked,
138            (false, false, Checked) => self.checked,
139            (false, false, Indeterminate) => self.indeterminate,
140        }
141    }
142}
143
144const CHECKBOX_SIZE: f32 = 18.;
145const CHECKBOX_STROKE: f32 = 2.;
146
147/// Controlled Material checkbox. Mixed activation requests Checked.
148#[derive(IntoElement)]
149pub struct Checkbox {
150    id: ElementId,
151    label: SharedString,
152    state: CheckboxState,
153    error: bool,
154    disabled: bool,
155    colors: CheckboxColors,
156    checkmark_stroke: StrokeOptions,
157    outline_stroke: Pixels,
158    interaction_source: Option<Entity<InteractionSource>>,
159    on_change: Option<CheckboxChange>,
160}
161
162impl Checkbox {
163    pub fn new(
164        id: impl Into<ElementId>,
165        label: impl Into<SharedString>,
166        state: CheckboxState,
167    ) -> Self {
168        Self {
169            id: id.into(),
170            label: label.into(),
171            state,
172            error: false,
173            disabled: false,
174            colors: CheckboxColors::default(),
175            checkmark_stroke: StrokeOptions::default().with_line_width(CHECKBOX_STROKE),
176            outline_stroke: px(CHECKBOX_STROKE),
177            interaction_source: None,
178            on_change: None,
179        }
180    }
181
182    pub fn error(mut self, error: bool) -> Self {
183        self.error = error;
184        self
185    }
186
187    pub fn disabled(mut self, disabled: bool) -> Self {
188        self.disabled = disabled;
189        self
190    }
191
192    pub fn colors(mut self, colors: CheckboxColors) -> Self {
193        self.colors = colors;
194        self
195    }
196
197    /// Sets the uniform path stroke used for the checkmark and the mixed mark.
198    pub fn checkmark_stroke(mut self, stroke: StrokeOptions) -> Self {
199        self.checkmark_stroke = stroke;
200        self
201    }
202
203    /// Sets the width of the rounded box outline. Zero omits the outline.
204    pub fn outline_stroke(mut self, width: Pixels) -> Self {
205        self.outline_stroke = width;
206        self
207    }
208
209    /// Reports pointer, keyboard and disabled feedback to a caller-owned source.
210    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
211        self.interaction_source = Some(source.clone());
212        self
213    }
214
215    pub fn on_change(
216        mut self,
217        handler: impl Fn(CheckboxState, &mut Window, &mut App) + 'static,
218    ) -> Self {
219        self.on_change = Some(Rc::new(handler));
220        self
221    }
222
223    /// Derives a parent value from its children. An empty set is unchecked.
224    pub fn aggregate(children: impl IntoIterator<Item = CheckboxState>) -> CheckboxState {
225        let mut children = children.into_iter();
226        let first = children.next().unwrap_or_default();
227        if children.all(|child| child == first) {
228            first
229        } else {
230            CheckboxState::Indeterminate
231        }
232    }
233}
234
235impl RenderOnce for Checkbox {
236    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
237        let checked = self.state != CheckboxState::Unchecked;
238        let accent = if self.error && !self.disabled {
239            tone(ColorRole::Error, window, cx)
240        } else {
241            selection_tone(checked, self.disabled, window, cx)
242        };
243        let on_accent = tone(
244            if self.disabled {
245                ColorRole::Surface
246            } else if self.error {
247                ColorRole::OnError
248            } else {
249                ColorRole::OnPrimary
250            },
251            window,
252            cx,
253        );
254        let motion = window_material_theme(window, cx).motion;
255        let reduced = self.disabled || cx.reduce_motion();
256        let effects = motion.spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
257        let spatial = motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
258        let draw = animate(
259            (self.id.clone(), "check-draw"),
260            f32::from(checked),
261            spatial,
262            window,
263            cx,
264        )
265        .clamp(0., 1.);
266        let mixed = animate(
267            (self.id.clone(), "check-shape"),
268            f32::from(self.state == CheckboxState::Indeterminate),
269            effects,
270            window,
271            cx,
272        )
273        .clamp(0., 1.);
274        let inactive = if self.error && !self.disabled {
275            accent
276        } else {
277            selection_tone(false, self.disabled, window, cx)
278        };
279        let (box_color, border, mark) = if self.colors == CheckboxColors::default() {
280            let fill = animate(
281                (self.id.clone(), "check-fill"),
282                f32::from(checked),
283                effects,
284                window,
285                cx,
286            )
287            .clamp(0., 1.);
288            (
289                accent.opacity(fill),
290                crate::motion::mix(inactive, accent, fill),
291                on_accent,
292            )
293        } else {
294            let colors = self.colors.for_state(self.state, self.error, self.disabled);
295            let mut sample = |name, color| {
296                animate_checkbox_color((self.id.clone(), name).into(), color, effects, window, cx)
297            };
298            (
299                sample(
300                    "check-box-color",
301                    colors
302                        .box_color
303                        .unwrap_or(accent.opacity(f32::from(checked))),
304                ),
305                sample(
306                    "check-border-color",
307                    colors
308                        .border
309                        .unwrap_or(if checked { accent } else { inactive }),
310                ),
311                sample("check-mark-color", colors.checkmark.unwrap_or(on_accent)),
312            )
313        };
314        let mark_stroke = checkbox_mark_stroke(self.checkmark_stroke);
315        let outline = px(checkbox_stroke_width(
316            self.outline_stroke.into(),
317            CHECKBOX_SIZE * 0.5,
318        ));
319        let indicator = canvas(
320            |_, _, _| (),
321            move |bounds, _, window, _| {
322                window.paint_quad(quad(
323                    bounds,
324                    px(2.),
325                    box_color,
326                    outline,
327                    if outline == px(0.) {
328                        gpui::transparent_black()
329                    } else {
330                        border
331                    },
332                    BorderStyle::Solid,
333                ));
334                if let Some(path) = checkbox_mark(bounds, draw, mixed, mark_stroke) {
335                    window.with_content_mask(Some(ContentMask { bounds }), |window| {
336                        window.paint_path(path, mark);
337                    });
338                }
339            },
340        )
341        .size(px(CHECKBOX_SIZE))
342        .flex_none();
343        let direction = window_material_theme(window, cx).layout.direction;
344        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
345        let focus = window
346            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
347            .read(cx)
348            .clone();
349        let tracker = self
350            .interaction_source
351            .as_ref()
352            .map(|source| InteractionSource::track(source, &self.id, window, cx));
353        let track_hover = tracker.is_some();
354        ripple
355            .borrow_mut()
356            .track(!self.disabled, &focus, tracker, window, cx);
357        let group: SharedString = format!("material-checkbox/{}", self.id).into();
358        let label = self.label;
359        let control = BaseCheckbox::new(self.id)
360            .track_focus(&focus)
361            .when(!self.disabled, |control| {
362                if track_hover {
363                    feedback_target(control, ripple.clone(), true, Some(focus.clone()))
364                } else {
365                    ripple_target(control, ripple.clone())
366                }
367            })
368            .state(self.state)
369            .when(self.error, |control| {
370                control.a11y_synthetic_children(|node| {
371                    node.parent_node()
372                        .set_invalid(gpui::accesskit::Invalid::True);
373                })
374            })
375            .disabled(self.disabled)
376            .accessibility_label(label.clone())
377            .group(group.clone())
378            .border_2()
379            .border_color(gpui::transparent_black())
380            .rounded_md()
381            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
382            .child(
383                row(direction)
384                    .child(selection_target(
385                        group,
386                        indicator,
387                        accent,
388                        !self.disabled,
389                        ripple,
390                        direction,
391                        cx.reduce_motion(),
392                    ))
393                    .child(label),
394            );
395        match self.on_change {
396            Some(handler) if !self.disabled => {
397                let change = handler.clone();
398                let next = if self.state == CheckboxState::Checked {
399                    CheckboxState::Unchecked
400                } else {
401                    CheckboxState::Checked
402                };
403                control
404                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
405                        change(next, window, cx)
406                    })
407                    .on_change(move |value, _, window, cx| handler(value, window, cx))
408            }
409            _ => control,
410        }
411    }
412}
413
414fn checkbox_stroke_width(width: f32, max: f32) -> f32 {
415    if width.is_finite() && width >= 0. {
416        width.min(max)
417    } else {
418        CHECKBOX_STROKE
419    }
420}
421
422fn checkbox_mark_stroke(mut stroke: StrokeOptions) -> StrokeOptions {
423    stroke.line_width = checkbox_stroke_width(stroke.line_width, CHECKBOX_SIZE);
424    stroke.variable_line_width = None;
425    if !stroke.miter_limit.is_finite() || stroke.miter_limit < StrokeOptions::MINIMUM_MITER_LIMIT {
426        stroke.miter_limit = StrokeOptions::DEFAULT_MITER_LIMIT;
427    }
428    if !stroke.tolerance.is_finite() || stroke.tolerance <= 0. {
429        stroke.tolerance = StrokeOptions::DEFAULT_TOLERANCE;
430    } else {
431        stroke.tolerance = stroke.tolerance.max(0.01);
432    }
433    stroke
434}
435
436fn checkbox_mark(
437    bounds: Bounds<Pixels>,
438    draw: f32,
439    mixed: f32,
440    stroke: StrokeOptions,
441) -> Option<Path<Pixels>> {
442    if draw == 0. || stroke.line_width == 0. {
443        return None;
444    }
445    let side = bounds.size.width;
446    let start = point(side * 0.2, side * 0.5);
447    let knee = point(side * (0.4 + 0.1 * mixed), side * (0.7 - 0.2 * mixed));
448    let end = point(side * 0.8, side * (0.3 + 0.2 * mixed));
449    let first = f32::from(knee.x - start.x).hypot(f32::from(knee.y - start.y));
450    let second = f32::from(end.x - knee.x).hypot(f32::from(end.y - knee.y));
451    let distance = (first + second) * draw;
452    let mut path = PathBuilder::default().with_style(PathStyle::Stroke(stroke));
453    path.move_to(bounds.origin + start);
454    if distance <= first {
455        path.line_to(bounds.origin + start + (knee - start) * (distance / first));
456    } else {
457        path.line_to(bounds.origin + knee);
458        path.line_to(bounds.origin + knee + (end - knee) * ((distance - first) / second));
459    }
460    path.build().ok()
461}
462
463fn animate_checkbox_color(
464    id: ElementId,
465    color: Hsla,
466    spec: MotionSpec,
467    window: &mut Window,
468    cx: &mut App,
469) -> Hsla {
470    let target = Rgba::from(color);
471    let mut sample = |channel, value| animate((id.clone(), channel), value, spec, window, cx);
472    let current = Rgba {
473        r: sample("red", target.r),
474        g: sample("green", target.g),
475        b: sample("blue", target.b),
476        a: sample("alpha", target.a),
477    };
478    if current == target {
479        color
480    } else {
481        current.into()
482    }
483}
484
485#[cfg(test)]
486mod checkbox_tests {
487    use super::*;
488    use gpui::size;
489
490    #[test]
491    fn checkbox_mark_strokes_fit_and_draw_checked_and_mixed_geometry() {
492        let bounds = Bounds::new(
493            point(px(0.), px(0.)),
494            size(px(CHECKBOX_SIZE), px(CHECKBOX_SIZE)),
495        );
496        let default = checkbox_mark_stroke(StrokeOptions::default().with_line_width(2.));
497        let wide = checkbox_mark_stroke(StrokeOptions::default().with_line_width(4.));
498        let mixed = checkbox_mark(bounds, 1., 1., default).unwrap();
499        assert_eq!(mixed.bounds.size.height, px(2.));
500        let wider_mixed = checkbox_mark(bounds, 1., 1., wide).unwrap();
501        assert_eq!(wider_mixed.bounds.size.height, px(4.));
502        let checked = checkbox_mark(bounds, 1., 0., default).unwrap();
503        let wider_checked = checkbox_mark(bounds, 1., 0., wide).unwrap();
504        assert!(checked.bounds.size.height > mixed.bounds.size.height);
505        assert!(wider_checked.bounds.size.height > checked.bounds.size.height);
506        assert!(checkbox_mark(bounds, 0., 0., wide).is_none());
507        assert!(checkbox_mark(bounds, 1., 0., wide.with_line_width(0.)).is_none());
508        assert_eq!(checkbox_stroke_width(f32::MAX, CHECKBOX_SIZE * 0.5), 9.);
509        for invalid in [-1., f32::NAN, f32::INFINITY] {
510            assert_eq!(checkbox_stroke_width(invalid, CHECKBOX_SIZE * 0.5), 2.);
511            assert_eq!(
512                checkbox_mark_stroke(wide.with_line_width(invalid)).line_width,
513                2.
514            );
515        }
516    }
517}
518
519/// Radio indicator pigments. Omitted values use the current window theme.
520#[derive(Clone, Copy, Debug, Default, PartialEq)]
521pub struct RadioColors {
522    pub selected: Option<Hsla>,
523    pub unselected: Option<Hsla>,
524    pub disabled_selected: Option<Hsla>,
525    pub disabled_unselected: Option<Hsla>,
526}
527
528impl RadioColors {
529    fn resolve(self, selected: bool, disabled: bool, window: &Window, cx: &App) -> Hsla {
530        match (selected, disabled) {
531            (true, false) => self.selected,
532            (false, false) => self.unselected,
533            (true, true) => self.disabled_selected,
534            (false, true) => self.disabled_unselected,
535        }
536        .unwrap_or_else(|| selection_tone(selected, disabled, window, cx))
537    }
538}
539
540/// A radio option. A group owns the tab stop and the caller owns selection.
541#[derive(IntoElement)]
542pub struct Radio {
543    id: ElementId,
544    label: SharedString,
545    selected: bool,
546    disabled: bool,
547    on_select: Option<crate::action::Activate>,
548    colors: RadioColors,
549    interaction_source: Option<Entity<InteractionSource>>,
550}
551
552impl Radio {
553    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
554        Self {
555            id: id.into(),
556            label: label.into(),
557            selected: false,
558            disabled: false,
559            on_select: None,
560            colors: RadioColors::default(),
561            interaction_source: None,
562        }
563    }
564
565    pub fn selected(mut self, selected: bool) -> Self {
566        self.selected = selected;
567        self
568    }
569
570    pub fn disabled(mut self, disabled: bool) -> Self {
571        self.disabled = disabled;
572        self
573    }
574
575    pub fn on_select(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
576        self.on_select = Some(Rc::new(handler));
577        self
578    }
579
580    /// Overrides indicator colors for the four enabled and selected combinations.
581    pub fn colors(mut self, colors: RadioColors) -> Self {
582        self.colors = colors;
583        self
584    }
585
586    /// Observes hover, press, keyboard focus, and disabled state.
587    /// Group options are observed under their rendered, group-scoped IDs.
588    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
589        self.interaction_source = Some(source.clone());
590        self
591    }
592
593    fn render_control(
594        self,
595        focus: Option<&FocusHandle>,
596        position: Option<(usize, usize)>,
597        tab_stop: bool,
598        window: &mut Window,
599        cx: &mut App,
600    ) -> BaseRadio {
601        let motion = window_material_theme(window, cx).motion;
602        let reduced = self.disabled || cx.reduce_motion();
603        let dot = animate(
604            (self.id.clone(), "radio-dot"),
605            f32::from(self.selected),
606            motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced),
607            window,
608            cx,
609        )
610        .clamp(0., 1.);
611        let tint = animate(
612            (self.id.clone(), "radio-color"),
613            f32::from(self.selected),
614            motion.spec(MotionKind::Effects, MotionSpeed::Fast, reduced),
615            window,
616            cx,
617        )
618        .clamp(0., 1.);
619        let accent = crate::motion::mix(
620            self.colors.resolve(false, self.disabled, window, cx),
621            self.colors.resolve(true, self.disabled, window, cx),
622            tint,
623        );
624        let indicator = div()
625            .size(px(20.))
626            .rounded_full()
627            .border_2()
628            .border_color(accent)
629            .flex()
630            .items_center()
631            .justify_center()
632            .child(div().size(px(10. * dot)).rounded_full().bg(accent));
633        let direction = window_material_theme(window, cx).layout.direction;
634        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
635        let focus = focus.cloned().unwrap_or_else(|| {
636            // Match Base's standalone focus ID so changing the source retains focus.
637            window
638                .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
639                .read(cx)
640                .clone()
641        });
642        let tracker = self
643            .interaction_source
644            .as_ref()
645            .map(|source| InteractionSource::track(source, &self.id, window, cx));
646        let observed = tracker.is_some();
647        ripple
648            .borrow_mut()
649            .track(!self.disabled, &focus, tracker, window, cx);
650        let group: SharedString = format!("material-radio/{}", self.id).into();
651        let radio = BaseRadio::new(self.id)
652            .when(!self.disabled, |control| {
653                if observed {
654                    feedback_target(control, ripple.clone(), true, Some(focus.clone()))
655                } else {
656                    ripple_target(control, ripple.clone())
657                }
658            })
659            .checked(self.selected)
660            .disabled(self.disabled)
661            .tab_stop(tab_stop)
662            .accessibility_label(self.label.clone())
663            .group(group.clone())
664            .border_2()
665            .border_color(gpui::transparent_black())
666            .rounded_md()
667            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
668            .child(
669                row(direction)
670                    .child(selection_target(
671                        group,
672                        indicator,
673                        accent,
674                        !self.disabled,
675                        ripple,
676                        direction,
677                        cx.reduce_motion(),
678                    ))
679                    .child(div().min_w_0().truncate().child(self.label)),
680            )
681            .track_focus(&focus)
682            .when_some(position, |radio, (position, size)| {
683                radio.set_position(position, size)
684            });
685        match self.on_select {
686            Some(handler) if !self.disabled => {
687                let select = handler.clone();
688                radio
689                    .when(!self.selected, |radio| {
690                        radio.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
691                            select(window, cx)
692                        })
693                    })
694                    .on_change(move |_, _, window, cx| handler(window, cx))
695            }
696            _ => radio,
697        }
698    }
699}
700
701impl RenderOnce for Radio {
702    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
703        self.render_control(None, None, true, window, cx)
704    }
705}
706
707/// A controlled single-selection group with one Tab stop and directional navigation.
708#[derive(IntoElement)]
709pub struct RadioGroup {
710    id: ElementId,
711    label: SharedString,
712    selected: Option<ElementId>,
713    options: Vec<Radio>,
714    axis: Axis,
715    on_select: Option<RadioChange>,
716}
717
718impl RadioGroup {
719    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
720        Self {
721            id: id.into(),
722            label: label.into(),
723            selected: None,
724            options: Vec::new(),
725            axis: Axis::Vertical,
726            on_select: None,
727        }
728    }
729
730    pub fn selected(mut self, selected: impl Into<ElementId>) -> Self {
731        self.selected = Some(selected.into());
732        self
733    }
734
735    pub fn options(mut self, options: impl IntoIterator<Item = Radio>) -> Self {
736        self.options.extend(options);
737        self
738    }
739
740    pub fn axis(mut self, axis: Axis) -> Self {
741        self.axis = axis;
742        self
743    }
744
745    pub fn on_select(
746        mut self,
747        handler: impl Fn(&ElementId, &mut Window, &mut App) + 'static,
748    ) -> Self {
749        self.on_select = Some(Rc::new(handler));
750        self
751    }
752}
753
754impl RenderOnce for RadioGroup {
755    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
756        let direction = window_material_theme(window, cx).layout.direction;
757        let current = self
758            .options
759            .iter()
760            .position(|item| !item.disabled && Some(&item.id) == self.selected.as_ref());
761        let tab_stop = current.or_else(|| self.options.iter().position(|item| !item.disabled));
762        let size = self.options.len();
763        let focus: Vec<_> = self
764            .options
765            .iter()
766            .map(|item| {
767                let id = ElementId::from((self.id.clone(), "radio-focus"));
768                window.with_id(id, |window| {
769                    window
770                        .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
771                        .read(cx)
772                        .clone()
773                })
774            })
775            .collect();
776        let navigation: Vec<_> = self
777            .options
778            .iter()
779            .zip(&focus)
780            .map(|(item, focus)| (item.id.clone(), focus.clone(), !item.disabled))
781            .collect();
782        let change = self.on_select.clone();
783        let selected = self.selected.clone();
784        let axis = self.axis;
785        let group = BaseRadioGroup::new(self.id.clone())
786            .axis(axis)
787            .aria_label(self.label)
788            .flex()
789            .gap_1()
790            .when(axis == Axis::Vertical, Styled::flex_col)
791            .when(axis == Axis::Horizontal, Styled::flex_wrap)
792            .when(
793                axis == Axis::Horizontal && direction == Direction::Rtl,
794                Styled::flex_row_reverse,
795            )
796            .on_key_down(move |event, window, cx| {
797                let items: Vec<_> = navigation
798                    .iter()
799                    .map(|(_, focus, enabled)| (focus, *enabled))
800                    .collect();
801                let Some(ix) =
802                    move_roving_focus(&items, &event.keystroke.key, axis, direction, window, cx)
803                else {
804                    return;
805                };
806                cx.stop_propagation();
807                if let Some(change) = &change
808                    && Some(&navigation[ix].0) != selected.as_ref()
809                {
810                    change(&navigation[ix].0, window, cx);
811                }
812            });
813
814        group.children(self.options.into_iter().zip(&focus).enumerate().map(
815            |(ix, (mut radio, focus))| {
816                let option_id = radio.id.clone();
817                radio.id = ElementId::from((self.id.clone(), option_id.to_string()));
818                radio.selected = Some(&option_id) == self.selected.as_ref();
819                let handler = self.on_select.clone();
820                radio.on_select = handler.map(|handler| {
821                    let callback: crate::action::Activate =
822                        Rc::new(move |window, cx| handler(&option_id, window, cx));
823                    callback
824                });
825                radio.render_control(
826                    Some(focus),
827                    Some((ix + 1, size)),
828                    Some(ix) == tab_stop,
829                    window,
830                    cx,
831                )
832            },
833        ))
834    }
835}
836
837/// Optional pigments for one switch state. Omitted fields use the window theme.
838#[derive(Clone, Copy, Debug, Default, PartialEq)]
839pub struct SwitchStateColors {
840    pub track: Option<Hsla>,
841    pub border: Option<Hsla>,
842    pub thumb: Option<Hsla>,
843    pub content: Option<Hsla>,
844}
845
846/// Per-instance colors for enabled and disabled switches in either checked state.
847#[derive(Clone, Copy, Debug, Default, PartialEq)]
848pub struct SwitchColors {
849    pub unchecked: SwitchStateColors,
850    pub checked: SwitchStateColors,
851    pub disabled_unchecked: SwitchStateColors,
852    pub disabled_checked: SwitchStateColors,
853}
854
855struct SwitchPalette {
856    track: Hsla,
857    border: Hsla,
858    thumb: Hsla,
859    content: Hsla,
860}
861
862impl SwitchStateColors {
863    fn resolve(self, defaults: SwitchPalette) -> SwitchPalette {
864        SwitchPalette {
865            track: self.track.unwrap_or(defaults.track),
866            border: self.border.unwrap_or(defaults.border),
867            thumb: self.thumb.unwrap_or(defaults.thumb),
868            content: self.content.unwrap_or(defaults.content),
869        }
870    }
871}
872
873impl SwitchColors {
874    fn resolve(
875        self,
876        checked: bool,
877        disabled: bool,
878        tint: f32,
879        window: &Window,
880        cx: &App,
881    ) -> SwitchPalette {
882        use ColorRole::*;
883        let color = |role| tone(role, window, cx);
884        if disabled {
885            // Compose precomposites disabled pigments over the surface color.
886            let muted = |role, opacity| color(Surface).blend(color(role).opacity(opacity));
887            return if checked {
888                self.disabled_checked.resolve(SwitchPalette {
889                    track: muted(OnSurface, 0.12),
890                    border: gpui::transparent_black(),
891                    thumb: color(Surface),
892                    content: muted(OnSurface, 0.38),
893                })
894            } else {
895                self.disabled_unchecked.resolve(SwitchPalette {
896                    track: muted(SurfaceContainerHighest, 0.12),
897                    border: muted(OnSurface, 0.12),
898                    thumb: muted(OnSurface, 0.38),
899                    content: muted(SurfaceContainerHighest, 0.38),
900                })
901            };
902        }
903
904        let unchecked = self.unchecked.resolve(SwitchPalette {
905            track: color(SurfaceContainerHighest),
906            border: color(Outline),
907            thumb: color(Outline),
908            content: color(SurfaceContainerHighest),
909        });
910        let on = self.checked.resolve(SwitchPalette {
911            track: color(Primary),
912            border: unchecked.border.opacity(0.),
913            thumb: color(OnPrimary),
914            content: color(OnPrimaryContainer),
915        });
916        let mix = |off, on| match tint {
917            0. => off,
918            1. => on,
919            _ => crate::motion::mix(off, on, tint),
920        };
921        SwitchPalette {
922            track: mix(unchecked.track, on.track),
923            border: mix(unchecked.border, on.border),
924            thumb: mix(unchecked.thumb, on.thumb),
925            content: if checked {
926                on.content
927            } else {
928                unchecked.content
929            },
930        }
931    }
932}
933
934/// Material switch. The caller owns the checked state and optional thumb content.
935#[derive(IntoElement)]
936pub struct Switch {
937    id: ElementId,
938    label: SharedString,
939    checked: bool,
940    disabled: bool,
941    checked_icon: Option<AnyElement>,
942    unchecked_icon: Option<AnyElement>,
943    thumb_content: Option<AnyElement>,
944    colors: SwitchColors,
945    interaction_source: Option<Entity<InteractionSource>>,
946    on_change: Option<Change>,
947}
948
949impl Switch {
950    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, checked: bool) -> Self {
951        Self {
952            id: id.into(),
953            label: label.into(),
954            checked,
955            disabled: false,
956            checked_icon: None,
957            unchecked_icon: None,
958            thumb_content: None,
959            colors: SwitchColors::default(),
960            interaction_source: None,
961            on_change: None,
962        }
963    }
964
965    pub fn disabled(mut self, disabled: bool) -> Self {
966        self.disabled = disabled;
967        self
968    }
969
970    pub fn checked_icon(mut self, icon: impl IntoElement) -> Self {
971        self.checked_icon = Some(icon.into_any_element());
972        self
973    }
974
975    pub fn unchecked_icon(mut self, icon: impl IntoElement) -> Self {
976        self.unchecked_icon = Some(icon.into_any_element());
977        self
978    }
979
980    /// Supplies decorative content in the centered 16 px thumb slot. The
981    /// element takes precedence over the icon preset for this render.
982    pub fn thumb_content(mut self, content: impl IntoElement) -> Self {
983        self.thumb_content = Some(content.into_any_element());
984        self
985    }
986
987    pub fn colors(mut self, colors: SwitchColors) -> Self {
988        self.colors = colors;
989        self
990    }
991
992    /// Reports presentation state to a caller-owned source.
993    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
994        self.interaction_source = Some(source.clone());
995        self
996    }
997
998    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
999        self.on_change = Some(Rc::new(handler));
1000        self
1001    }
1002}
1003
1004impl RenderOnce for Switch {
1005    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1006        use ColorRole::*;
1007        let theme = window_material_theme(window, cx);
1008        let direction = theme.layout.direction;
1009        let motion = theme.motion.spec(
1010            MotionKind::Spatial,
1011            MotionSpeed::Fast,
1012            self.disabled || cx.reduce_motion(),
1013        );
1014        let tint = animate(
1015            (self.id.clone(), "switch-color"),
1016            f32::from(self.checked),
1017            window_material_theme(window, cx).motion.spec(
1018                MotionKind::Effects,
1019                MotionSpeed::Fast,
1020                self.disabled || cx.reduce_motion(),
1021            ),
1022            window,
1023            cx,
1024        )
1025        .clamp(0., 1.);
1026        let SwitchPalette {
1027            track,
1028            thumb,
1029            border,
1030            content,
1031        } = self
1032            .colors
1033            .resolve(self.checked, self.disabled, tint, window, cx);
1034        let icon = if self.checked {
1035            self.checked_icon
1036        } else {
1037            self.unchecked_icon
1038        };
1039        let decoration = self
1040            .thumb_content
1041            .map(|content| {
1042                div()
1043                    .id("switch-thumb-content")
1044                    .role(gpui::Role::Group)
1045                    .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
1046                    .size(px(16.))
1047                    .overflow_hidden()
1048                    .flex()
1049                    .items_center()
1050                    .justify_center()
1051                    .child(content)
1052                    .into_any_element()
1053            })
1054            .or(icon);
1055        let normal_size = if self.checked || decoration.is_some() {
1056            24.
1057        } else {
1058            16.
1059        };
1060        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
1061        let focus = window
1062            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
1063            .read(cx)
1064            .clone();
1065        let tracker = self
1066            .interaction_source
1067            .as_ref()
1068            .map(|source| InteractionSource::track(source, &self.id, window, cx));
1069        let observes_input = tracker.is_some();
1070        ripple
1071            .borrow_mut()
1072            .track(!self.disabled, &focus, tracker, window, cx);
1073        let active = ripple.borrow().pressed();
1074        let diameter = animate(
1075            (self.id.clone(), "thumb-diameter"),
1076            if active { 28. } else { normal_size },
1077            if active { MotionSpec::Instant } else { motion },
1078            window,
1079            cx,
1080        )
1081        .clamp(16., 28.);
1082        let offset = animate(
1083            (self.id.clone(), "thumb-offset"),
1084            match (active, self.checked) {
1085                (true, false) => 2.,
1086                (true, true) => 22.,
1087                (false, true) => 24.,
1088                (false, false) => (32. - normal_size) / 2.,
1089            },
1090            if active { MotionSpec::Instant } else { motion },
1091            window,
1092            cx,
1093        );
1094        // Offset and diameter are sampled independently, including a reversal on release.
1095        let offset = px(offset.clamp(2., 50. - diameter));
1096        let ink = ripple.clone();
1097        let group: SharedString = format!("material-switch/{}", self.id).into();
1098        let handle = div()
1099            .absolute()
1100            .top_0()
1101            .h_full()
1102            .w(px(diameter))
1103            .flex()
1104            .items_center()
1105            .justify_center()
1106            .when(direction == Direction::Ltr, |handle| handle.left(offset))
1107            .when(direction == Direction::Rtl, |handle| handle.right(offset))
1108            .child(
1109                div()
1110                    .id((self.id.clone(), "switch-thumb"))
1111                    .relative()
1112                    .test_support()
1113                    .size(px(diameter))
1114                    .rounded_full()
1115                    .bg(thumb)
1116                    .text_color(content)
1117                    .text_size(px(16.))
1118                    .flex()
1119                    .items_center()
1120                    .justify_center()
1121                    .child(
1122                        div()
1123                            .id("switch-state-layer")
1124                            .absolute()
1125                            .size(px(40.))
1126                            .left(px((diameter - 40.) / 2.))
1127                            .top(px((diameter - 40.) / 2.))
1128                            .rounded_full()
1129                            .when(!self.disabled, |layer| {
1130                                let accent = tone(
1131                                    if self.checked { Primary } else { OnSurface },
1132                                    window,
1133                                    cx,
1134                                );
1135                                let static_pressed = active && cx.reduce_motion();
1136                                layer
1137                                    .when(static_pressed, |layer| {
1138                                        layer.bg(accent.opacity(StateLayer::Pressed.opacity()))
1139                                    })
1140                                    .when(!static_pressed, |layer| {
1141                                        layer.group_hover(group.clone(), move |style| {
1142                                            style.bg(accent.opacity(StateLayer::Hover.opacity()))
1143                                        })
1144                                    })
1145                                    .when(cx.reduce_motion(), |layer| {
1146                                        layer.group_active(group.clone(), move |style| {
1147                                            style.bg(accent.opacity(StateLayer::Pressed.opacity()))
1148                                        })
1149                                    })
1150                            })
1151                            .child(ripple_ink(
1152                                ink,
1153                                tone(if self.checked { Primary } else { OnSurface }, window, cx),
1154                                gpui_material_theme::CornerRole::Full.shape(),
1155                                direction,
1156                            )),
1157                    )
1158                    .children(decoration),
1159            );
1160        let track = div()
1161            .id((self.id.clone(), "switch-track"))
1162            .test_support()
1163            .relative()
1164            .w(px(52.))
1165            .h(px(32.))
1166            .rounded_full()
1167            .bg(track)
1168            .when(border.a > 0., |track| {
1169                track.child(
1170                    div()
1171                        .absolute()
1172                        .inset_0()
1173                        .rounded_full()
1174                        .border_2()
1175                        .border_color(border),
1176                )
1177            })
1178            .child(handle);
1179        let control = BaseSwitch::new(self.id)
1180            .checked(self.checked)
1181            .disabled(self.disabled)
1182            .track_focus(&focus)
1183            .group(group)
1184            .accessibility_label(self.label.clone())
1185            .when(!self.disabled, |control| {
1186                feedback_target(
1187                    control,
1188                    ripple,
1189                    observes_input,
1190                    observes_input.then_some(focus),
1191                )
1192            })
1193            .border_2()
1194            .border_color(gpui::transparent_black())
1195            .rounded_md()
1196            .focus_visible(focus_style(tone(Secondary, window, cx)))
1197            .child(
1198                row(direction)
1199                    .id("switch-row")
1200                    .min_h(px(48.))
1201                    .px_1()
1202                    .child(track)
1203                    .child(self.label),
1204            );
1205        match self.on_change {
1206            Some(handler) if !self.disabled => {
1207                let change = handler.clone();
1208                control
1209                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
1210                        change(!self.checked, window, cx)
1211                    })
1212                    .on_change(move |checked, _, window, cx| handler(checked, window, cx))
1213            }
1214            _ => control,
1215        }
1216    }
1217}