use std::{cell::RefCell, rc::Rc, time::Duration};
use arc_motion::{
BlurFallback, CubicBezier, PathPoint, PolylinePath, TransformOrigin, arc_spring,
arc_spring_with_options, is_reduced_motion, motion_now, scaled_bounds, spring::SpringOptions,
};
use arc_tokens::{
ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography,
};
use gpui_kit::{
App, BorderStyle, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
KeyUpEvent, MouseButton, ParentElement, PathBuilder, RenderOnce, SharedString, Styled, Window,
assets::IconName, base::Button as BaseButton, canvas, div, point, prelude::*, px, quad,
};
type ActionHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
const WIDTH_MORPH_SPRING: SpringSpec = SpringSpec::visual(0.24, 0.0);
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ActionButtonState {
#[default]
Idle,
Pending,
Success,
}
#[derive(Clone)]
struct ActionButtonInternal {
uncontrolled_state: ActionButtonState,
last_state: ActionButtonState,
state_changed_at_secs: f64,
pending_finish_at_secs: Option<f64>,
reset_at_secs: Option<f64>,
pressed: bool,
hovered: bool,
last_label: SharedString,
morph_armed_until_secs: f64,
label_changed_at_secs: f64,
measured_button_width: Rc<RefCell<f32>>,
measured_label_width: Rc<RefCell<f32>>,
has_measured_label: Rc<RefCell<bool>>,
}
impl ActionButtonInternal {
fn new(initial_state: ActionButtonState, initial_label: SharedString, now: f64) -> Self {
Self {
uncontrolled_state: initial_state,
last_state: initial_state,
state_changed_at_secs: now - 10.0,
pending_finish_at_secs: None,
reset_at_secs: None,
pressed: false,
hovered: false,
last_label: initial_label,
morph_armed_until_secs: f64::NEG_INFINITY,
label_changed_at_secs: now - 10.0,
measured_button_width: Rc::new(RefCell::new(0.0)),
measured_label_width: Rc::new(RefCell::new(0.0)),
has_measured_label: Rc::new(RefCell::new(false)),
}
}
}
#[derive(IntoElement)]
pub struct ActionButton {
id: ElementId,
label: SharedString,
pending_label: SharedString,
success_label: SharedString,
state: Option<ActionButtonState>,
reset_after: Duration,
pending_duration: Duration,
disabled: bool,
accessibility_label: Option<SharedString>,
focus_handle: Option<FocusHandle>,
on_action: Option<ActionHandler>,
}
impl ActionButton {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
pending_label: "Saving".into(),
success_label: "Saved".into(),
state: None,
reset_after: Duration::from_millis(2400),
pending_duration: Duration::ZERO,
disabled: false,
accessibility_label: None,
focus_handle: None,
on_action: None,
}
}
pub fn pending_label(mut self, label: impl Into<SharedString>) -> Self {
self.pending_label = label.into();
self
}
pub fn success_label(mut self, label: impl Into<SharedString>) -> Self {
self.success_label = label.into();
self
}
pub fn state(mut self, state: ActionButtonState) -> Self {
self.state = Some(state);
self
}
pub fn reset_after(mut self, duration: Duration) -> Self {
self.reset_after = duration;
self
}
pub fn pending_duration(mut self, duration: Duration) -> Self {
self.pending_duration = duration;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
self.accessibility_label = Some(label.into());
self
}
pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
self.focus_handle = Some(handle.clone());
self
}
pub fn on_action(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.on_action = Some(Rc::new(handler));
self
}
}
fn paint_spinner(cx: f32, cy: 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(cx + radius * a.cos()), px(cy + 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);
}
}
fn checkmark_polyline() -> PolylinePath {
let s = 17.0 / 24.0;
PolylinePath::new(vec![
PathPoint::new(4.0 * s, 12.0 * s),
PathPoint::new(9.0 * s, 17.0 * s),
PathPoint::new(20.0 * s, 6.0 * s),
])
}
impl RenderOnce for ActionButton {
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 is_controlled = self.state.is_some();
let initial_state = self.state.unwrap_or(ActionButtonState::Idle);
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-action-button-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| {
ActionButtonInternal::new(initial_state, self.label.clone(), now)
});
if !is_controlled {
let snap = internal.read(cx).clone();
let mut keep_ticking = false;
if let Some(done_at) = snap.pending_finish_at_secs {
if now >= done_at {
let reset_secs = self.reset_after.as_secs_f64();
internal.update(cx, |s, _| {
s.pending_finish_at_secs = None;
s.uncontrolled_state = ActionButtonState::Success;
s.reset_at_secs = if reset_secs > 0.0 {
Some(now + reset_secs)
} else {
None
};
});
} else {
keep_ticking = true;
}
}
let snap2 = internal.read(cx).clone();
if let Some(reset_at) = snap2.reset_at_secs {
if now >= reset_at {
internal.update(cx, |s, _| {
s.reset_at_secs = None;
s.uncontrolled_state = ActionButtonState::Idle;
});
} else {
keep_ticking = true;
}
}
if keep_ticking {
window.request_animation_frame();
}
}
let current_state = self
.state
.unwrap_or_else(|| internal.read(cx).uncontrolled_state);
let current_text = match current_state {
ActionButtonState::Idle => self.label.clone(),
ActionButtonState::Pending => self.pending_label.clone(),
ActionButtonState::Success => self.success_label.clone(),
};
{
let snap = internal.read(cx).clone();
if snap.last_state != current_state || snap.last_label != current_text {
internal.update(cx, |s, _| {
if s.last_state != current_state {
s.last_state = current_state;
s.state_changed_at_secs = now;
}
if s.last_label != current_text {
s.last_label = current_text.clone();
s.morph_armed_until_secs = now + 0.7;
s.label_changed_at_secs = now;
}
});
}
}
let snap = internal.read(cx).clone();
let pending = current_state == ActionButtonState::Pending;
let inert = self.disabled || pending;
let btn_w = *snap.measured_button_width.borrow();
let target_scale = if !inert && !reduced && snap.pressed {
if btn_w > 220.0 { 0.985 } else { 0.97 }
} 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_label_w = *snap.measured_label_width.borrow();
let morph_active = !reduced
&& *snap.has_measured_label.borrow()
&& measured_label_w > 0.0
&& now <= snap.morph_armed_until_secs;
let morphed_label_w = if measured_label_w > 0.0 {
let sample = arc_spring_with_options(
(self.id.clone(), "label-width"),
measured_label_w,
SpringOptions::new(WIDTH_MORPH_SPRING),
window,
cx,
);
if morph_active {
Some(sample.value)
} else {
None
}
} else {
None
};
let label_elapsed = (now - snap.label_changed_at_secs).max(0.0);
let label_dur = if reduced {
motion.duration.instant.as_secs_f64()
} else {
0.16
};
let (label_op, label_y) = if label_elapsed < label_dur {
let t = (label_elapsed / label_dur).clamp(0.0, 1.0) as f32;
window.request_animation_frame();
let e = if reduced {
t
} else {
CubicBezier::from_spec(motion.ease.enter).sample(t)
};
(e, if reduced { 0.0 } else { 2.0 * (1.0 - e) })
} else {
(1.0, 0.0)
};
let icon_elapsed = (now - snap.state_changed_at_secs).max(0.0);
let icon_dur = motion.duration.fast.as_secs_f64();
let icon_t = if icon_elapsed < icon_dur {
window.request_animation_frame();
(icon_elapsed / icon_dur).clamp(0.0, 1.0) as f32
} else {
1.0
};
let icon_eased = if reduced {
icon_t
} else {
CubicBezier::from_spec(motion.ease.enter).sample(icon_t)
};
let icon_blur = BlurFallback::evaluate(
px((1.0 - icon_eased) * f32::from(motion.blur.subtle)),
reduced,
);
let arrow_x = if current_state == ActionButtonState::Idle && !reduced {
-6.0 * (1.0 - icon_eased)
} else {
0.0
};
let bg = colors.foreground;
let fg = colors.background;
let show_shadow = !inert && snap.hovered && !snap.pressed;
let resting_shadows = Shadows::resting(theme.mode);
let btn_w_ref = snap.measured_button_width.clone();
let backdrop = 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);
}
window.paint_quad(quad(
paint_rect,
radii,
bg,
Edges::all(px(1.0)),
bg,
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0();
let label_w_ref = snap.measured_label_width.clone();
let has_label_ref = snap.has_measured_label.clone();
let label_probe = canvas(
move |rect, window, _| {
let w = f32::from(rect.size.width);
let prev = *label_w_ref.borrow();
*label_w_ref.borrow_mut() = w;
if w > 0.0 {
*has_label_ref.borrow_mut() = true;
}
if (w - prev).abs() > 0.5 && prev > 0.0 {
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let icon_op = (icon_eased * icon_blur.opacity_multiplier).clamp(0.0, 1.0);
let icon_color = Hsla {
a: fg.a * icon_op,
..fg
};
let icon_el = match current_state {
ActionButtonState::Idle => div()
.w(px(17.0))
.h(px(17.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.ml(px(arrow_x))
.opacity(icon_op)
.child(IconName::ArrowRight)
.into_any_element(),
ActionButtonState::Pending => {
let spin_angle = if reduced {
0.0
} else {
window.request_animation_frame();
((now % 0.7) / 0.7) as f32 * std::f32::consts::TAU
};
div()
.w(px(17.0))
.h(px(17.0))
.flex_none()
.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(cx, cy, 6.5, spin_angle, icon_color, window);
},
)
.size_full(),
)
.into_any_element()
}
ActionButtonState::Success => {
let check_progress = if reduced {
1.0
} else {
let delayed = (icon_elapsed - 0.05).max(0.0);
let dur = motion.duration.standard.as_secs_f64();
if delayed < dur {
window.request_animation_frame();
let t = (delayed / dur).clamp(0.0, 1.0) as f32;
CubicBezier::from_spec(motion.ease.enter).sample(t)
} else {
1.0
}
};
let check_path = checkmark_polyline();
div()
.w(px(17.0))
.h(px(17.0))
.flex_none()
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let sliced = check_path.slice(0.0, check_progress);
if let Some(builder) =
sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(1.8))
&& let Ok(path) = builder.build()
{
window.paint_path(path, icon_color);
}
},
)
.size_full(),
)
.into_any_element()
}
};
let internal_click = internal.clone();
let internal_hover = internal.clone();
let internal_down = internal.clone();
let internal_up = internal.clone();
let internal_up_out = internal.clone();
let internal_kd = internal.clone();
let internal_ku = internal.clone();
let on_action = self.on_action;
let pending_secs = self.pending_duration.as_secs_f64();
let reset_secs = self.reset_after.as_secs_f64();
let is_disabled = self.disabled;
let mut base = BaseButton::new(self.id.clone())
.disabled(self.disabled)
.accessibility_label(
self.accessibility_label
.unwrap_or_else(|| self.label.clone()),
)
.on_click(move |_, window, cx| {
if is_disabled || pending {
return;
}
if !is_controlled {
let t_now = motion_now(cx);
internal_click.update(cx, |s, _| {
s.reset_at_secs = None;
if pending_secs > 0.0 {
s.uncontrolled_state = ActionButtonState::Pending;
s.pending_finish_at_secs = Some(t_now + pending_secs);
} else {
s.uncontrolled_state = ActionButtonState::Success;
s.pending_finish_at_secs = None;
s.reset_at_secs = if reset_secs > 0.0 {
Some(t_now + reset_secs)
} else {
None
};
}
});
}
if let Some(handler) = &on_action {
handler(&(), window, cx);
}
window.refresh();
});
if let Some(handle) = &self.focus_handle {
base = base.track_focus(handle);
}
base.relative()
.self_start()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(Spacing::S2)
.min_h(ControlHeights::MD)
.px(Spacing::S4)
.rounded(Radii::CONTROL)
.overflow_hidden()
.text_size(Typography::TEXT_SM)
.text_color(fg)
.when(self.disabled && !pending, |this| this.opacity(0.7))
.when(!inert, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
internal_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;
}
internal_down.update(cx, |s, _| s.pressed = true);
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
internal_up.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
internal_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" {
internal_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" {
internal_ku.update(cx, |s, _| s.pressed = false);
window.refresh();
}
})
.child(backdrop)
.child(
div()
.relative()
.flex()
.items_center()
.when_some(morphed_label_w, |this, w| this.w(px(w)).overflow_hidden())
.child(
div()
.relative()
.flex_none()
.mt(px(label_y))
.opacity(label_op)
.child(label_probe)
.child(current_text),
),
)
.child(icon_el)
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct ActionButtonHost {
state: ActionButtonState,
runs: Rc<Cell<usize>>,
}
impl Render for ActionButtonHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let runs = self.runs.clone();
div().p(Spacing::S4).child(
ActionButton::new("deploy-action", "Deploy")
.pending_label("Deploying")
.success_label("Deployed")
.state(self.state)
.on_action(cx.listener(move |this, _, _, cx| {
runs.set(runs.get() + 1);
this.state = ActionButtonState::Pending;
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn action_button_cycles_and_swallows_clicks_while_pending(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let runs = Rc::new(Cell::new(0usize));
let (view, cx) = cx.add_window_view(|_, _| ActionButtonHost {
state: ActionButtonState::Idle,
runs: runs.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let btn = window.find_by_label("Deploy");
assert_eq!(btn.role(), Some(Role::Button));
let pos = btn.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
assert_eq!(runs.get(), 1);
});
cx.update(|window, cx| {
window.render_frame(cx);
let btn = window.find_by_label("Deploy");
assert_ne!(btn.disabled(), Some(true));
let pos = btn.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
assert_eq!(runs.get(), 1);
});
view.update(cx, |v, cx| {
v.state = ActionButtonState::Success;
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(window.find_by_label("Deploy").role(), Some(Role::Button));
});
}
#[test]
fn action_button_width_morph_spring_matches_0_24s_critically_damped_curve() {
let solver = SpringSolver::new(WIDTH_MORPH_SPRING, 52.0, 96.0, 0.0);
let omega0 = std::f64::consts::TAU / (0.24 * 1.2);
let mut actual = CurveTrace::new("action_button", "width");
let mut expected = CurveTrace::new("action_button", "width");
for frame in 0..=30 {
let t_ms = frame as f64 * 16.0;
let t = t_ms / 1000.0;
let ref_w = 96.0 - (-omega0 * t).exp() * (44.0 + omega0 * 44.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, "ActionButton width morph error {err:.3}% >= 5%");
}
}