Skip to main content

gpui_material_components/selection/
switch.rs

1use std::cell::RefCell;
2use std::rc::Rc;
3
4use gpui::{
5    AccessibleAction, AnyElement, App, Div, ElementId, Entity, Hsla, InteractiveElement,
6    IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Stateful,
7    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
8};
9use gpui_base::{Switch as BaseSwitch, TestSupportExt};
10use gpui_material_foundation::{InteractionSource, animate, current_material_theme};
11use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed, StateLayer};
12
13use crate::action::{Change, FeedbackState, feedback_target, ripple_ink, ripple_state};
14
15use super::{focus_style, row, tone};
16
17/// Optional pigments for one switch state. Omitted fields use the window theme.
18#[derive(Clone, Copy, Debug, Default, PartialEq)]
19pub struct SwitchStateColors {
20    pub track: Option<Hsla>,
21    pub border: Option<Hsla>,
22    pub thumb: Option<Hsla>,
23    pub content: Option<Hsla>,
24}
25
26/// Per-instance colors for enabled and disabled switches in either checked state.
27#[derive(Clone, Copy, Debug, Default, PartialEq)]
28pub struct SwitchColors {
29    pub unchecked: SwitchStateColors,
30    pub checked: SwitchStateColors,
31    pub disabled_unchecked: SwitchStateColors,
32    pub disabled_checked: SwitchStateColors,
33}
34
35struct SwitchPalette {
36    track: Hsla,
37    border: Hsla,
38    thumb: Hsla,
39    content: Hsla,
40}
41
42impl SwitchStateColors {
43    fn resolve(self, defaults: SwitchPalette) -> SwitchPalette {
44        SwitchPalette {
45            track: self.track.unwrap_or(defaults.track),
46            border: self.border.unwrap_or(defaults.border),
47            thumb: self.thumb.unwrap_or(defaults.thumb),
48            content: self.content.unwrap_or(defaults.content),
49        }
50    }
51}
52
53impl SwitchColors {
54    fn resolve(
55        self,
56        checked: bool,
57        disabled: bool,
58        tint: f32,
59        window: &Window,
60        cx: &App,
61    ) -> SwitchPalette {
62        use ColorRole::*;
63        let color = |role| tone(role, window, cx);
64        if disabled {
65            // Compose precomposites disabled pigments over the surface color.
66            let muted = |role, opacity| color(Surface).blend(color(role).opacity(opacity));
67            return if checked {
68                self.disabled_checked.resolve(SwitchPalette {
69                    track: muted(OnSurface, 0.12),
70                    border: gpui::transparent_black(),
71                    thumb: color(Surface),
72                    content: muted(OnSurface, 0.38),
73                })
74            } else {
75                self.disabled_unchecked.resolve(SwitchPalette {
76                    track: muted(SurfaceContainerHighest, 0.12),
77                    border: muted(OnSurface, 0.12),
78                    thumb: muted(OnSurface, 0.38),
79                    content: muted(SurfaceContainerHighest, 0.38),
80                })
81            };
82        }
83
84        let unchecked = self.unchecked.resolve(SwitchPalette {
85            track: color(SurfaceContainerHighest),
86            border: color(Outline),
87            thumb: color(Outline),
88            content: color(SurfaceContainerHighest),
89        });
90        let on = self.checked.resolve(SwitchPalette {
91            track: color(Primary),
92            border: unchecked.border.opacity(0.),
93            thumb: color(OnPrimary),
94            content: color(OnPrimaryContainer),
95        });
96        let mix = |off, on| match tint {
97            0. => off,
98            1. => on,
99            _ => crate::motion::mix(off, on, tint),
100        };
101        SwitchPalette {
102            track: mix(unchecked.track, on.track),
103            border: mix(unchecked.border, on.border),
104            thumb: mix(unchecked.thumb, on.thumb),
105            content: if checked {
106                on.content
107            } else {
108                unchecked.content
109            },
110        }
111    }
112}
113
114/// Material switch. The caller owns the checked state and optional thumb content.
115#[derive(IntoElement)]
116pub struct Switch {
117    id: ElementId,
118    label: SharedString,
119    checked: bool,
120    disabled: bool,
121    checked_icon: Option<AnyElement>,
122    unchecked_icon: Option<AnyElement>,
123    thumb_content: Option<AnyElement>,
124    colors: SwitchColors,
125    interaction_source: Option<Entity<InteractionSource>>,
126    on_change: Option<Change>,
127}
128
129impl Switch {
130    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, checked: bool) -> Self {
131        Self {
132            id: id.into(),
133            label: label.into(),
134            checked,
135            disabled: false,
136            checked_icon: None,
137            unchecked_icon: None,
138            thumb_content: None,
139            colors: SwitchColors::default(),
140            interaction_source: None,
141            on_change: None,
142        }
143    }
144
145    pub fn disabled(mut self, disabled: bool) -> Self {
146        self.disabled = disabled;
147        self
148    }
149
150    pub fn checked_icon(mut self, icon: impl IntoElement) -> Self {
151        self.checked_icon = Some(icon.into_any_element());
152        self
153    }
154
155    pub fn unchecked_icon(mut self, icon: impl IntoElement) -> Self {
156        self.unchecked_icon = Some(icon.into_any_element());
157        self
158    }
159
160    /// Supplies decorative content in the centered 16 px thumb slot. The
161    /// element takes precedence over the icon preset for this render.
162    pub fn thumb_content(mut self, content: impl IntoElement) -> Self {
163        self.thumb_content = Some(content.into_any_element());
164        self
165    }
166
167    pub fn colors(mut self, colors: SwitchColors) -> Self {
168        self.colors = colors;
169        self
170    }
171
172    /// Reports presentation state to a caller-owned source.
173    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
174        self.interaction_source = Some(source.clone());
175        self
176    }
177
178    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
179        self.on_change = Some(Rc::new(handler));
180        self
181    }
182
183    fn thumb_decoration(&mut self) -> Option<AnyElement> {
184        let icon = if self.checked {
185            self.checked_icon.take()
186        } else {
187            self.unchecked_icon.take()
188        };
189        self.thumb_content
190            .take()
191            .map(|content| {
192                div()
193                    .id("switch-thumb-content")
194                    .role(gpui::Role::Group)
195                    .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
196                    .size(px(16.))
197                    .overflow_hidden()
198                    .flex()
199                    .items_center()
200                    .justify_center()
201                    .child(content)
202                    .into_any_element()
203            })
204            .or(icon)
205    }
206
207    fn thumb_geometry(
208        &self,
209        has_decoration: bool,
210        active: bool,
211        motion: MotionSpec,
212        window: &mut Window,
213        cx: &mut App,
214    ) -> (f32, Pixels) {
215        let normal_size = if self.checked || has_decoration {
216            24.
217        } else {
218            16.
219        };
220        let diameter = animate(
221            (self.id.clone(), "thumb-diameter"),
222            if active { 28. } else { normal_size },
223            if active { MotionSpec::Instant } else { motion },
224            window,
225            cx,
226        )
227        .clamp(16., 28.);
228        let offset = animate(
229            (self.id.clone(), "thumb-offset"),
230            match (active, self.checked) {
231                (true, false) => 2.,
232                (true, true) => 22.,
233                (false, true) => 24.,
234                (false, false) => (32. - normal_size) / 2.,
235            },
236            if active { MotionSpec::Instant } else { motion },
237            window,
238            cx,
239        );
240        // Offset and diameter are sampled independently, including a reversal on release.
241        (diameter, px(offset.clamp(2., 50. - diameter)))
242    }
243}
244
245#[allow(clippy::too_many_arguments)]
246fn render_state_layer(
247    diameter: f32,
248    checked: bool,
249    disabled: bool,
250    active: bool,
251    group: &SharedString,
252    ink: Rc<RefCell<FeedbackState>>,
253    direction: Direction,
254    window: &Window,
255    cx: &App,
256) -> Stateful<Div> {
257    use ColorRole::*;
258    let accent = tone(if checked { Primary } else { OnSurface }, window, cx);
259    div()
260        .id("switch-state-layer")
261        .absolute()
262        .size(px(40.))
263        .left(px((diameter - 40.) / 2.))
264        .top(px((diameter - 40.) / 2.))
265        .rounded_full()
266        .when(!disabled, |layer| {
267            let static_pressed = active && cx.reduce_motion();
268            layer
269                .when(static_pressed, |layer| {
270                    layer.bg(accent.opacity(StateLayer::Pressed.opacity()))
271                })
272                .when(!static_pressed, |layer| {
273                    layer.group_hover(group.clone(), move |style| {
274                        style.bg(accent.opacity(StateLayer::Hover.opacity()))
275                    })
276                })
277                .when(cx.reduce_motion(), |layer| {
278                    layer.group_active(group.clone(), move |style| {
279                        style.bg(accent.opacity(StateLayer::Pressed.opacity()))
280                    })
281                })
282        })
283        .child(ripple_ink(
284            ink,
285            accent,
286            gpui_material_theme::CornerRole::Full.shape(),
287            direction,
288        ))
289}
290
291#[allow(clippy::too_many_arguments)]
292fn render_track(
293    id: &ElementId,
294    palette: SwitchPalette,
295    diameter: f32,
296    offset: Pixels,
297    direction: Direction,
298    state_layer: Stateful<Div>,
299    decoration: Option<AnyElement>,
300) -> impl IntoElement + use<> {
301    let handle = div()
302        .absolute()
303        .top_0()
304        .h_full()
305        .w(px(diameter))
306        .flex()
307        .items_center()
308        .justify_center()
309        .when(direction == Direction::Ltr, |handle| handle.left(offset))
310        .when(direction == Direction::Rtl, |handle| handle.right(offset))
311        .child(
312            div()
313                .id((id.clone(), "switch-thumb"))
314                .relative()
315                .test_support()
316                .size(px(diameter))
317                .rounded_full()
318                .bg(palette.thumb)
319                .text_color(palette.content)
320                .text_size(px(16.))
321                .flex()
322                .items_center()
323                .justify_center()
324                .child(state_layer)
325                .children(decoration),
326        );
327    div()
328        .id((id.clone(), "switch-track"))
329        .test_support()
330        .relative()
331        .w(px(52.))
332        .h(px(32.))
333        .rounded_full()
334        .bg(palette.track)
335        .when(palette.border.a > 0., |track| {
336            track.child(
337                div()
338                    .absolute()
339                    .inset_0()
340                    .rounded_full()
341                    .border_2()
342                    .border_color(palette.border),
343            )
344        })
345        .child(handle)
346}
347
348impl RenderOnce for Switch {
349    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
350        let theme = current_material_theme(window, cx);
351        let direction = theme.layout.direction;
352        let reduced = self.disabled || cx.reduce_motion();
353        let motion = theme
354            .motion
355            .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
356        let effects = theme
357            .motion
358            .spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
359        let tint = animate(
360            (self.id.clone(), "switch-color"),
361            f32::from(self.checked),
362            effects,
363            window,
364            cx,
365        )
366        .clamp(0., 1.);
367        let palette = self
368            .colors
369            .resolve(self.checked, self.disabled, tint, window, cx);
370        let decoration = self.thumb_decoration();
371        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
372        let focus = window
373            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
374            .read(cx)
375            .clone();
376        let tracker = self
377            .interaction_source
378            .as_ref()
379            .map(|source| InteractionSource::track(source, &self.id, window, cx));
380        let observes_input = tracker.is_some();
381        ripple
382            .borrow_mut()
383            .track(!self.disabled, &focus, tracker, window, cx);
384        let active = ripple.borrow().pressed();
385        let (diameter, offset) =
386            self.thumb_geometry(decoration.is_some(), active, motion, window, cx);
387        let group: SharedString = format!("material-switch/{}", self.id).into();
388        let state_layer = render_state_layer(
389            diameter,
390            self.checked,
391            self.disabled,
392            active,
393            &group,
394            ripple.clone(),
395            direction,
396            window,
397            cx,
398        );
399        let track = render_track(
400            &self.id,
401            palette,
402            diameter,
403            offset,
404            direction,
405            state_layer,
406            decoration,
407        );
408        let control = BaseSwitch::new(self.id)
409            .checked(self.checked)
410            .disabled(self.disabled)
411            .track_focus(&focus)
412            .group(group)
413            .accessibility_label(self.label.clone())
414            .when(!self.disabled, |control| {
415                feedback_target(
416                    control,
417                    ripple,
418                    observes_input,
419                    observes_input.then_some(focus),
420                )
421            })
422            .border_2()
423            .border_color(gpui::transparent_black())
424            .rounded_md()
425            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
426            .child(
427                row(direction)
428                    .id("switch-row")
429                    .min_h(px(48.))
430                    .px_1()
431                    .child(track)
432                    .child(self.label),
433            );
434        match self.on_change {
435            Some(handler) if !self.disabled => {
436                let change = handler.clone();
437                control
438                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
439                        change(!self.checked, window, cx)
440                    })
441                    .on_change(move |checked, _, window, cx| handler(checked, window, cx))
442            }
443            _ => control,
444        }
445    }
446}