1use std::{cell::RefCell, rc::Rc, time::Duration};
17
18use arc_motion::{
19 BlurFallback, CubicBezier, PathPoint, PolylinePath, TransformOrigin, arc_spring,
20 arc_spring_with_options, is_reduced_motion, motion_now, scaled_bounds, spring::SpringOptions,
21};
22use arc_tokens::{
23 ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography,
24};
25use gpui_kit::{
26 App, BorderStyle, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
27 KeyUpEvent, MouseButton, ParentElement, PathBuilder, RenderOnce, SharedString, Styled, Window,
28 assets::IconName, base::Button as BaseButton, canvas, div, point, prelude::*, px, quad,
29};
30
31type ActionHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
32
33const WIDTH_MORPH_SPRING: SpringSpec = SpringSpec::visual(0.24, 0.0);
35
36#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
38pub enum ActionButtonState {
39 #[default]
40 Idle,
41 Pending,
42 Success,
43}
44
45#[derive(Clone)]
46struct ActionButtonInternal {
47 uncontrolled_state: ActionButtonState,
48 last_state: ActionButtonState,
49 state_changed_at_secs: f64,
50 pending_finish_at_secs: Option<f64>,
51 reset_at_secs: Option<f64>,
52 pressed: bool,
53 hovered: bool,
54 last_label: SharedString,
55 morph_armed_until_secs: f64,
56 label_changed_at_secs: f64,
57 measured_button_width: Rc<RefCell<f32>>,
58 measured_label_width: Rc<RefCell<f32>>,
59 has_measured_label: Rc<RefCell<bool>>,
60}
61
62impl ActionButtonInternal {
63 fn new(initial_state: ActionButtonState, initial_label: SharedString, now: f64) -> Self {
64 Self {
65 uncontrolled_state: initial_state,
66 last_state: initial_state,
67 state_changed_at_secs: now - 10.0,
68 pending_finish_at_secs: None,
69 reset_at_secs: None,
70 pressed: false,
71 hovered: false,
72 last_label: initial_label,
73 morph_armed_until_secs: f64::NEG_INFINITY,
74 label_changed_at_secs: now - 10.0,
75 measured_button_width: Rc::new(RefCell::new(0.0)),
76 measured_label_width: Rc::new(RefCell::new(0.0)),
77 has_measured_label: Rc::new(RefCell::new(false)),
78 }
79 }
80}
81
82#[derive(IntoElement)]
85pub struct ActionButton {
86 id: ElementId,
87 label: SharedString,
88 pending_label: SharedString,
89 success_label: SharedString,
90 state: Option<ActionButtonState>,
91 reset_after: Duration,
92 pending_duration: Duration,
93 disabled: bool,
94 accessibility_label: Option<SharedString>,
95 focus_handle: Option<FocusHandle>,
96 on_action: Option<ActionHandler>,
97}
98
99impl ActionButton {
100 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
101 Self {
102 id: id.into(),
103 label: label.into(),
104 pending_label: "Saving".into(),
105 success_label: "Saved".into(),
106 state: None,
107 reset_after: Duration::from_millis(2400),
108 pending_duration: Duration::ZERO,
109 disabled: false,
110 accessibility_label: None,
111 focus_handle: None,
112 on_action: None,
113 }
114 }
115
116 pub fn pending_label(mut self, label: impl Into<SharedString>) -> Self {
117 self.pending_label = label.into();
118 self
119 }
120
121 pub fn success_label(mut self, label: impl Into<SharedString>) -> Self {
122 self.success_label = label.into();
123 self
124 }
125
126 pub fn state(mut self, state: ActionButtonState) -> Self {
129 self.state = Some(state);
130 self
131 }
132
133 pub fn reset_after(mut self, duration: Duration) -> Self {
135 self.reset_after = duration;
136 self
137 }
138
139 pub fn pending_duration(mut self, duration: Duration) -> Self {
141 self.pending_duration = duration;
142 self
143 }
144
145 pub fn disabled(mut self, disabled: bool) -> Self {
146 self.disabled = disabled;
147 self
148 }
149
150 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
151 self.accessibility_label = Some(label.into());
152 self
153 }
154
155 pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
156 self.focus_handle = Some(handle.clone());
157 self
158 }
159
160 pub fn on_action(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
161 self.on_action = Some(Rc::new(handler));
162 self
163 }
164}
165
166fn paint_spinner(cx: f32, cy: f32, radius: f32, angle_rad: f32, color: Hsla, window: &mut Window) {
167 let steps = 20usize;
168 let sweep = std::f32::consts::TAU * 0.72;
169 let mut builder = PathBuilder::stroke(px(1.5));
170 for i in 0..=steps {
171 let a = angle_rad + sweep * (i as f32 / steps as f32);
172 let p = point(px(cx + radius * a.cos()), px(cy + radius * a.sin()));
173 if i == 0 {
174 builder.move_to(p);
175 } else {
176 builder.line_to(p);
177 }
178 }
179 if let Ok(path) = builder.build() {
180 window.paint_path(path, color);
181 }
182}
183
184fn checkmark_polyline() -> PolylinePath {
185 let s = 17.0 / 24.0;
187 PolylinePath::new(vec![
188 PathPoint::new(4.0 * s, 12.0 * s),
189 PathPoint::new(9.0 * s, 17.0 * s),
190 PathPoint::new(20.0 * s, 6.0 * s),
191 ])
192}
193
194impl RenderOnce for ActionButton {
195 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
196 let theme = cx.arc_theme().clone();
197 let colors = theme.colors;
198 let motion = theme.motion;
199 let reduced = is_reduced_motion(cx);
200 let now = motion_now(cx);
201
202 let is_controlled = self.state.is_some();
203 let initial_state = self.state.unwrap_or(ActionButtonState::Idle);
204 let state_id =
205 ElementId::NamedChild(self.id.clone().into(), "__arc-action-button-state".into());
206 let internal = window.use_keyed_state(state_id, cx, |_, _| {
207 ActionButtonInternal::new(initial_state, self.label.clone(), now)
208 });
209
210 if !is_controlled {
212 let snap = internal.read(cx).clone();
213 let mut keep_ticking = false;
214 if let Some(done_at) = snap.pending_finish_at_secs {
215 if now >= done_at {
216 let reset_secs = self.reset_after.as_secs_f64();
217 internal.update(cx, |s, _| {
218 s.pending_finish_at_secs = None;
219 s.uncontrolled_state = ActionButtonState::Success;
220 s.reset_at_secs = if reset_secs > 0.0 {
221 Some(now + reset_secs)
222 } else {
223 None
224 };
225 });
226 } else {
227 keep_ticking = true;
228 }
229 }
230 let snap2 = internal.read(cx).clone();
231 if let Some(reset_at) = snap2.reset_at_secs {
232 if now >= reset_at {
233 internal.update(cx, |s, _| {
234 s.reset_at_secs = None;
235 s.uncontrolled_state = ActionButtonState::Idle;
236 });
237 } else {
238 keep_ticking = true;
239 }
240 }
241 if keep_ticking {
242 window.request_animation_frame();
243 }
244 }
245
246 let current_state = self
247 .state
248 .unwrap_or_else(|| internal.read(cx).uncontrolled_state);
249 let current_text = match current_state {
250 ActionButtonState::Idle => self.label.clone(),
251 ActionButtonState::Pending => self.pending_label.clone(),
252 ActionButtonState::Success => self.success_label.clone(),
253 };
254
255 {
257 let snap = internal.read(cx).clone();
258 if snap.last_state != current_state || snap.last_label != current_text {
259 internal.update(cx, |s, _| {
260 if s.last_state != current_state {
261 s.last_state = current_state;
262 s.state_changed_at_secs = now;
263 }
264 if s.last_label != current_text {
265 s.last_label = current_text.clone();
266 s.morph_armed_until_secs = now + 0.7;
267 s.label_changed_at_secs = now;
268 }
269 });
270 }
271 }
272
273 let snap = internal.read(cx).clone();
274 let pending = current_state == ActionButtonState::Pending;
275 let inert = self.disabled || pending;
276
277 let btn_w = *snap.measured_button_width.borrow();
279 let target_scale = if !inert && !reduced && snap.pressed {
280 if btn_w > 220.0 { 0.985 } else { 0.97 }
281 } else {
282 1.0
283 };
284 let animated_scale = if reduced {
285 1.0
286 } else {
287 arc_spring(
288 (self.id.clone(), "press-scale"),
289 target_scale,
290 motion.spring.snappy,
291 window,
292 cx,
293 )
294 };
295
296 let measured_label_w = *snap.measured_label_width.borrow();
298 let morph_active = !reduced
299 && *snap.has_measured_label.borrow()
300 && measured_label_w > 0.0
301 && now <= snap.morph_armed_until_secs;
302 let morphed_label_w = if measured_label_w > 0.0 {
303 let sample = arc_spring_with_options(
304 (self.id.clone(), "label-width"),
305 measured_label_w,
306 SpringOptions::new(WIDTH_MORPH_SPRING),
307 window,
308 cx,
309 );
310 if morph_active {
311 Some(sample.value)
312 } else {
313 None
314 }
315 } else {
316 None
317 };
318
319 let label_elapsed = (now - snap.label_changed_at_secs).max(0.0);
321 let label_dur = if reduced {
322 motion.duration.instant.as_secs_f64()
323 } else {
324 0.16
325 };
326 let (label_op, label_y) = if label_elapsed < label_dur {
327 let t = (label_elapsed / label_dur).clamp(0.0, 1.0) as f32;
328 window.request_animation_frame();
329 let e = if reduced {
330 t
331 } else {
332 CubicBezier::from_spec(motion.ease.enter).sample(t)
333 };
334 (e, if reduced { 0.0 } else { 2.0 * (1.0 - e) })
335 } else {
336 (1.0, 0.0)
337 };
338
339 let icon_elapsed = (now - snap.state_changed_at_secs).max(0.0);
341 let icon_dur = motion.duration.fast.as_secs_f64();
342 let icon_t = if icon_elapsed < icon_dur {
343 window.request_animation_frame();
344 (icon_elapsed / icon_dur).clamp(0.0, 1.0) as f32
345 } else {
346 1.0
347 };
348 let icon_eased = if reduced {
349 icon_t
350 } else {
351 CubicBezier::from_spec(motion.ease.enter).sample(icon_t)
352 };
353 let icon_blur = BlurFallback::evaluate(
354 px((1.0 - icon_eased) * f32::from(motion.blur.subtle)),
355 reduced,
356 );
357 let arrow_x = if current_state == ActionButtonState::Idle && !reduced {
358 -6.0 * (1.0 - icon_eased)
359 } else {
360 0.0
361 };
362
363 let bg = colors.foreground;
364 let fg = colors.background;
365 let show_shadow = !inert && snap.hovered && !snap.pressed;
366 let resting_shadows = Shadows::resting(theme.mode);
367
368 let btn_w_ref = snap.measured_button_width.clone();
369 let backdrop = canvas(
370 move |rect, _, _| {
371 *btn_w_ref.borrow_mut() = f32::from(rect.size.width);
372 },
373 move |rect, _, window, _| {
374 let paint_rect = scaled_bounds(
375 rect,
376 animated_scale,
377 animated_scale,
378 TransformOrigin::CENTER,
379 );
380 let radii = Corners::all(Radii::CONTROL);
381 if show_shadow {
382 window.paint_drop_shadows(paint_rect, radii, &resting_shadows);
383 }
384 window.paint_quad(quad(
385 paint_rect,
386 radii,
387 bg,
388 Edges::all(px(1.0)),
389 bg,
390 BorderStyle::Solid,
391 ));
392 },
393 )
394 .absolute()
395 .inset_0();
396
397 let label_w_ref = snap.measured_label_width.clone();
398 let has_label_ref = snap.has_measured_label.clone();
399 let label_probe = canvas(
400 move |rect, window, _| {
401 let w = f32::from(rect.size.width);
402 let prev = *label_w_ref.borrow();
403 *label_w_ref.borrow_mut() = w;
404 if w > 0.0 {
405 *has_label_ref.borrow_mut() = true;
406 }
407 if (w - prev).abs() > 0.5 && prev > 0.0 {
408 window.request_animation_frame();
409 }
410 },
411 |_, _, _, _| {},
412 )
413 .absolute()
414 .inset_0();
415
416 let icon_op = (icon_eased * icon_blur.opacity_multiplier).clamp(0.0, 1.0);
417 let icon_color = Hsla {
418 a: fg.a * icon_op,
419 ..fg
420 };
421
422 let icon_el = match current_state {
423 ActionButtonState::Idle => div()
424 .w(px(17.0))
425 .h(px(17.0))
426 .flex_none()
427 .flex()
428 .items_center()
429 .justify_center()
430 .ml(px(arrow_x))
431 .opacity(icon_op)
432 .child(IconName::ArrowRight)
433 .into_any_element(),
434 ActionButtonState::Pending => {
435 let spin_angle = if reduced {
436 0.0
437 } else {
438 window.request_animation_frame();
439 ((now % 0.7) / 0.7) as f32 * std::f32::consts::TAU
440 };
441 div()
442 .w(px(17.0))
443 .h(px(17.0))
444 .flex_none()
445 .child(
446 canvas(
447 |_, _, _| {},
448 move |rect, _, window, _| {
449 let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
450 let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
451 paint_spinner(cx, cy, 6.5, spin_angle, icon_color, window);
452 },
453 )
454 .size_full(),
455 )
456 .into_any_element()
457 }
458 ActionButtonState::Success => {
459 let check_progress = if reduced {
461 1.0
462 } else {
463 let delayed = (icon_elapsed - 0.05).max(0.0);
464 let dur = motion.duration.standard.as_secs_f64();
465 if delayed < dur {
466 window.request_animation_frame();
467 let t = (delayed / dur).clamp(0.0, 1.0) as f32;
468 CubicBezier::from_spec(motion.ease.enter).sample(t)
469 } else {
470 1.0
471 }
472 };
473 let check_path = checkmark_polyline();
474 div()
475 .w(px(17.0))
476 .h(px(17.0))
477 .flex_none()
478 .child(
479 canvas(
480 |_, _, _| {},
481 move |rect, _, window, _| {
482 let sliced = check_path.slice(0.0, check_progress);
483 if let Some(builder) =
484 sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(1.8))
485 && let Ok(path) = builder.build()
486 {
487 window.paint_path(path, icon_color);
488 }
489 },
490 )
491 .size_full(),
492 )
493 .into_any_element()
494 }
495 };
496
497 let internal_click = internal.clone();
498 let internal_hover = internal.clone();
499 let internal_down = internal.clone();
500 let internal_up = internal.clone();
501 let internal_up_out = internal.clone();
502 let internal_kd = internal.clone();
503 let internal_ku = internal.clone();
504 let on_action = self.on_action;
505 let pending_secs = self.pending_duration.as_secs_f64();
506 let reset_secs = self.reset_after.as_secs_f64();
507 let is_disabled = self.disabled;
508
509 let mut base = BaseButton::new(self.id.clone())
510 .disabled(self.disabled)
511 .accessibility_label(
512 self.accessibility_label
513 .unwrap_or_else(|| self.label.clone()),
514 )
515 .on_click(move |_, window, cx| {
516 if is_disabled || pending {
517 return;
518 }
519 if !is_controlled {
520 let t_now = motion_now(cx);
521 internal_click.update(cx, |s, _| {
522 s.reset_at_secs = None;
523 if pending_secs > 0.0 {
524 s.uncontrolled_state = ActionButtonState::Pending;
525 s.pending_finish_at_secs = Some(t_now + pending_secs);
526 } else {
527 s.uncontrolled_state = ActionButtonState::Success;
528 s.pending_finish_at_secs = None;
529 s.reset_at_secs = if reset_secs > 0.0 {
530 Some(t_now + reset_secs)
531 } else {
532 None
533 };
534 }
535 });
536 }
537 if let Some(handler) = &on_action {
538 handler(&(), window, cx);
539 }
540 window.refresh();
541 });
542
543 if let Some(handle) = &self.focus_handle {
544 base = base.track_focus(handle);
545 }
546
547 base.relative()
548 .self_start()
549 .flex()
550 .flex_row()
551 .items_center()
552 .justify_center()
553 .gap(Spacing::S2)
554 .min_h(ControlHeights::MD)
555 .px(Spacing::S4)
556 .rounded(Radii::CONTROL)
557 .overflow_hidden()
558 .text_size(Typography::TEXT_SM)
559 .text_color(fg)
560 .when(self.disabled && !pending, |this| this.opacity(0.7))
561 .when(!inert, |this| this.cursor_pointer())
562 .on_hover(move |hovered, window, cx| {
563 internal_hover.update(cx, |s, _| {
564 s.hovered = *hovered;
565 if !*hovered {
566 s.pressed = false;
567 }
568 });
569 window.refresh();
570 })
571 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
572 if inert {
573 return;
574 }
575 internal_down.update(cx, |s, _| s.pressed = true);
576 window.refresh();
577 })
578 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
579 internal_up.update(cx, |s, _| s.pressed = false);
580 window.refresh();
581 })
582 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
583 internal_up_out.update(cx, |s, _| s.pressed = false);
584 window.refresh();
585 })
586 .on_key_down(move |event: &KeyDownEvent, window, cx| {
587 if inert {
588 return;
589 }
590 if event.keystroke.key == "space" || event.keystroke.key == "enter" {
591 internal_kd.update(cx, |s, _| s.pressed = true);
592 window.refresh();
593 }
594 })
595 .on_key_up(move |event: &KeyUpEvent, window, cx| {
596 if event.keystroke.key == "space" || event.keystroke.key == "enter" {
597 internal_ku.update(cx, |s, _| s.pressed = false);
598 window.refresh();
599 }
600 })
601 .child(backdrop)
602 .child(
603 div()
604 .relative()
605 .flex()
606 .items_center()
607 .when_some(morphed_label_w, |this, w| this.w(px(w)).overflow_hidden())
608 .child(
609 div()
610 .relative()
611 .flex_none()
612 .mt(px(label_y))
613 .opacity(label_op)
614 .child(label_probe)
615 .child(current_text),
616 ),
617 )
618 .child(icon_el)
619 }
620}
621
622#[cfg(test)]
623mod tests {
624 use std::{cell::Cell, rc::Rc};
625
626 use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
627 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
628 use gpui_kit::{
629 Context, MouseButton, Render, Role, TestAppContext, div,
630 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
631 };
632
633 use super::*;
634
635 struct ActionButtonHost {
636 state: ActionButtonState,
637 runs: Rc<Cell<usize>>,
638 }
639
640 impl Render for ActionButtonHost {
641 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
642 let runs = self.runs.clone();
643 div().p(Spacing::S4).child(
644 ActionButton::new("deploy-action", "Deploy")
645 .pending_label("Deploying")
646 .success_label("Deployed")
647 .state(self.state)
648 .on_action(cx.listener(move |this, _, _, cx| {
649 runs.set(runs.get() + 1);
650 this.state = ActionButtonState::Pending;
651 cx.notify();
652 })),
653 )
654 }
655 }
656
657 #[gpui_kit::test]
658 fn action_button_cycles_and_swallows_clicks_while_pending(cx: &mut TestAppContext) {
659 cx.update(|cx| {
660 gpui_kit::init(cx);
661 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
662 });
663
664 let runs = Rc::new(Cell::new(0usize));
665 let (view, cx) = cx.add_window_view(|_, _| ActionButtonHost {
666 state: ActionButtonState::Idle,
667 runs: runs.clone(),
668 });
669
670 cx.update(|window, cx| {
671 window.render_frame(cx);
672 let btn = window.find_by_label("Deploy");
673 assert_eq!(btn.role(), Some(Role::Button));
674 let pos = btn.bounds().center();
675 window.pointer_down(pos, MouseButton::Left, cx);
676 window.pointer_up(pos, MouseButton::Left, cx);
677 assert_eq!(runs.get(), 1);
678 });
679
680 cx.update(|window, cx| {
682 window.render_frame(cx);
683 let btn = window.find_by_label("Deploy");
684 assert_ne!(btn.disabled(), Some(true));
685 let pos = btn.bounds().center();
686 window.pointer_down(pos, MouseButton::Left, cx);
687 window.pointer_up(pos, MouseButton::Left, cx);
688 assert_eq!(runs.get(), 1);
689 });
690
691 view.update(cx, |v, cx| {
693 v.state = ActionButtonState::Success;
694 cx.notify();
695 });
696 cx.update(|window, cx| {
697 window.render_frame(cx);
698 assert_eq!(window.find_by_label("Deploy").role(), Some(Role::Button));
699 });
700 }
701
702 #[test]
703 fn action_button_width_morph_spring_matches_0_24s_critically_damped_curve() {
704 let solver = SpringSolver::new(WIDTH_MORPH_SPRING, 52.0, 96.0, 0.0);
705 let omega0 = std::f64::consts::TAU / (0.24 * 1.2);
706 let mut actual = CurveTrace::new("action_button", "width");
707 let mut expected = CurveTrace::new("action_button", "width");
708 for frame in 0..=30 {
709 let t_ms = frame as f64 * 16.0;
710 let t = t_ms / 1000.0;
711 let ref_w = 96.0 - (-omega0 * t).exp() * (44.0 + omega0 * 44.0 * t);
712 expected.push(t_ms, ref_w);
713 actual.push(t_ms, f64::from(solver.sample(t).value));
714 }
715 let err = max_curve_error_pct(&actual, &expected);
716 assert!(err < 5.0, "ActionButton width morph error {err:.3}% >= 5%");
717 }
718}