use std::{cell::RefCell, rc::Rc};
use arc_motion::{
ArcPresence, ArcPresenceConfig, CubicBezier, TransformOrigin, arc_spring,
arc_spring_with_options, arc_transition, is_reduced_motion, motion_now, scaled_bounds,
spring::SpringOptions,
};
use arc_tokens::{
ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
};
use gpui_kit::{
AnyElement, App, BorderStyle, ClickEvent, Corners, Edges, ElementId, FocusHandle, Hsla,
IntoElement, KeyDownEvent, KeyUpEvent, MouseButton, ParentElement, PathBuilder, Pixels,
RenderOnce, SharedString, Styled, Window, assets::IconName, base::Button as BaseButton, canvas,
div, point, prelude::*, px, quad,
};
type ClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ButtonVariant {
#[default]
Primary,
Secondary,
Ghost,
Danger,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ButtonSize {
Sm,
#[default]
Md,
Lg,
}
impl ButtonSize {
pub const fn min_height(self) -> Pixels {
match self {
Self::Sm => ControlHeights::SM,
Self::Md => ControlHeights::MD,
Self::Lg => ControlHeights::LG,
}
}
pub const fn padding_x(self) -> Pixels {
match self {
Self::Sm => px(10.0),
Self::Md => Spacing::S3,
Self::Lg => Spacing::S4,
}
}
}
pub fn adaptive_press_scale(button_width_px: f32) -> f32 {
if button_width_px > 220.0 {
0.985
} else if button_width_px > 0.0 && button_width_px <= 48.0 {
0.96
} else {
0.97
}
}
#[derive(Clone)]
struct ButtonInternalState {
pressed: bool,
hovered: bool,
last_content_key: SharedString,
morph_armed_until_secs: f64,
phase_started_at_secs: f64,
measured_button_width: Rc<RefCell<f32>>,
measured_content_width: Rc<RefCell<f32>>,
has_measured_content: Rc<RefCell<bool>>,
}
impl ButtonInternalState {
fn new(initial_key: SharedString, now: f64) -> Self {
Self {
pressed: false,
hovered: false,
last_content_key: initial_key,
morph_armed_until_secs: f64::NEG_INFINITY,
phase_started_at_secs: now - 10.0,
measured_button_width: Rc::new(RefCell::new(0.0)),
measured_content_width: Rc::new(RefCell::new(0.0)),
has_measured_content: Rc::new(RefCell::new(false)),
}
}
}
#[derive(IntoElement)]
pub struct Button {
id: ElementId,
variant: ButtonVariant,
size: ButtonSize,
square_size: Option<Pixels>,
label: Option<SharedString>,
icon_start: Option<IconName>,
icon_end: Option<IconName>,
custom_child: Option<AnyElement>,
content_key_override: Option<SharedString>,
loading: bool,
disabled: bool,
anchors_layer: bool,
selected: bool,
accessibility_label: Option<SharedString>,
tab_index: isize,
tab_stop: bool,
focus_handle: Option<FocusHandle>,
on_click: Option<ClickHandler>,
}
impl Button {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
variant: ButtonVariant::Primary,
size: ButtonSize::Md,
square_size: None,
label: None,
icon_start: None,
icon_end: None,
custom_child: None,
content_key_override: None,
loading: false,
disabled: false,
anchors_layer: false,
selected: false,
accessibility_label: None,
tab_index: 0,
tab_stop: true,
focus_handle: None,
on_click: None,
}
}
pub fn variant(mut self, variant: ButtonVariant) -> Self {
self.variant = variant;
self
}
pub fn size(mut self, size: ButtonSize) -> Self {
self.size = size;
self
}
pub fn square(mut self, size: Pixels) -> Self {
self.square_size = Some(size);
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon_start = Some(icon);
self
}
pub fn icon_end(mut self, icon: IconName) -> Self {
self.icon_end = Some(icon);
self
}
pub fn child(mut self, element: impl IntoElement) -> Self {
self.custom_child = Some(element.into_any_element());
self
}
pub fn content_key(mut self, key: impl Into<SharedString>) -> Self {
self.content_key_override = Some(key.into());
self
}
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn anchors_layer(mut self, anchors_layer: bool) -> Self {
self.anchors_layer = anchors_layer;
self
}
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
self.accessibility_label = Some(label.into());
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_click(
mut self,
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_click = Some(Rc::new(handler));
self
}
fn derive_content_key(&self) -> SharedString {
if let Some(key) = &self.content_key_override {
return key.clone();
}
let mut out = String::new();
if let Some(icon) = self.icon_start {
out.push_str(&format!("<{icon:?}>"));
}
if let Some(label) = &self.label {
out.push_str(label.as_ref());
}
if let Some(icon) = self.icon_end {
out.push_str(&format!("<{icon:?}>"));
}
SharedString::from(out)
}
}
fn paint_spinner_arc(
center_x: f32,
center_y: f32,
radius: f32,
angle_rad: f32,
color: Hsla,
window: &mut Window,
) {
let steps = 20usize;
let sweep = std::f32::consts::TAU * 0.72;
let mut builder = PathBuilder::stroke(px(1.5));
for i in 0..=steps {
let a = angle_rad + sweep * (i as f32 / steps as f32);
let p = point(
px(center_x + radius * a.cos()),
px(center_y + radius * a.sin()),
);
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
impl RenderOnce for Button {
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 content_key = self.derive_content_key();
let is_icon_only = self.label.as_ref().is_none_or(|s| s.trim().is_empty())
&& self.custom_child.is_none()
&& (self.icon_start.is_some() || self.icon_end.is_some());
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-button-state".into());
let state = window.use_keyed_state(state_id, cx, |_, _| {
ButtonInternalState::new(content_key.clone(), now)
});
{
let prev_key = state.read(cx).last_content_key.clone();
if prev_key != content_key {
state.update(cx, |s, _| {
s.last_content_key = content_key.clone();
s.morph_armed_until_secs = now + 0.7;
s.phase_started_at_secs = now;
});
}
}
let snap = state.read(cx).clone();
let inert = self.disabled || self.loading;
let button_w = *snap.measured_button_width.borrow();
let target_scale = if !inert && !self.anchors_layer && !reduced && snap.pressed {
adaptive_press_scale(button_w)
} else {
1.0
};
let animated_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), "press-scale"),
target_scale,
motion.spring.snappy,
window,
cx,
)
};
let measured_content_w = *snap.measured_content_width.borrow();
let morph_active = !reduced
&& *snap.has_measured_content.borrow()
&& measured_content_w > 0.0
&& now <= snap.morph_armed_until_secs;
let morphed_slot_width = if measured_content_w > 0.0 {
let sample = arc_spring_with_options(
(self.id.clone(), "slot-width"),
measured_content_w,
SpringOptions::new(motion.spring.morph),
window,
cx,
);
if morph_active {
Some(sample.value)
} else {
None
}
} else {
None
};
let phase_elapsed = (now - snap.phase_started_at_secs).max(0.0);
let phase_dur = if reduced {
motion.duration.instant
} else if is_icon_only {
motion.duration.fast
} else {
motion.duration.standard
};
let (phase_opacity, phase_y) = if phase_elapsed < phase_dur.as_secs_f64() {
let t = (phase_elapsed / phase_dur.as_secs_f64()).clamp(0.0, 1.0) as f32;
window.request_animation_frame();
let eased = if reduced {
t
} else {
CubicBezier::from_spec(motion.ease.enter).sample(t)
};
let y_off = if reduced || is_icon_only {
0.0
} else {
2.0 * (1.0 - eased)
};
(eased, y_off)
} else {
(1.0, 0.0)
};
let loader_presence = ArcPresence::new((self.id.clone(), "loader-presence"), self.loading)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.fast,
exit_duration: motion.duration.instant,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let loader_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), "loader-scale"),
if self.loading { 1.0 } else { 0.8 },
motion.spring.snappy,
window,
cx,
)
};
let label_visibility = arc_transition(
(self.id.clone(), "label-vis"),
if self.loading { 0.0 } else { 1.0 },
if reduced {
motion.duration.instant
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let is_hover = !inert && snap.hovered;
let is_press = !inert && snap.pressed;
let (mut bg, border, fg, show_shadow, root_opacity) = match self.variant {
ButtonVariant::Primary => {
if self.disabled {
(
colors.foreground,
colors.foreground,
colors.background,
false,
0.52_f32,
)
} else {
let op = if is_press {
0.84
} else if is_hover {
0.91
} else {
1.0
};
(
colors.foreground,
colors.foreground,
colors.background,
is_hover && !is_press,
op,
)
}
}
ButtonVariant::Secondary => {
if self.disabled {
(
colors.surface_muted,
colors.border,
colors.text_muted,
false,
1.0,
)
} else {
let surface = if is_press || is_hover || self.selected {
colors.surface_muted
} else {
colors.surface
};
(
surface,
colors.border,
colors.foreground,
is_hover && !is_press,
1.0,
)
}
}
ButtonVariant::Ghost => {
if self.disabled {
(
Hsla::transparent_black(),
Hsla::transparent_black(),
colors.text_muted,
false,
1.0,
)
} else if is_press || is_hover || self.selected {
(
colors.surface_muted,
Hsla::transparent_black(),
colors.foreground,
false,
1.0,
)
} else {
(
Hsla::transparent_black(),
Hsla::transparent_black(),
colors.text_secondary,
false,
1.0,
)
}
}
ButtonVariant::Danger => {
if self.disabled {
(
colors.surface_muted,
colors.border,
oklab_mix(colors.danger, colors.surface_muted, 0.55),
false,
1.0,
)
} else if is_press || is_hover {
(
colors.surface_muted,
colors.danger,
colors.danger,
false,
1.0,
)
} else {
(colors.surface, colors.border, colors.danger, false, 1.0)
}
}
};
if self.variant == ButtonVariant::Primary && root_opacity < 1.0 && !self.disabled {
bg.a *= root_opacity;
}
let btn_w_ref = snap.measured_button_width.clone();
let resting_shadows = Shadows::resting(theme.mode);
let backdrop_canvas = canvas(
move |rect, _, _| {
*btn_w_ref.borrow_mut() = f32::from(rect.size.width);
},
move |rect, _, window, _| {
let paint_rect = scaled_bounds(
rect,
animated_scale,
animated_scale,
TransformOrigin::CENTER,
);
let radii = Corners::all(Radii::CONTROL);
if show_shadow {
window.paint_drop_shadows(paint_rect, radii, &resting_shadows);
}
if bg.a > 0.0 || border.a > 0.0 {
window.paint_quad(quad(
paint_rect,
radii,
bg,
Edges::all(px(1.0)),
border,
BorderStyle::Solid,
));
}
},
)
.absolute()
.inset_0();
let content_w_ref = snap.measured_content_width.clone();
let has_measured_ref = snap.has_measured_content.clone();
let content_measure = canvas(
move |rect, window, _| {
let next_w = f32::from(rect.size.width);
let prev_w = *content_w_ref.borrow();
*content_w_ref.borrow_mut() = next_w;
if next_w > 0.0 {
*has_measured_ref.borrow_mut() = true;
}
if (next_w - prev_w).abs() > 0.5 && prev_w > 0.0 {
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let label_content = div()
.relative()
.flex_none()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(Spacing::S2)
.mt(px(phase_y))
.opacity((phase_opacity * label_visibility).clamp(0.0, 1.0))
.child(content_measure)
.when_some(self.icon_start, |this, icon| this.child(icon))
.when_some(self.label.clone(), |this, text| this.child(text))
.when_some(self.custom_child, |this, elem| this.child(elem))
.when_some(self.icon_end, |this, icon| this.child(icon));
let label_slot = div()
.relative()
.flex()
.items_center()
.justify_center()
.when_some(morphed_slot_width, |this, w| {
this.w(px(w)).overflow_hidden()
})
.child(label_content);
let spinner_overlay = if loader_presence.should_render() {
let spinner_op = loader_presence.progress.clamp(0.0, 1.0);
let spinner_color = Hsla {
a: fg.a * spinner_op,
..fg
};
let spin_angle = if reduced {
0.0
} else {
window.request_animation_frame();
((now % 0.7) / 0.7) as f32 * std::f32::consts::TAU
};
let radius = 6.5 * loader_scale.clamp(0.6, 1.05);
Some(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
paint_spinner_arc(
cx,
cy,
radius,
spin_angle,
spinner_color,
window,
);
},
)
.size(Spacing::S4),
),
)
} else {
None
};
let a11y_label = self
.accessibility_label
.clone()
.or_else(|| self.label.clone());
let state_hover = state.clone();
let state_down = state.clone();
let state_up = state.clone();
let state_up_out = state.clone();
let state_kd = state.clone();
let state_ku = state.clone();
let is_loading = self.loading;
let is_disabled = self.disabled;
let on_click = self.on_click;
let mut base = BaseButton::new(self.id.clone())
.disabled(self.disabled)
.tab_index(self.tab_index)
.tab_stop(self.tab_stop);
if let Some(label) = a11y_label {
base = base.accessibility_label(label);
}
if let Some(handle) = &self.focus_handle {
base = base.track_focus(handle);
}
if let Some(handler) = on_click {
base = base.on_click(move |event, window, cx| {
if is_loading || is_disabled {
return;
}
handler(event, window, cx);
});
}
let pad_x = if is_icon_only {
Spacing::S2
} else {
self.size.padding_x()
};
base.relative()
.self_start()
.flex()
.flex_row()
.items_center()
.justify_center()
.min_h(self.size.min_height())
.when(is_icon_only, |this| this.min_w(self.size.min_height()))
.px(pad_x)
.when_some(self.square_size, |this, side| {
this.w(side).h(side).min_w(side).min_h(side).px_0()
})
.rounded(Radii::CONTROL)
.text_size(Typography::TEXT_SM)
.text_color(fg)
.when(
self.disabled && self.variant == ButtonVariant::Primary,
|this| this.opacity(0.52),
)
.when(!inert, |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 inert {
return;
}
state_down.update(cx, |s, _| s.pressed = true);
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
state_up.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
state_up_out.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if inert {
return;
}
if event.keystroke.key == "space" || event.keystroke.key == "enter" {
state_kd.update(cx, |s, _| s.pressed = true);
window.refresh();
}
})
.on_key_up(move |event: &KeyUpEvent, window, cx| {
if event.keystroke.key == "space" || event.keystroke.key == "enter" {
state_ku.update(cx, |s, _| s.pressed = false);
window.refresh();
}
})
.child(backdrop_canvas)
.child(label_slot)
.when_some(spinner_overlay, |this, loader| this.child(loader))
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_motion::{
CurveTrace, ReducedMotionChoice, SpringSolver, max_curve_error_pct, set_reduced_motion,
};
use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct ButtonHost {
clicks: Rc<Cell<usize>>,
loading: bool,
disabled: bool,
label: SharedString,
}
impl Render for ButtonHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let clicks = self.clicks.clone();
div().p(Spacing::S4).child(
Button::new("save-btn")
.variant(ButtonVariant::Primary)
.size(ButtonSize::Md)
.label(self.label.clone())
.loading(self.loading)
.disabled(self.disabled)
.on_click(cx.listener(move |_, _, _, _| {
clicks.set(clicks.get() + 1);
})),
)
}
}
#[gpui_kit::test]
fn button_click_keyboard_loading_swallow_and_disabled(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let clicks = Rc::new(Cell::new(0usize));
let (view, cx) = cx.add_window_view(|_, _| ButtonHost {
clicks: clicks.clone(),
loading: false,
disabled: false,
label: "Save".into(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let btn = window.find_by_label("Save");
assert_eq!(btn.role(), Some(Role::Button));
assert_ne!(btn.disabled(), Some(true));
let center = btn.bounds().center();
window.pointer_down(center, MouseButton::Left, cx);
window.pointer_up(center, MouseButton::Left, cx);
assert_eq!(clicks.get(), 1);
window.press("space", cx);
assert_eq!(clicks.get(), 2);
});
view.update(cx, |v, cx| {
v.loading = true;
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
let btn = window.find_by_label("Save");
assert_ne!(btn.disabled(), Some(true));
let center = btn.bounds().center();
window.pointer_down(center, MouseButton::Left, cx);
window.pointer_up(center, MouseButton::Left, cx);
assert_eq!(clicks.get(), 2);
});
view.update(cx, |v, cx| {
v.loading = false;
v.disabled = true;
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
let btn = window.find_by_label("Save");
assert_eq!(btn.disabled(), Some(true));
let center = btn.bounds().center();
window.pointer_down(center, MouseButton::Left, cx);
window.pointer_up(center, MouseButton::Left, cx);
assert_eq!(clicks.get(), 2);
});
}
#[test]
fn adaptive_press_scale_matches_arc_width_breakpoints() {
assert!((adaptive_press_scale(36.0) - 0.96).abs() < 1e-6);
assert!((adaptive_press_scale(48.0) - 0.96).abs() < 1e-6);
assert!((adaptive_press_scale(120.0) - 0.97).abs() < 1e-6);
assert!((adaptive_press_scale(220.0) - 0.97).abs() < 1e-6);
assert!((adaptive_press_scale(260.0) - 0.985).abs() < 1e-6);
}
#[test]
fn button_width_morph_spring_matches_motion_reference_within_5_percent() {
let spec = ArcMotionTokens::DEFAULT.spring.morph;
let solver = SpringSolver::new(spec, 60.0, 128.0, 0.0);
let omega0 = std::f64::consts::TAU / (0.42 * 1.2);
let mut actual = CurveTrace::new("button", "slot_width");
let mut expected = CurveTrace::new("button", "slot_width");
for frame in 0..=45 {
let t_ms = frame as f64 * 16.0;
let t = t_ms / 1000.0;
let ref_w = 128.0 - (-omega0 * t).exp() * (68.0 + omega0 * 68.0 * t);
expected.push(t_ms, ref_w);
actual.push(t_ms, f64::from(solver.sample(t).value));
}
let err = max_curve_error_pct(&actual, &expected);
assert!(err < 5.0, "Button width morph error {err:.3}% >= 5%");
assert!(
err < 1.0,
"Expected tight morph spring match, got {err:.3}%"
);
}
#[gpui_kit::test]
fn button_reduced_motion_and_label_morph_do_not_crash(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
set_reduced_motion(ReducedMotionChoice::Reduce, cx);
});
let (view, cx) = cx.add_window_view(|_, _| ButtonHost {
clicks: Rc::new(Cell::new(0)),
loading: false,
disabled: false,
label: "Save".into(),
});
cx.update(|window, cx| {
window.render_frame(cx);
});
view.update(cx, |v, cx| {
v.label = "Saved changes".into();
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(
window.find_by_label("Saved changes").role(),
Some(Role::Button)
);
});
}
}