1use std::{cell::RefCell, rc::Rc};
23
24use arc_motion::{
25 ArcPresence, ArcPresenceConfig, CubicBezier, TransformOrigin, arc_spring,
26 arc_spring_with_options, arc_transition, is_reduced_motion, motion_now, scaled_bounds,
27 spring::SpringOptions,
28};
29use arc_tokens::{
30 ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
31};
32use gpui_kit::{
33 AnyElement, App, BorderStyle, ClickEvent, Corners, Edges, ElementId, FocusHandle, Hsla,
34 IntoElement, KeyDownEvent, KeyUpEvent, MouseButton, ParentElement, PathBuilder, Pixels,
35 RenderOnce, SharedString, Styled, Window, assets::IconName, base::Button as BaseButton, canvas,
36 div, point, prelude::*, px, quad,
37};
38
39type ClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
40
41#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
43pub enum ButtonVariant {
44 #[default]
45 Primary,
46 Secondary,
47 Ghost,
48 Danger,
49}
50
51#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
53pub enum ButtonSize {
54 Sm,
55 #[default]
56 Md,
57 Lg,
58}
59
60impl ButtonSize {
61 pub const fn min_height(self) -> Pixels {
62 match self {
63 Self::Sm => ControlHeights::SM,
64 Self::Md => ControlHeights::MD,
65 Self::Lg => ControlHeights::LG,
66 }
67 }
68
69 pub const fn padding_x(self) -> Pixels {
70 match self {
71 Self::Sm => px(10.0),
72 Self::Md => Spacing::S3,
73 Self::Lg => Spacing::S4,
74 }
75 }
76}
77
78pub fn adaptive_press_scale(button_width_px: f32) -> f32 {
82 if button_width_px > 220.0 {
83 0.985
84 } else if button_width_px > 0.0 && button_width_px <= 48.0 {
85 0.96
86 } else {
87 0.97
88 }
89}
90
91#[derive(Clone)]
92struct ButtonInternalState {
93 pressed: bool,
94 hovered: bool,
95 last_content_key: SharedString,
96 morph_armed_until_secs: f64,
97 phase_started_at_secs: f64,
98 measured_button_width: Rc<RefCell<f32>>,
99 measured_content_width: Rc<RefCell<f32>>,
100 has_measured_content: Rc<RefCell<bool>>,
101}
102
103impl ButtonInternalState {
104 fn new(initial_key: SharedString, now: f64) -> Self {
105 Self {
106 pressed: false,
107 hovered: false,
108 last_content_key: initial_key,
109 morph_armed_until_secs: f64::NEG_INFINITY,
110 phase_started_at_secs: now - 10.0,
111 measured_button_width: Rc::new(RefCell::new(0.0)),
112 measured_content_width: Rc::new(RefCell::new(0.0)),
113 has_measured_content: Rc::new(RefCell::new(false)),
114 }
115 }
116}
117
118#[derive(IntoElement)]
121pub struct Button {
122 id: ElementId,
123 variant: ButtonVariant,
124 size: ButtonSize,
125 label: Option<SharedString>,
126 icon_start: Option<IconName>,
127 icon_end: Option<IconName>,
128 custom_child: Option<AnyElement>,
129 content_key_override: Option<SharedString>,
130 loading: bool,
131 disabled: bool,
132 anchors_layer: bool,
133 selected: bool,
134 accessibility_label: Option<SharedString>,
135 tab_index: isize,
136 tab_stop: bool,
137 focus_handle: Option<FocusHandle>,
138 on_click: Option<ClickHandler>,
139}
140
141impl Button {
142 pub fn new(id: impl Into<ElementId>) -> Self {
143 Self {
144 id: id.into(),
145 variant: ButtonVariant::Primary,
146 size: ButtonSize::Md,
147 label: None,
148 icon_start: None,
149 icon_end: None,
150 custom_child: None,
151 content_key_override: None,
152 loading: false,
153 disabled: false,
154 anchors_layer: false,
155 selected: false,
156 accessibility_label: None,
157 tab_index: 0,
158 tab_stop: true,
159 focus_handle: None,
160 on_click: None,
161 }
162 }
163
164 pub fn variant(mut self, variant: ButtonVariant) -> Self {
165 self.variant = variant;
166 self
167 }
168
169 pub fn size(mut self, size: ButtonSize) -> Self {
170 self.size = size;
171 self
172 }
173
174 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
177 self.label = Some(label.into());
178 self
179 }
180
181 pub fn icon(mut self, icon: IconName) -> Self {
183 self.icon_start = Some(icon);
184 self
185 }
186
187 pub fn icon_end(mut self, icon: IconName) -> Self {
189 self.icon_end = Some(icon);
190 self
191 }
192
193 pub fn child(mut self, element: impl IntoElement) -> Self {
196 self.custom_child = Some(element.into_any_element());
197 self
198 }
199
200 pub fn content_key(mut self, key: impl Into<SharedString>) -> Self {
202 self.content_key_override = Some(key.into());
203 self
204 }
205
206 pub fn loading(mut self, loading: bool) -> Self {
209 self.loading = loading;
210 self
211 }
212
213 pub fn disabled(mut self, disabled: bool) -> Self {
214 self.disabled = disabled;
215 self
216 }
217
218 pub fn anchors_layer(mut self, anchors_layer: bool) -> Self {
221 self.anchors_layer = anchors_layer;
222 self
223 }
224
225 pub fn selected(mut self, selected: bool) -> Self {
227 self.selected = selected;
228 self
229 }
230
231 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
233 self.accessibility_label = Some(label.into());
234 self
235 }
236
237 pub fn tab_index(mut self, tab_index: isize) -> Self {
238 self.tab_index = tab_index;
239 self
240 }
241
242 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
243 self.tab_stop = tab_stop;
244 self
245 }
246
247 pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
248 self.focus_handle = Some(handle.clone());
249 self
250 }
251
252 pub fn on_click(
253 mut self,
254 handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
255 ) -> Self {
256 self.on_click = Some(Rc::new(handler));
257 self
258 }
259
260 fn derive_content_key(&self) -> SharedString {
261 if let Some(key) = &self.content_key_override {
262 return key.clone();
263 }
264 let mut out = String::new();
265 if let Some(icon) = self.icon_start {
266 out.push_str(&format!("<{icon:?}>"));
267 }
268 if let Some(label) = &self.label {
269 out.push_str(label.as_ref());
270 }
271 if let Some(icon) = self.icon_end {
272 out.push_str(&format!("<{icon:?}>"));
273 }
274 SharedString::from(out)
275 }
276}
277
278fn paint_spinner_arc(
279 center_x: f32,
280 center_y: f32,
281 radius: f32,
282 angle_rad: f32,
283 color: Hsla,
284 window: &mut Window,
285) {
286 let steps = 20usize;
287 let sweep = std::f32::consts::TAU * 0.72;
288 let mut builder = PathBuilder::stroke(px(1.5));
289 for i in 0..=steps {
290 let a = angle_rad + sweep * (i as f32 / steps as f32);
291 let p = point(
292 px(center_x + radius * a.cos()),
293 px(center_y + radius * a.sin()),
294 );
295 if i == 0 {
296 builder.move_to(p);
297 } else {
298 builder.line_to(p);
299 }
300 }
301 if let Ok(path) = builder.build() {
302 window.paint_path(path, color);
303 }
304}
305
306impl RenderOnce for Button {
307 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
308 let theme = cx.arc_theme().clone();
309 let colors = theme.colors;
310 let motion = theme.motion;
311 let reduced = is_reduced_motion(cx);
312 let now = motion_now(cx);
313
314 let content_key = self.derive_content_key();
315 let is_icon_only = self.label.as_ref().is_none_or(|s| s.trim().is_empty())
316 && self.custom_child.is_none()
317 && (self.icon_start.is_some() || self.icon_end.is_some());
318
319 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-button-state".into());
320 let state = window.use_keyed_state(state_id, cx, |_, _| {
321 ButtonInternalState::new(content_key.clone(), now)
322 });
323
324 {
326 let prev_key = state.read(cx).last_content_key.clone();
327 if prev_key != content_key {
328 state.update(cx, |s, _| {
329 s.last_content_key = content_key.clone();
330 s.morph_armed_until_secs = now + 0.7;
331 s.phase_started_at_secs = now;
332 });
333 }
334 }
335
336 let snap = state.read(cx).clone();
337 let inert = self.disabled || self.loading;
338
339 let button_w = *snap.measured_button_width.borrow();
341 let target_scale = if !inert && !self.anchors_layer && !reduced && snap.pressed {
342 adaptive_press_scale(button_w)
343 } else {
344 1.0
345 };
346 let animated_scale = if reduced {
347 1.0
348 } else {
349 arc_spring(
350 (self.id.clone(), "press-scale"),
351 target_scale,
352 motion.spring.snappy,
353 window,
354 cx,
355 )
356 };
357
358 let measured_content_w = *snap.measured_content_width.borrow();
360 let morph_active = !reduced
361 && *snap.has_measured_content.borrow()
362 && measured_content_w > 0.0
363 && now <= snap.morph_armed_until_secs;
364 let morphed_slot_width = if measured_content_w > 0.0 {
365 let sample = arc_spring_with_options(
366 (self.id.clone(), "slot-width"),
367 measured_content_w,
368 SpringOptions::new(motion.spring.morph),
369 window,
370 cx,
371 );
372 if morph_active {
373 Some(sample.value)
374 } else {
375 None
376 }
377 } else {
378 None
379 };
380
381 let phase_elapsed = (now - snap.phase_started_at_secs).max(0.0);
383 let phase_dur = if reduced {
384 motion.duration.instant
385 } else if is_icon_only {
386 motion.duration.fast
387 } else {
388 motion.duration.standard
389 };
390 let (phase_opacity, phase_y) = if phase_elapsed < phase_dur.as_secs_f64() {
391 let t = (phase_elapsed / phase_dur.as_secs_f64()).clamp(0.0, 1.0) as f32;
392 window.request_animation_frame();
393 let eased = if reduced {
394 t
395 } else {
396 CubicBezier::from_spec(motion.ease.enter).sample(t)
397 };
398 let y_off = if reduced || is_icon_only {
399 0.0
400 } else {
401 2.0 * (1.0 - eased)
402 };
403 (eased, y_off)
404 } else {
405 (1.0, 0.0)
406 };
407
408 let loader_presence = ArcPresence::new((self.id.clone(), "loader-presence"), self.loading)
410 .animate_initial(false)
411 .config(ArcPresenceConfig {
412 enter_duration: motion.duration.fast,
413 exit_duration: motion.duration.instant,
414 enter_ease: motion.ease.enter,
415 exit_ease: motion.ease.standard,
416 fade_on_reduced_motion: true,
417 })
418 .sample(window, cx);
419 let loader_scale = if reduced {
420 1.0
421 } else {
422 arc_spring(
423 (self.id.clone(), "loader-scale"),
424 if self.loading { 1.0 } else { 0.8 },
425 motion.spring.snappy,
426 window,
427 cx,
428 )
429 };
430 let label_visibility = arc_transition(
431 (self.id.clone(), "label-vis"),
432 if self.loading { 0.0 } else { 1.0 },
433 if reduced {
434 motion.duration.instant
435 } else {
436 motion.duration.fast
437 },
438 motion.ease.standard,
439 window,
440 cx,
441 );
442
443 let is_hover = !inert && snap.hovered;
445 let is_press = !inert && snap.pressed;
446 let (mut bg, border, fg, show_shadow, root_opacity) = match self.variant {
447 ButtonVariant::Primary => {
448 if self.disabled {
449 (
450 colors.foreground,
451 colors.foreground,
452 colors.background,
453 false,
454 0.52_f32,
455 )
456 } else {
457 let op = if is_press {
458 0.84
459 } else if is_hover {
460 0.91
461 } else {
462 1.0
463 };
464 (
465 colors.foreground,
466 colors.foreground,
467 colors.background,
468 is_hover && !is_press,
469 op,
470 )
471 }
472 }
473 ButtonVariant::Secondary => {
474 if self.disabled {
475 (
476 colors.surface_muted,
477 colors.border,
478 colors.text_muted,
479 false,
480 1.0,
481 )
482 } else {
483 let surface = if is_press || is_hover || self.selected {
484 colors.surface_muted
485 } else {
486 colors.surface
487 };
488 (
489 surface,
490 colors.border,
491 colors.foreground,
492 is_hover && !is_press,
493 1.0,
494 )
495 }
496 }
497 ButtonVariant::Ghost => {
498 if self.disabled {
499 (
500 Hsla::transparent_black(),
501 Hsla::transparent_black(),
502 colors.text_muted,
503 false,
504 1.0,
505 )
506 } else if is_press || is_hover || self.selected {
507 (
508 colors.surface_muted,
509 Hsla::transparent_black(),
510 colors.foreground,
511 false,
512 1.0,
513 )
514 } else {
515 (
516 Hsla::transparent_black(),
517 Hsla::transparent_black(),
518 colors.text_secondary,
519 false,
520 1.0,
521 )
522 }
523 }
524 ButtonVariant::Danger => {
525 if self.disabled {
526 (
527 colors.surface_muted,
528 colors.border,
529 oklab_mix(colors.danger, colors.surface_muted, 0.55),
530 false,
531 1.0,
532 )
533 } else if is_press || is_hover {
534 (
535 colors.surface_muted,
536 colors.danger,
537 colors.danger,
538 false,
539 1.0,
540 )
541 } else {
542 (colors.surface, colors.border, colors.danger, false, 1.0)
543 }
544 }
545 };
546 if self.variant == ButtonVariant::Primary && root_opacity < 1.0 && !self.disabled {
547 bg.a *= root_opacity;
548 }
549
550 let btn_w_ref = snap.measured_button_width.clone();
552 let resting_shadows = Shadows::resting(theme.mode);
553 let backdrop_canvas = canvas(
554 move |rect, _, _| {
555 *btn_w_ref.borrow_mut() = f32::from(rect.size.width);
556 },
557 move |rect, _, window, _| {
558 let paint_rect = scaled_bounds(
559 rect,
560 animated_scale,
561 animated_scale,
562 TransformOrigin::CENTER,
563 );
564 let radii = Corners::all(Radii::CONTROL);
565 if show_shadow {
566 window.paint_drop_shadows(paint_rect, radii, &resting_shadows);
567 }
568 if bg.a > 0.0 || border.a > 0.0 {
569 window.paint_quad(quad(
570 paint_rect,
571 radii,
572 bg,
573 Edges::all(px(1.0)),
574 border,
575 BorderStyle::Solid,
576 ));
577 }
578 },
579 )
580 .absolute()
581 .inset_0();
582
583 let content_w_ref = snap.measured_content_width.clone();
585 let has_measured_ref = snap.has_measured_content.clone();
586 let content_measure = canvas(
587 move |rect, window, _| {
588 let next_w = f32::from(rect.size.width);
589 let prev_w = *content_w_ref.borrow();
590 *content_w_ref.borrow_mut() = next_w;
591 if next_w > 0.0 {
592 *has_measured_ref.borrow_mut() = true;
593 }
594 if (next_w - prev_w).abs() > 0.5 && prev_w > 0.0 {
595 window.request_animation_frame();
596 }
597 },
598 |_, _, _, _| {},
599 )
600 .absolute()
601 .inset_0();
602
603 let label_content = div()
604 .relative()
605 .flex_none()
606 .flex()
607 .flex_row()
608 .items_center()
609 .justify_center()
610 .gap(Spacing::S2)
611 .mt(px(phase_y))
612 .opacity((phase_opacity * label_visibility).clamp(0.0, 1.0))
613 .child(content_measure)
614 .when_some(self.icon_start, |this, icon| this.child(icon))
615 .when_some(self.label.clone(), |this, text| this.child(text))
616 .when_some(self.custom_child, |this, elem| this.child(elem))
617 .when_some(self.icon_end, |this, icon| this.child(icon));
618
619 let label_slot = div()
620 .relative()
621 .flex()
622 .items_center()
623 .justify_center()
624 .when_some(morphed_slot_width, |this, w| {
625 this.w(px(w)).overflow_hidden()
626 })
627 .child(label_content);
628
629 let spinner_overlay = if loader_presence.should_render() {
631 let spinner_op = loader_presence.progress.clamp(0.0, 1.0);
632 let spinner_color = Hsla {
633 a: fg.a * spinner_op,
634 ..fg
635 };
636 let spin_angle = if reduced {
637 0.0
638 } else {
639 window.request_animation_frame();
640 ((now % 0.7) / 0.7) as f32 * std::f32::consts::TAU
641 };
642 let radius = 6.5 * loader_scale.clamp(0.6, 1.05);
643 Some(
644 div()
645 .absolute()
646 .inset_0()
647 .flex()
648 .items_center()
649 .justify_center()
650 .child(
651 canvas(
652 |_, _, _| {},
653 move |rect, _, window, _| {
654 let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
655 let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
656 paint_spinner_arc(
657 cx,
658 cy,
659 radius,
660 spin_angle,
661 spinner_color,
662 window,
663 );
664 },
665 )
666 .size(Spacing::S4),
667 ),
668 )
669 } else {
670 None
671 };
672
673 let a11y_label = self
674 .accessibility_label
675 .clone()
676 .or_else(|| self.label.clone());
677
678 let state_hover = state.clone();
679 let state_down = state.clone();
680 let state_up = state.clone();
681 let state_up_out = state.clone();
682 let state_kd = state.clone();
683 let state_ku = state.clone();
684 let is_loading = self.loading;
685 let is_disabled = self.disabled;
686 let on_click = self.on_click;
687
688 let mut base = BaseButton::new(self.id.clone())
689 .disabled(self.disabled)
690 .tab_index(self.tab_index)
691 .tab_stop(self.tab_stop);
692
693 if let Some(label) = a11y_label {
694 base = base.accessibility_label(label);
695 }
696 if let Some(handle) = &self.focus_handle {
697 base = base.track_focus(handle);
698 }
699 if let Some(handler) = on_click {
700 base = base.on_click(move |event, window, cx| {
701 if is_loading || is_disabled {
703 return;
704 }
705 handler(event, window, cx);
706 });
707 }
708
709 let pad_x = if is_icon_only {
710 Spacing::S2
711 } else {
712 self.size.padding_x()
713 };
714
715 base.relative()
716 .self_start()
717 .flex()
718 .flex_row()
719 .items_center()
720 .justify_center()
721 .min_h(self.size.min_height())
722 .when(is_icon_only, |this| this.min_w(self.size.min_height()))
723 .px(pad_x)
724 .rounded(Radii::CONTROL)
725 .text_size(Typography::TEXT_SM)
726 .text_color(fg)
727 .when(
728 self.disabled && self.variant == ButtonVariant::Primary,
729 |this| this.opacity(0.52),
730 )
731 .when(!inert, |this| this.cursor_pointer())
732 .on_hover(move |hovered, window, cx| {
733 state_hover.update(cx, |s, _| {
734 s.hovered = *hovered;
735 if !*hovered {
736 s.pressed = false;
737 }
738 });
739 window.refresh();
740 })
741 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
742 if inert {
743 return;
744 }
745 state_down.update(cx, |s, _| s.pressed = true);
746 window.refresh();
747 })
748 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
749 state_up.update(cx, |s, _| s.pressed = false);
750 window.refresh();
751 })
752 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
753 state_up_out.update(cx, |s, _| s.pressed = false);
754 window.refresh();
755 })
756 .on_key_down(move |event: &KeyDownEvent, window, cx| {
757 if inert {
758 return;
759 }
760 if event.keystroke.key == "space" || event.keystroke.key == "enter" {
761 state_kd.update(cx, |s, _| s.pressed = true);
762 window.refresh();
763 }
764 })
765 .on_key_up(move |event: &KeyUpEvent, window, cx| {
766 if event.keystroke.key == "space" || event.keystroke.key == "enter" {
767 state_ku.update(cx, |s, _| s.pressed = false);
768 window.refresh();
769 }
770 })
771 .child(backdrop_canvas)
772 .child(label_slot)
773 .when_some(spinner_overlay, |this, loader| this.child(loader))
774 }
775}
776
777#[cfg(test)]
778mod tests {
779 use std::{cell::Cell, rc::Rc};
780
781 use arc_motion::{
782 CurveTrace, ReducedMotionChoice, SpringSolver, max_curve_error_pct, set_reduced_motion,
783 };
784 use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
785 use gpui_kit::{
786 Context, MouseButton, Render, Role, TestAppContext, div,
787 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
788 };
789
790 use super::*;
791
792 struct ButtonHost {
793 clicks: Rc<Cell<usize>>,
794 loading: bool,
795 disabled: bool,
796 label: SharedString,
797 }
798
799 impl Render for ButtonHost {
800 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
801 let clicks = self.clicks.clone();
802 div().p(Spacing::S4).child(
803 Button::new("save-btn")
804 .variant(ButtonVariant::Primary)
805 .size(ButtonSize::Md)
806 .label(self.label.clone())
807 .loading(self.loading)
808 .disabled(self.disabled)
809 .on_click(cx.listener(move |_, _, _, _| {
810 clicks.set(clicks.get() + 1);
811 })),
812 )
813 }
814 }
815
816 #[gpui_kit::test]
817 fn button_click_keyboard_loading_swallow_and_disabled(cx: &mut TestAppContext) {
818 cx.update(|cx| {
819 gpui_kit::init(cx);
820 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
821 });
822
823 let clicks = Rc::new(Cell::new(0usize));
824 let (view, cx) = cx.add_window_view(|_, _| ButtonHost {
825 clicks: clicks.clone(),
826 loading: false,
827 disabled: false,
828 label: "Save".into(),
829 });
830
831 cx.update(|window, cx| {
832 window.render_frame(cx);
833 let btn = window.find_by_label("Save");
834 assert_eq!(btn.role(), Some(Role::Button));
835 assert_ne!(btn.disabled(), Some(true));
836
837 let center = btn.bounds().center();
839 window.pointer_down(center, MouseButton::Left, cx);
840 window.pointer_up(center, MouseButton::Left, cx);
841 assert_eq!(clicks.get(), 1);
842
843 window.press("space", cx);
845 assert_eq!(clicks.get(), 2);
846 });
847
848 view.update(cx, |v, cx| {
850 v.loading = true;
851 cx.notify();
852 });
853 cx.update(|window, cx| {
854 window.render_frame(cx);
855 let btn = window.find_by_label("Save");
856 assert_ne!(btn.disabled(), Some(true));
857 let center = btn.bounds().center();
858 window.pointer_down(center, MouseButton::Left, cx);
859 window.pointer_up(center, MouseButton::Left, cx);
860 assert_eq!(clicks.get(), 2);
861 });
862
863 view.update(cx, |v, cx| {
865 v.loading = false;
866 v.disabled = true;
867 cx.notify();
868 });
869 cx.update(|window, cx| {
870 window.render_frame(cx);
871 let btn = window.find_by_label("Save");
872 assert_eq!(btn.disabled(), Some(true));
873 let center = btn.bounds().center();
874 window.pointer_down(center, MouseButton::Left, cx);
875 window.pointer_up(center, MouseButton::Left, cx);
876 assert_eq!(clicks.get(), 2);
877 });
878 }
879
880 #[test]
881 fn adaptive_press_scale_matches_arc_width_breakpoints() {
882 assert!((adaptive_press_scale(36.0) - 0.96).abs() < 1e-6);
883 assert!((adaptive_press_scale(48.0) - 0.96).abs() < 1e-6);
884 assert!((adaptive_press_scale(120.0) - 0.97).abs() < 1e-6);
885 assert!((adaptive_press_scale(220.0) - 0.97).abs() < 1e-6);
886 assert!((adaptive_press_scale(260.0) - 0.985).abs() < 1e-6);
887 }
888
889 #[test]
890 fn button_width_morph_spring_matches_motion_reference_within_5_percent() {
891 let spec = ArcMotionTokens::DEFAULT.spring.morph;
892 let solver = SpringSolver::new(spec, 60.0, 128.0, 0.0);
893 let omega0 = std::f64::consts::TAU / (0.42 * 1.2);
894 let mut actual = CurveTrace::new("button", "slot_width");
895 let mut expected = CurveTrace::new("button", "slot_width");
896 for frame in 0..=45 {
897 let t_ms = frame as f64 * 16.0;
898 let t = t_ms / 1000.0;
899 let ref_w = 128.0 - (-omega0 * t).exp() * (68.0 + omega0 * 68.0 * t);
900 expected.push(t_ms, ref_w);
901 actual.push(t_ms, f64::from(solver.sample(t).value));
902 }
903 let err = max_curve_error_pct(&actual, &expected);
904 assert!(err < 5.0, "Button width morph error {err:.3}% >= 5%");
905 assert!(
906 err < 1.0,
907 "Expected tight morph spring match, got {err:.3}%"
908 );
909 }
910
911 #[gpui_kit::test]
912 fn button_reduced_motion_and_label_morph_do_not_crash(cx: &mut TestAppContext) {
913 cx.update(|cx| {
914 gpui_kit::init(cx);
915 install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
916 set_reduced_motion(ReducedMotionChoice::Reduce, cx);
917 });
918 let (view, cx) = cx.add_window_view(|_, _| ButtonHost {
919 clicks: Rc::new(Cell::new(0)),
920 loading: false,
921 disabled: false,
922 label: "Save".into(),
923 });
924 cx.update(|window, cx| {
925 window.render_frame(cx);
926 });
927 view.update(cx, |v, cx| {
928 v.label = "Saved changes".into();
929 cx.notify();
930 });
931 cx.update(|window, cx| {
932 window.render_frame(cx);
933 assert_eq!(
934 window.find_by_label("Saved changes").role(),
935 Some(Role::Button)
936 );
937 });
938 }
939}