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,
};
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;
const STRETCH: f32 = 4.0;
const GLIDE_SPRING: SpringSpec = SpringSpec::visual(0.30, 0.0);
const STRETCH_KEYFRAME_DURATION_SECS: f64 = 0.34;
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,
}
}
}
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)
}
#[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,
}
}
pub fn checked(mut self, checked: bool) -> Self {
self.checked = Some(checked);
self
}
pub fn default_checked(mut self, default_checked: bool) -> Self {
self.default_checked = default_checked;
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
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);
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;
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);
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(
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));
window.click("controlled-switch", cx);
assert_eq!(window.find("controlled-switch").checked(), Some(true));
assert_eq!(changes.get(), 1);
window.press("space", cx);
assert_eq!(window.find("controlled-switch").checked(), Some(false));
assert_eq!(changes.get(), 2);
assert_eq!(window.find("uncontrolled-switch").checked(), Some(true));
window.click("uncontrolled-switch", cx);
assert_eq!(window.find("uncontrolled-switch").checked(), Some(false));
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() {
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%");
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));
});
}
}