Skip to main content

arc_ui/inputs/
switch.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/switch/switch.tsx` & `switch.module.css`
3//!
4//! P1 Sample Component #1: `switch`
5//!
6//! - Behavior & Accessibility: `gpui_kit::base::Switch` (`Role::Switch`, `aria_toggled`,
7//!   Space/Enter keyboard activation, focus handle, disabled semantics).
8//! - Motion:
9//!   - Thumb `x`: critically damped `glide` spring (`visualDuration: 0.30s, bounce: 0`)
10//!   - Thumb press stretch `width`: `motion.spring.snappy` (`+5px`, anchored on far edge)
11//!   - Programmatic toggle mass stretch `scale_x`: `[1.0, 1.16, 1.0]` over `340ms` (suppressed
12//!     within 250ms of a pointer/Space release and under `reduce_motion`)
13//!   - Track checked crossfade & thumb fill transition: `duration.standard` + `ease.standard`
14//!   - Unchecked hover track darken: `duration.fast` + `ease.standard`
15
16use std::rc::Rc;
17
18use arc_motion::{CubicBezier, arc_spring, arc_transition, is_reduced_motion, motion_now};
19use arc_tokens::{
20    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix,
21};
22use gpui_kit::{
23    App, ElementId, FocusHandle, IntoElement, KeyDownEvent, KeyUpEvent, MouseButton, ParentElement,
24    RenderOnce, SharedString, Styled, Window, base::Switch as BaseSwitch, div, prelude::*, px,
25};
26
27/// Track inner width (36 - 4 padding) minus the 16px thumb (shadcn compact Switch).
28const TRACK_WIDTH: f32 = 36.0;
29const TRACK_HEIGHT: f32 = 20.0;
30const TRACK_PADDING: f32 = 2.0;
31const THUMB_SIZE: f32 = 16.0;
32const TRAVEL: f32 = 16.0;
33/// How far the thumb widens toward the other side while pressed.
34const STRETCH: f32 = 4.0;
35/// Critically damped glide spring from `switch.tsx`.
36const GLIDE_SPRING: SpringSpec = SpringSpec::visual(0.30, 0.0);
37/// Programmatic mass-stretch keyframe duration (`0.34s`).
38const STRETCH_KEYFRAME_DURATION_SECS: f64 = 0.34;
39/// Release suppression window (`250ms`) so a press release does not double-stretch.
40const PRESS_SUPPRESS_SECS: f64 = 0.25;
41
42type ChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
43
44#[derive(Clone, Copy, Debug)]
45struct SwitchInternalState {
46    uncontrolled_checked: bool,
47    pressed: bool,
48    hovered: bool,
49    last_shown: bool,
50    released_at_secs: f64,
51    stretch_started_at_secs: Option<f64>,
52}
53
54impl SwitchInternalState {
55    fn new(initial: bool) -> Self {
56        Self {
57            uncontrolled_checked: initial,
58            pressed: false,
59            hovered: false,
60            last_shown: initial,
61            released_at_secs: f64::NEG_INFINITY,
62            stretch_started_at_secs: None,
63        }
64    }
65}
66
67/// Evaluates Arc's programmatic mass-stretch curve `[1.0, 1.16, 1.0]` with `times: [0, 0.4, 1]`
68/// and `ease: ["easeOut", "easeInOut"]` at elapsed seconds `t`.
69fn eval_programmatic_scale_x(elapsed_secs: f64) -> (f32, bool) {
70    if elapsed_secs <= 0.0 {
71        return (1.0, false);
72    }
73    if elapsed_secs >= STRETCH_KEYFRAME_DURATION_SECS {
74        return (1.0, true);
75    }
76    let u = (elapsed_secs / STRETCH_KEYFRAME_DURATION_SECS) as f32;
77    let scale = if u < 0.4 {
78        let local = u / 0.4;
79        let eased = CubicBezier::new(0.0, 0.0, 0.58, 1.0).sample(local);
80        1.0 + 0.16 * eased
81    } else {
82        let local = (u - 0.4) / 0.6;
83        let eased = CubicBezier::new(0.42, 0.0, 0.58, 1.0).sample(local);
84        1.16 - 0.16 * eased
85    };
86    (scale, false)
87}
88
89/// Arc `Switch` component with spring-gliding thumb, held-press stretch, and controlled/uncontrolled API.
90#[derive(IntoElement)]
91pub struct Switch {
92    id: ElementId,
93    checked: Option<bool>,
94    default_checked: bool,
95    label: Option<SharedString>,
96    accessibility_label: Option<SharedString>,
97    disabled: bool,
98    tab_index: isize,
99    tab_stop: bool,
100    focus_handle: Option<FocusHandle>,
101    on_checked_change: Option<ChangeHandler>,
102}
103
104impl Switch {
105    pub fn new(id: impl Into<ElementId>) -> Self {
106        Self {
107            id: id.into(),
108            checked: None,
109            default_checked: false,
110            label: None,
111            accessibility_label: None,
112            disabled: false,
113            tab_index: 0,
114            tab_stop: true,
115            focus_handle: None,
116            on_checked_change: None,
117        }
118    }
119
120    /// Controlled checked state. Omit to run in uncontrolled mode seeded by [`Self::default_checked`].
121    pub fn checked(mut self, checked: bool) -> Self {
122        self.checked = Some(checked);
123        self
124    }
125
126    /// Initial value when running uncontrolled.
127    pub fn default_checked(mut self, default_checked: bool) -> Self {
128        self.default_checked = default_checked;
129        self
130    }
131
132    /// Visible label shown to the right of the track; also serves as default accessible name.
133    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
134        self.label = Some(label.into());
135        self
136    }
137
138    /// Explicit accessible name overriding `label`.
139    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
140        self.accessibility_label = Some(label.into());
141        self
142    }
143
144    pub fn disabled(mut self, disabled: bool) -> Self {
145        self.disabled = disabled;
146        self
147    }
148
149    pub fn tab_index(mut self, tab_index: isize) -> Self {
150        self.tab_index = tab_index;
151        self
152    }
153
154    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
155        self.tab_stop = tab_stop;
156        self
157    }
158
159    pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
160        self.focus_handle = Some(handle.clone());
161        self
162    }
163
164    pub fn on_checked_change(
165        mut self,
166        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
167    ) -> Self {
168        self.on_checked_change = Some(Rc::new(handler));
169        self
170    }
171}
172
173impl RenderOnce for Switch {
174    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
175        let theme = cx.arc_theme().clone();
176        let colors = theme.colors;
177        let motion = theme.motion;
178        let reduced = is_reduced_motion(cx);
179        let now = motion_now(cx);
180
181        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-switch-state".into());
182        let initial_checked = self.checked.unwrap_or(self.default_checked);
183        let state = window.use_keyed_state(state_id, cx, |_, _| {
184            SwitchInternalState::new(initial_checked)
185        });
186
187        let mut snapshot = *state.read(cx);
188        let on = self.checked.unwrap_or(snapshot.uncontrolled_checked);
189
190        // Trigger brief programmatic mass-stretch when `checked` changes outside a direct press.
191        if snapshot.last_shown != on {
192            let from_press = (now - snapshot.released_at_secs) < PRESS_SUPPRESS_SECS;
193            let start_stretch = !reduced && !from_press;
194            state.update(cx, |s, _| {
195                s.last_shown = on;
196                if start_stretch {
197                    s.stretch_started_at_secs = Some(now);
198                }
199            });
200            snapshot = *state.read(cx);
201        }
202
203        let (scale_x, stretch_done) = match snapshot.stretch_started_at_secs {
204            Some(started) if !reduced => eval_programmatic_scale_x(now - started),
205            _ => (1.0, true),
206        };
207        if !stretch_done {
208            window.request_animation_frame();
209        } else if snapshot.stretch_started_at_secs.is_some() {
210            state.update(cx, |s, _| s.stretch_started_at_secs = None);
211        }
212
213        let extra = if snapshot.pressed && !reduced && !self.disabled {
214            STRETCH
215        } else {
216            0.0
217        };
218        let target_x = if on { TRAVEL - extra } else { 0.0 };
219        let target_width = THUMB_SIZE + extra;
220
221        // Channel IDs follow §4 step 6: `(component_id, "property-name")`.
222        let thumb_x = arc_spring(
223            (self.id.clone(), "thumb-x"),
224            target_x,
225            GLIDE_SPRING,
226            window,
227            cx,
228        );
229        let thumb_width = arc_spring(
230            (self.id.clone(), "thumb-width"),
231            target_width,
232            motion.spring.snappy,
233            window,
234            cx,
235        );
236        let track_on_opacity = arc_transition(
237            (self.id.clone(), "track-on-opacity"),
238            if on { 1.0 } else { 0.0 },
239            motion.duration.standard,
240            motion.ease.standard,
241            window,
242            cx,
243        );
244        let thumb_color_t = arc_transition(
245            (self.id.clone(), "thumb-color-t"),
246            if on { 1.0 } else { 0.0 },
247            motion.duration.standard,
248            motion.ease.standard,
249            window,
250            cx,
251        );
252        let track_hover_t = arc_transition(
253            (self.id.clone(), "track-hover-t"),
254            if snapshot.hovered && !on && !self.disabled {
255                1.0
256            } else {
257                0.0
258            },
259            motion.duration.fast,
260            motion.ease.standard,
261            window,
262            cx,
263        );
264
265        let track_bg = oklab_mix(
266            colors.control_track_hover,
267            colors.control_track,
268            track_hover_t,
269        );
270        let thumb_bg = oklab_mix(colors.control_thumb_on, colors.control_thumb, thumb_color_t);
271
272        // Apply programmatic `scale_x` around the thumb's center without clipping outside track.
273        let drawn_width = thumb_width * scale_x;
274        let max_x = (TRACK_WIDTH - 2.0 * TRACK_PADDING - drawn_width).max(0.0);
275        let drawn_x = (thumb_x - (drawn_width - thumb_width) * 0.5).clamp(0.0, max_x);
276
277        let is_controlled = self.checked.is_some();
278        let disabled = self.disabled;
279        let state_for_change = state.clone();
280        let on_checked_change = self.on_checked_change;
281
282        let state_down = state.clone();
283        let state_up = state.clone();
284        let state_hover = state.clone();
285        let state_key_down = state.clone();
286        let state_key_up = state.clone();
287
288        let aria_label = self.accessibility_label.or_else(|| self.label.clone());
289
290        let mut base = BaseSwitch::new(self.id.clone())
291            .checked(on)
292            .disabled(disabled)
293            .tab_index(self.tab_index)
294            .tab_stop(self.tab_stop)
295            .on_change(move |next, _event, window, cx| {
296                if !is_controlled {
297                    state_for_change.update(cx, |s, _| {
298                        s.uncontrolled_checked = next;
299                    });
300                }
301                if let Some(handler) = &on_checked_change {
302                    handler(&next, window, cx);
303                }
304                window.refresh();
305            });
306
307        if let Some(label) = aria_label {
308            base = base.accessibility_label(label);
309        }
310        if let Some(handle) = &self.focus_handle {
311            base = base.track_focus(handle);
312        }
313
314        base.flex()
315            .flex_row()
316            .self_start()
317            .min_h(ControlHeights::MD)
318            .items_center()
319            .gap(Spacing::S3)
320            .text_size(Typography::TEXT_SM)
321            .text_color(colors.foreground)
322            .when(disabled, |this| this.opacity(0.5))
323            .when(!disabled, |this| this.cursor_pointer())
324            .on_hover(move |hovered, window, cx| {
325                state_hover.update(cx, |s, _| {
326                    s.hovered = *hovered;
327                    if !*hovered {
328                        s.pressed = false;
329                    }
330                });
331                window.refresh();
332            })
333            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
334                if !disabled {
335                    state_down.update(cx, |s, _| s.pressed = true);
336                    window.refresh();
337                }
338            })
339            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
340                let release_now = motion_now(cx);
341                state_up.update(cx, |s, _| {
342                    if s.pressed && !disabled {
343                        s.released_at_secs = release_now;
344                    }
345                    s.pressed = false;
346                });
347                window.refresh();
348            })
349            .on_key_down(move |event: &KeyDownEvent, window, cx| {
350                if !disabled && event.keystroke.key == "space" {
351                    state_key_down.update(cx, |s, _| s.pressed = true);
352                    window.refresh();
353                }
354            })
355            .on_key_up(move |event: &KeyUpEvent, window, cx| {
356                if event.keystroke.key == "space" {
357                    let release_now = motion_now(cx);
358                    state_key_up.update(cx, |s, _| {
359                        if s.pressed && !disabled {
360                            s.released_at_secs = release_now;
361                        }
362                        s.pressed = false;
363                    });
364                    window.refresh();
365                }
366            })
367            .child(
368                // Fixed 42x24 pill track with crossfading active fill layer
369                div()
370                    .relative()
371                    .flex_none()
372                    .w(px(TRACK_WIDTH))
373                    .h(px(TRACK_HEIGHT))
374                    .rounded(Radii::PILL)
375                    .bg(track_bg)
376                    .child(
377                        div()
378                            .absolute()
379                            .inset_0()
380                            .rounded(Radii::PILL)
381                            .bg(colors.control_on)
382                            .opacity(track_on_opacity),
383                    )
384                    .child(
385                        div()
386                            .absolute()
387                            .top(px(TRACK_PADDING))
388                            .left(px(TRACK_PADDING + drawn_x))
389                            .w(px(drawn_width))
390                            .h(px(THUMB_SIZE))
391                            .rounded(Radii::PILL)
392                            .bg(thumb_bg)
393                            .shadow(Shadows::control_thumb(theme.mode)),
394                    ),
395            )
396            .when_some(self.label, |this, label| {
397                this.child(
398                    div()
399                        .line_height(gpui_kit::relative(Typography::LEADING_BODY))
400                        .child(label),
401                )
402            })
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use std::{cell::Cell, rc::Rc, time::Duration};
409
410    use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
411    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
412    use gpui_kit::{Context, Render, Role, TestAppContext, div, test::TestWindowExt as _};
413
414    use super::*;
415
416    struct SwitchHost {
417        controlled: bool,
418        changes: Rc<Cell<usize>>,
419    }
420
421    impl Render for SwitchHost {
422        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
423            let changes = self.changes.clone();
424            div()
425                .flex()
426                .flex_col()
427                .gap(Spacing::S3)
428                .p(Spacing::S4)
429                .child(
430                    Switch::new("controlled-switch")
431                        .label("Wi-Fi")
432                        .checked(self.controlled)
433                        .on_checked_change(cx.listener(move |this, next: &bool, _, cx| {
434                            this.controlled = *next;
435                            changes.set(changes.get() + 1);
436                            cx.notify();
437                        })),
438                )
439                .child(
440                    Switch::new("uncontrolled-switch")
441                        .label("Bluetooth")
442                        .default_checked(true),
443                )
444                .child(
445                    Switch::new("disabled-switch")
446                        .label("Airplane")
447                        .checked(false)
448                        .disabled(true),
449                )
450        }
451    }
452
453    #[gpui_kit::test]
454    fn switch_controlled_uncontrolled_disabled_and_keyboard(cx: &mut TestAppContext) {
455        cx.update(|cx| {
456            gpui_kit::init(cx);
457            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
458        });
459        let changes = Rc::new(Cell::new(0usize));
460        let (view, cx) = cx.add_window_view(|_, _| SwitchHost {
461            controlled: false,
462            changes: changes.clone(),
463        });
464
465        cx.update(|window, cx| {
466            window.render_frame(cx);
467
468            let sw = window.find("controlled-switch");
469            assert_eq!(sw.role(), Some(Role::Switch));
470            assert_eq!(sw.checked(), Some(false));
471
472            // Click toggles controlled switch
473            window.click("controlled-switch", cx);
474            assert_eq!(window.find("controlled-switch").checked(), Some(true));
475            assert_eq!(changes.get(), 1);
476
477            // Space key toggles focused switch
478            window.press("space", cx);
479            assert_eq!(window.find("controlled-switch").checked(), Some(false));
480            assert_eq!(changes.get(), 2);
481
482            // Uncontrolled switch starts checked and toggles itself
483            assert_eq!(window.find("uncontrolled-switch").checked(), Some(true));
484            window.click("uncontrolled-switch", cx);
485            assert_eq!(window.find("uncontrolled-switch").checked(), Some(false));
486
487            // Disabled switch ignores clicks
488            assert_eq!(window.find("disabled-switch").disabled(), Some(true));
489            window.click("disabled-switch", cx);
490            assert_eq!(window.find("disabled-switch").checked(), Some(false));
491        });
492
493        assert!(!view.read_with(cx, |v, _| v.controlled));
494    }
495
496    #[test]
497    fn switch_glide_spring_matches_motion_reference_within_5_percent() {
498        // Motion `glide = { type: "spring", visualDuration: 0.3, bounce: 0 }` over 0..TRAVEL
499        let travel = f64::from(TRAVEL);
500        let solver = SpringSolver::new(GLIDE_SPRING, 0.0, travel, 0.0);
501        let mut actual = CurveTrace::new("switch", "thumb_x");
502        let mut expected = CurveTrace::new("switch", "thumb_x");
503
504        let omega0 = std::f64::consts::TAU / (0.30 * 1.2);
505        for frame in 0..=40 {
506            let t_ms = frame as f64 * 16.0;
507            let t = t_ms / 1000.0;
508            let ref_x = travel - (-omega0 * t).exp() * (travel + omega0 * travel * t);
509            expected.push(t_ms, ref_x);
510            actual.push(t_ms, f64::from(solver.sample(t).value));
511        }
512
513        let err = max_curve_error_pct(&actual, &expected);
514        assert!(err < 5.0, "Switch thumb_x curve error {err:.3}% >= 5%");
515        // Rest-delta snap at 0.5px over 18px travel is <= ~0.6%
516        assert!(
517            err < 1.0,
518            "Expected tight Motion match < 1.0%, got {err:.3}%"
519        );
520    }
521
522    #[gpui_kit::test]
523    fn switch_reduced_motion_snaps_immediately(cx: &mut TestAppContext) {
524        cx.update(|cx| {
525            gpui_kit::init(cx);
526            install_arc_theme(ThemeMode::Dark, Accent::Blue, cx);
527            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
528        });
529        let changes = Rc::new(Cell::new(0usize));
530        let (_view, cx) = cx.add_window_view(|_, _| SwitchHost {
531            controlled: false,
532            changes,
533        });
534
535        cx.update(|window, cx| {
536            window.render_frame(cx);
537            window.click("controlled-switch", cx);
538            assert_eq!(window.find("controlled-switch").checked(), Some(true));
539        });
540        cx.executor().advance_clock(Duration::from_millis(16));
541        cx.update(|window, cx| {
542            window.render_frame(cx);
543            assert_eq!(window.find("controlled-switch").checked(), Some(true));
544        });
545    }
546}