arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/switch/switch.tsx` & `switch.module.css`
//!
//! P1 Sample Component #1: `switch`
//!
//! - Behavior & Accessibility: `gpui_kit::base::Switch` (`Role::Switch`, `aria_toggled`,
//!   Space/Enter keyboard activation, focus handle, disabled semantics).
//! - Motion:
//!   - Thumb `x`: critically damped `glide` spring (`visualDuration: 0.30s, bounce: 0`)
//!   - Thumb press stretch `width`: `motion.spring.snappy` (`+5px`, anchored on far edge)
//!   - Programmatic toggle mass stretch `scale_x`: `[1.0, 1.16, 1.0]` over `340ms` (suppressed
//!     within 250ms of a pointer/Space release and under `reduce_motion`)
//!   - Track checked crossfade & thumb fill transition: `duration.standard` + `ease.standard`
//!   - Unchecked hover track darken: `duration.fast` + `ease.standard`

use std::rc::Rc;

use arc_motion::{CubicBezier, arc_spring, arc_transition, is_reduced_motion, motion_now};
use arc_tokens::{
    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix,
};
use gpui_kit::{
    App, ElementId, FocusHandle, IntoElement, KeyDownEvent, KeyUpEvent, MouseButton, ParentElement,
    RenderOnce, SharedString, Styled, Window, base::Switch as BaseSwitch, div, prelude::*, px,
};

/// Track inner width (36 - 4 padding) minus the 16px thumb (shadcn compact Switch).
const TRACK_WIDTH: f32 = 36.0;
const TRACK_HEIGHT: f32 = 20.0;
const TRACK_PADDING: f32 = 2.0;
const THUMB_SIZE: f32 = 16.0;
const TRAVEL: f32 = 16.0;
/// How far the thumb widens toward the other side while pressed.
const STRETCH: f32 = 4.0;
/// Critically damped glide spring from `switch.tsx`.
const GLIDE_SPRING: SpringSpec = SpringSpec::visual(0.30, 0.0);
/// Programmatic mass-stretch keyframe duration (`0.34s`).
const STRETCH_KEYFRAME_DURATION_SECS: f64 = 0.34;
/// Release suppression window (`250ms`) so a press release does not double-stretch.
const PRESS_SUPPRESS_SECS: f64 = 0.25;

type ChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;

#[derive(Clone, Copy, Debug)]
struct SwitchInternalState {
    uncontrolled_checked: bool,
    pressed: bool,
    hovered: bool,
    last_shown: bool,
    released_at_secs: f64,
    stretch_started_at_secs: Option<f64>,
}

impl SwitchInternalState {
    fn new(initial: bool) -> Self {
        Self {
            uncontrolled_checked: initial,
            pressed: false,
            hovered: false,
            last_shown: initial,
            released_at_secs: f64::NEG_INFINITY,
            stretch_started_at_secs: None,
        }
    }
}

/// Evaluates Arc's programmatic mass-stretch curve `[1.0, 1.16, 1.0]` with `times: [0, 0.4, 1]`
/// and `ease: ["easeOut", "easeInOut"]` at elapsed seconds `t`.
fn eval_programmatic_scale_x(elapsed_secs: f64) -> (f32, bool) {
    if elapsed_secs <= 0.0 {
        return (1.0, false);
    }
    if elapsed_secs >= STRETCH_KEYFRAME_DURATION_SECS {
        return (1.0, true);
    }
    let u = (elapsed_secs / STRETCH_KEYFRAME_DURATION_SECS) as f32;
    let scale = if u < 0.4 {
        let local = u / 0.4;
        let eased = CubicBezier::new(0.0, 0.0, 0.58, 1.0).sample(local);
        1.0 + 0.16 * eased
    } else {
        let local = (u - 0.4) / 0.6;
        let eased = CubicBezier::new(0.42, 0.0, 0.58, 1.0).sample(local);
        1.16 - 0.16 * eased
    };
    (scale, false)
}

/// Arc `Switch` component with spring-gliding thumb, held-press stretch, and controlled/uncontrolled API.
#[derive(IntoElement)]
pub struct Switch {
    id: ElementId,
    checked: Option<bool>,
    default_checked: bool,
    label: Option<SharedString>,
    accessibility_label: Option<SharedString>,
    disabled: bool,
    tab_index: isize,
    tab_stop: bool,
    focus_handle: Option<FocusHandle>,
    on_checked_change: Option<ChangeHandler>,
}

impl Switch {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            checked: None,
            default_checked: false,
            label: None,
            accessibility_label: None,
            disabled: false,
            tab_index: 0,
            tab_stop: true,
            focus_handle: None,
            on_checked_change: None,
        }
    }

    /// Controlled checked state. Omit to run in uncontrolled mode seeded by [`Self::default_checked`].
    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = Some(checked);
        self
    }

    /// Initial value when running uncontrolled.
    pub fn default_checked(mut self, default_checked: bool) -> Self {
        self.default_checked = default_checked;
        self
    }

    /// Visible label shown to the right of the track; also serves as default accessible name.
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Explicit accessible name overriding `label`.
    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
        self.accessibility_label = Some(label.into());
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn tab_index(mut self, tab_index: isize) -> Self {
        self.tab_index = tab_index;
        self
    }

    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
        self.tab_stop = tab_stop;
        self
    }

    pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
        self.focus_handle = Some(handle.clone());
        self
    }

    pub fn on_checked_change(
        mut self,
        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_checked_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for Switch {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-switch-state".into());
        let initial_checked = self.checked.unwrap_or(self.default_checked);
        let state = window.use_keyed_state(state_id, cx, |_, _| {
            SwitchInternalState::new(initial_checked)
        });

        let mut snapshot = *state.read(cx);
        let on = self.checked.unwrap_or(snapshot.uncontrolled_checked);

        // Trigger brief programmatic mass-stretch when `checked` changes outside a direct press.
        if snapshot.last_shown != on {
            let from_press = (now - snapshot.released_at_secs) < PRESS_SUPPRESS_SECS;
            let start_stretch = !reduced && !from_press;
            state.update(cx, |s, _| {
                s.last_shown = on;
                if start_stretch {
                    s.stretch_started_at_secs = Some(now);
                }
            });
            snapshot = *state.read(cx);
        }

        let (scale_x, stretch_done) = match snapshot.stretch_started_at_secs {
            Some(started) if !reduced => eval_programmatic_scale_x(now - started),
            _ => (1.0, true),
        };
        if !stretch_done {
            window.request_animation_frame();
        } else if snapshot.stretch_started_at_secs.is_some() {
            state.update(cx, |s, _| s.stretch_started_at_secs = None);
        }

        let extra = if snapshot.pressed && !reduced && !self.disabled {
            STRETCH
        } else {
            0.0
        };
        let target_x = if on { TRAVEL - extra } else { 0.0 };
        let target_width = THUMB_SIZE + extra;

        // Channel IDs follow §4 step 6: `(component_id, "property-name")`.
        let thumb_x = arc_spring(
            (self.id.clone(), "thumb-x"),
            target_x,
            GLIDE_SPRING,
            window,
            cx,
        );
        let thumb_width = arc_spring(
            (self.id.clone(), "thumb-width"),
            target_width,
            motion.spring.snappy,
            window,
            cx,
        );
        let track_on_opacity = arc_transition(
            (self.id.clone(), "track-on-opacity"),
            if on { 1.0 } else { 0.0 },
            motion.duration.standard,
            motion.ease.standard,
            window,
            cx,
        );
        let thumb_color_t = arc_transition(
            (self.id.clone(), "thumb-color-t"),
            if on { 1.0 } else { 0.0 },
            motion.duration.standard,
            motion.ease.standard,
            window,
            cx,
        );
        let track_hover_t = arc_transition(
            (self.id.clone(), "track-hover-t"),
            if snapshot.hovered && !on && !self.disabled {
                1.0
            } else {
                0.0
            },
            motion.duration.fast,
            motion.ease.standard,
            window,
            cx,
        );

        let track_bg = oklab_mix(
            colors.control_track_hover,
            colors.control_track,
            track_hover_t,
        );
        let thumb_bg = oklab_mix(colors.control_thumb_on, colors.control_thumb, thumb_color_t);

        // Apply programmatic `scale_x` around the thumb's center without clipping outside track.
        let drawn_width = thumb_width * scale_x;
        let max_x = (TRACK_WIDTH - 2.0 * TRACK_PADDING - drawn_width).max(0.0);
        let drawn_x = (thumb_x - (drawn_width - thumb_width) * 0.5).clamp(0.0, max_x);

        let is_controlled = self.checked.is_some();
        let disabled = self.disabled;
        let state_for_change = state.clone();
        let on_checked_change = self.on_checked_change;

        let state_down = state.clone();
        let state_up = state.clone();
        let state_hover = state.clone();
        let state_key_down = state.clone();
        let state_key_up = state.clone();

        let aria_label = self.accessibility_label.or_else(|| self.label.clone());

        let mut base = BaseSwitch::new(self.id.clone())
            .checked(on)
            .disabled(disabled)
            .tab_index(self.tab_index)
            .tab_stop(self.tab_stop)
            .on_change(move |next, _event, window, cx| {
                if !is_controlled {
                    state_for_change.update(cx, |s, _| {
                        s.uncontrolled_checked = next;
                    });
                }
                if let Some(handler) = &on_checked_change {
                    handler(&next, window, cx);
                }
                window.refresh();
            });

        if let Some(label) = aria_label {
            base = base.accessibility_label(label);
        }
        if let Some(handle) = &self.focus_handle {
            base = base.track_focus(handle);
        }

        base.flex()
            .flex_row()
            .self_start()
            .min_h(ControlHeights::MD)
            .items_center()
            .gap(Spacing::S3)
            .text_size(Typography::TEXT_SM)
            .text_color(colors.foreground)
            .when(disabled, |this| this.opacity(0.5))
            .when(!disabled, |this| this.cursor_pointer())
            .on_hover(move |hovered, window, cx| {
                state_hover.update(cx, |s, _| {
                    s.hovered = *hovered;
                    if !*hovered {
                        s.pressed = false;
                    }
                });
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                if !disabled {
                    state_down.update(cx, |s, _| s.pressed = true);
                    window.refresh();
                }
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                let release_now = motion_now(cx);
                state_up.update(cx, |s, _| {
                    if s.pressed && !disabled {
                        s.released_at_secs = release_now;
                    }
                    s.pressed = false;
                });
                window.refresh();
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if !disabled && event.keystroke.key == "space" {
                    state_key_down.update(cx, |s, _| s.pressed = true);
                    window.refresh();
                }
            })
            .on_key_up(move |event: &KeyUpEvent, window, cx| {
                if event.keystroke.key == "space" {
                    let release_now = motion_now(cx);
                    state_key_up.update(cx, |s, _| {
                        if s.pressed && !disabled {
                            s.released_at_secs = release_now;
                        }
                        s.pressed = false;
                    });
                    window.refresh();
                }
            })
            .child(
                // Fixed 42x24 pill track with crossfading active fill layer
                div()
                    .relative()
                    .flex_none()
                    .w(px(TRACK_WIDTH))
                    .h(px(TRACK_HEIGHT))
                    .rounded(Radii::PILL)
                    .bg(track_bg)
                    .child(
                        div()
                            .absolute()
                            .inset_0()
                            .rounded(Radii::PILL)
                            .bg(colors.control_on)
                            .opacity(track_on_opacity),
                    )
                    .child(
                        div()
                            .absolute()
                            .top(px(TRACK_PADDING))
                            .left(px(TRACK_PADDING + drawn_x))
                            .w(px(drawn_width))
                            .h(px(THUMB_SIZE))
                            .rounded(Radii::PILL)
                            .bg(thumb_bg)
                            .shadow(Shadows::control_thumb(theme.mode)),
                    ),
            )
            .when_some(self.label, |this, label| {
                this.child(
                    div()
                        .line_height(gpui_kit::relative(Typography::LEADING_BODY))
                        .child(label),
                )
            })
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc, time::Duration};

    use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, Role, TestAppContext, div, test::TestWindowExt as _};

    use super::*;

    struct SwitchHost {
        controlled: bool,
        changes: Rc<Cell<usize>>,
    }

    impl Render for SwitchHost {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let changes = self.changes.clone();
            div()
                .flex()
                .flex_col()
                .gap(Spacing::S3)
                .p(Spacing::S4)
                .child(
                    Switch::new("controlled-switch")
                        .label("Wi-Fi")
                        .checked(self.controlled)
                        .on_checked_change(cx.listener(move |this, next: &bool, _, cx| {
                            this.controlled = *next;
                            changes.set(changes.get() + 1);
                            cx.notify();
                        })),
                )
                .child(
                    Switch::new("uncontrolled-switch")
                        .label("Bluetooth")
                        .default_checked(true),
                )
                .child(
                    Switch::new("disabled-switch")
                        .label("Airplane")
                        .checked(false)
                        .disabled(true),
                )
        }
    }

    #[gpui_kit::test]
    fn switch_controlled_uncontrolled_disabled_and_keyboard(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
        });
        let changes = Rc::new(Cell::new(0usize));
        let (view, cx) = cx.add_window_view(|_, _| SwitchHost {
            controlled: false,
            changes: changes.clone(),
        });

        cx.update(|window, cx| {
            window.render_frame(cx);

            let sw = window.find("controlled-switch");
            assert_eq!(sw.role(), Some(Role::Switch));
            assert_eq!(sw.checked(), Some(false));

            // Click toggles controlled switch
            window.click("controlled-switch", cx);
            assert_eq!(window.find("controlled-switch").checked(), Some(true));
            assert_eq!(changes.get(), 1);

            // Space key toggles focused switch
            window.press("space", cx);
            assert_eq!(window.find("controlled-switch").checked(), Some(false));
            assert_eq!(changes.get(), 2);

            // Uncontrolled switch starts checked and toggles itself
            assert_eq!(window.find("uncontrolled-switch").checked(), Some(true));
            window.click("uncontrolled-switch", cx);
            assert_eq!(window.find("uncontrolled-switch").checked(), Some(false));

            // Disabled switch ignores clicks
            assert_eq!(window.find("disabled-switch").disabled(), Some(true));
            window.click("disabled-switch", cx);
            assert_eq!(window.find("disabled-switch").checked(), Some(false));
        });

        assert!(!view.read_with(cx, |v, _| v.controlled));
    }

    #[test]
    fn switch_glide_spring_matches_motion_reference_within_5_percent() {
        // Motion `glide = { type: "spring", visualDuration: 0.3, bounce: 0 }` over 0..TRAVEL
        let travel = f64::from(TRAVEL);
        let solver = SpringSolver::new(GLIDE_SPRING, 0.0, travel, 0.0);
        let mut actual = CurveTrace::new("switch", "thumb_x");
        let mut expected = CurveTrace::new("switch", "thumb_x");

        let omega0 = std::f64::consts::TAU / (0.30 * 1.2);
        for frame in 0..=40 {
            let t_ms = frame as f64 * 16.0;
            let t = t_ms / 1000.0;
            let ref_x = travel - (-omega0 * t).exp() * (travel + omega0 * travel * t);
            expected.push(t_ms, ref_x);
            actual.push(t_ms, f64::from(solver.sample(t).value));
        }

        let err = max_curve_error_pct(&actual, &expected);
        assert!(err < 5.0, "Switch thumb_x curve error {err:.3}% >= 5%");
        // Rest-delta snap at 0.5px over 18px travel is <= ~0.6%
        assert!(
            err < 1.0,
            "Expected tight Motion match < 1.0%, got {err:.3}%"
        );
    }

    #[gpui_kit::test]
    fn switch_reduced_motion_snaps_immediately(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Dark, Accent::Blue, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });
        let changes = Rc::new(Cell::new(0usize));
        let (_view, cx) = cx.add_window_view(|_, _| SwitchHost {
            controlled: false,
            changes,
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click("controlled-switch", cx);
            assert_eq!(window.find("controlled-switch").checked(), Some(true));
        });
        cx.executor().advance_clock(Duration::from_millis(16));
        cx.update(|window, cx| {
            window.render_frame(cx);
            assert_eq!(window.find("controlled-switch").checked(), Some(true));
        });
    }
}