Skip to main content

arc_ui/actions/
button.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/button/button.tsx` & `button.module.css`
3//!
4//! P2 Component #1: `button`
5//!
6//! - Behavior & Accessibility: `gpui_kit::base::Button` (`Role::Button`, focus handle,
7//!   Enter/Space keyboard activation, disabled semantics). Loading keeps the button focusable
8//!   (preventing mid-action focus loss) while swallowing clicks.
9//! - Visual Variants: `Primary`, `Secondary`, `Ghost`, `Danger` across `Sm` (36px), `Md` (44px),
10//!   and `Lg` (50px) heights. Disabled outlined/ghost buttons keep their shape and mute only text.
11//! - Motion:
12//!   - Adaptive press scale (`whileTap`): `0.985` for wide (>220px), `0.96` for compact/icon
13//!     (<=48px), `0.97` otherwise; suppressed for `anchors_layer`, `disabled`, `loading`, and
14//!     `reduce_motion`. Painted in backdrop canvas via `scaled_bounds` so sibling layout never shifts.
15//!   - Label morph width (`useMorphWidth`): springs slot width with `motion.spring.morph` when
16//!     content key changes within a 700ms armed window; first paint snaps cleanly with zero wobble.
17//!   - Label crossfade (`LabelPhase`): incoming text rises `2px → 0px` (`duration.standard` +
18//!     `ease.enter`); icon-only enters via `scale 0.85 → 1.0`.
19//!   - Loading spinner: `ArcPresence` scale `0.6 → 1.0` + `700ms` rotating arc (`PathBuilder`),
20//!     static under `reduce_motion`, while label fades smoothly to `opacity: 0`.
21
22use 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/// Visual hierarchy variant matching Arc `ButtonVariant`.
42#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
43pub enum ButtonVariant {
44    #[default]
45    Primary,
46    Secondary,
47    Ghost,
48    Danger,
49}
50
51/// Control height & horizontal padding preset matching Arc `ButtonSize`.
52#[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
78/// Computes Arc's width-adaptive press scale (`button.tsx` lines 20-25):
79/// compact icon buttons (`<= 48px`) press deeper (`0.96`), wide buttons (`> 220px`) press less
80/// (`0.985`), and standard buttons press to `0.97`.
81pub 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/// Arc `Button` component with adaptive press scale, width-morphing label slot,
119/// loading spinner presence, and full keyboard/accessibility behavior.
120#[derive(IntoElement)]
121pub struct Button {
122    id: ElementId,
123    variant: ButtonVariant,
124    size: ButtonSize,
125    square_size: Option<Pixels>,
126    label: Option<SharedString>,
127    icon_start: Option<IconName>,
128    icon_end: Option<IconName>,
129    custom_child: Option<AnyElement>,
130    content_key_override: Option<SharedString>,
131    loading: bool,
132    disabled: bool,
133    anchors_layer: bool,
134    selected: bool,
135    accessibility_label: Option<SharedString>,
136    tab_index: isize,
137    tab_stop: bool,
138    focus_handle: Option<FocusHandle>,
139    on_click: Option<ClickHandler>,
140}
141
142impl Button {
143    pub fn new(id: impl Into<ElementId>) -> Self {
144        Self {
145            id: id.into(),
146            variant: ButtonVariant::Primary,
147            size: ButtonSize::Md,
148            square_size: None,
149            label: None,
150            icon_start: None,
151            icon_end: None,
152            custom_child: None,
153            content_key_override: None,
154            loading: false,
155            disabled: false,
156            anchors_layer: false,
157            selected: false,
158            accessibility_label: None,
159            tab_index: 0,
160            tab_stop: true,
161            focus_handle: None,
162            on_click: None,
163        }
164    }
165
166    pub fn variant(mut self, variant: ButtonVariant) -> Self {
167        self.variant = variant;
168        self
169    }
170
171    pub fn size(mut self, size: ButtonSize) -> Self {
172        self.size = size;
173        self
174    }
175
176    /// 固定正方形图标按钮,复用相同的按压、焦点和键盘行为。
177    pub fn square(mut self, size: Pixels) -> Self {
178        self.square_size = Some(size);
179        self
180    }
181
182    /// Primary button text label. Changes to this string automatically morph button width via
183    /// `motion.spring.morph` and crossfade cleanly.
184    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
185        self.label = Some(label.into());
186        self
187    }
188
189    /// Optional leading icon (or standalone icon when `.label(...)` is omitted).
190    pub fn icon(mut self, icon: IconName) -> Self {
191        self.icon_start = Some(icon);
192        self
193    }
194
195    /// Optional trailing icon shown after the label.
196    pub fn icon_end(mut self, icon: IconName) -> Self {
197        self.icon_end = Some(icon);
198        self
199    }
200
201    /// Optional custom child element inside the label slot (pair with `.content_key(...)` to
202    /// drive width morphing and crossfade when custom content changes).
203    pub fn child(mut self, element: impl IntoElement) -> Self {
204        self.custom_child = Some(element.into_any_element());
205        self
206    }
207
208    /// Explicit key identifying the current label phase (overrides auto-derived label/icon key).
209    pub fn content_key(mut self, key: impl Into<SharedString>) -> Self {
210        self.content_key_override = Some(key.into());
211        self
212    }
213
214    /// Shows a centered spinning arc and fades the label out while keeping focusable and
215    /// swallowing pointer/keyboard clicks.
216    pub fn loading(mut self, loading: bool) -> Self {
217        self.loading = loading;
218        self
219    }
220
221    pub fn disabled(mut self, disabled: bool) -> Self {
222        self.disabled = disabled;
223        self
224    }
225
226    /// Marks this button as a trigger anchoring a menu, popover, or dialog so press scaling is
227    /// suppressed and floating layers never measure a shrunken anchor.
228    pub fn anchors_layer(mut self, anchors_layer: bool) -> Self {
229        self.anchors_layer = anchors_layer;
230        self
231    }
232
233    /// Persistent selected visual state (e.g. while an anchored popover or menu is open).
234    pub fn selected(mut self, selected: bool) -> Self {
235        self.selected = selected;
236        self
237    }
238
239    /// Explicit accessible name overriding `.label(...)`. Required for icon-only buttons.
240    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
241        self.accessibility_label = Some(label.into());
242        self
243    }
244
245    pub fn tab_index(mut self, tab_index: isize) -> Self {
246        self.tab_index = tab_index;
247        self
248    }
249
250    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
251        self.tab_stop = tab_stop;
252        self
253    }
254
255    pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
256        self.focus_handle = Some(handle.clone());
257        self
258    }
259
260    pub fn on_click(
261        mut self,
262        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
263    ) -> Self {
264        self.on_click = Some(Rc::new(handler));
265        self
266    }
267
268    fn derive_content_key(&self) -> SharedString {
269        if let Some(key) = &self.content_key_override {
270            return key.clone();
271        }
272        let mut out = String::new();
273        if let Some(icon) = self.icon_start {
274            out.push_str(&format!("<{icon:?}>"));
275        }
276        if let Some(label) = &self.label {
277            out.push_str(label.as_ref());
278        }
279        if let Some(icon) = self.icon_end {
280            out.push_str(&format!("<{icon:?}>"));
281        }
282        SharedString::from(out)
283    }
284}
285
286fn paint_spinner_arc(
287    center_x: f32,
288    center_y: f32,
289    radius: f32,
290    angle_rad: f32,
291    color: Hsla,
292    window: &mut Window,
293) {
294    let steps = 20usize;
295    let sweep = std::f32::consts::TAU * 0.72;
296    let mut builder = PathBuilder::stroke(px(1.5));
297    for i in 0..=steps {
298        let a = angle_rad + sweep * (i as f32 / steps as f32);
299        let p = point(
300            px(center_x + radius * a.cos()),
301            px(center_y + radius * a.sin()),
302        );
303        if i == 0 {
304            builder.move_to(p);
305        } else {
306            builder.line_to(p);
307        }
308    }
309    if let Ok(path) = builder.build() {
310        window.paint_path(path, color);
311    }
312}
313
314impl RenderOnce for Button {
315    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
316        let theme = cx.arc_theme().clone();
317        let colors = theme.colors;
318        let motion = theme.motion;
319        let reduced = is_reduced_motion(cx);
320        let now = motion_now(cx);
321
322        let content_key = self.derive_content_key();
323        let is_icon_only = self.label.as_ref().is_none_or(|s| s.trim().is_empty())
324            && self.custom_child.is_none()
325            && (self.icon_start.is_some() || self.icon_end.is_some());
326
327        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-button-state".into());
328        let state = window.use_keyed_state(state_id, cx, |_, _| {
329            ButtonInternalState::new(content_key.clone(), now)
330        });
331
332        // Detect label / icon change to arm width morphing (700ms window) and trigger phase enter.
333        {
334            let prev_key = state.read(cx).last_content_key.clone();
335            if prev_key != content_key {
336                state.update(cx, |s, _| {
337                    s.last_content_key = content_key.clone();
338                    s.morph_armed_until_secs = now + 0.7;
339                    s.phase_started_at_secs = now;
340                });
341            }
342        }
343
344        let snap = state.read(cx).clone();
345        let inert = self.disabled || self.loading;
346
347        // 1. Adaptive press scale (`whileTap` in button.tsx).
348        let button_w = *snap.measured_button_width.borrow();
349        let target_scale = if !inert && !self.anchors_layer && !reduced && snap.pressed {
350            adaptive_press_scale(button_w)
351        } else {
352            1.0
353        };
354        let animated_scale = if reduced {
355            1.0
356        } else {
357            arc_spring(
358                (self.id.clone(), "press-scale"),
359                target_scale,
360                motion.spring.snappy,
361                window,
362                cx,
363            )
364        };
365
366        // 2. Label width morph (`useMorphWidth` in button.tsx).
367        let measured_content_w = *snap.measured_content_width.borrow();
368        let morph_active = !reduced
369            && *snap.has_measured_content.borrow()
370            && measured_content_w > 0.0
371            && now <= snap.morph_armed_until_secs;
372        let morphed_slot_width = if measured_content_w > 0.0 {
373            let sample = arc_spring_with_options(
374                (self.id.clone(), "slot-width"),
375                measured_content_w,
376                SpringOptions::new(motion.spring.morph),
377                window,
378                cx,
379            );
380            if morph_active {
381                Some(sample.value)
382            } else {
383                None
384            }
385        } else {
386            None
387        };
388
389        // 3. Label phase enter crossfade (`LabelPhase` in button.tsx).
390        let phase_elapsed = (now - snap.phase_started_at_secs).max(0.0);
391        let phase_dur = if reduced {
392            motion.duration.instant
393        } else if is_icon_only {
394            motion.duration.fast
395        } else {
396            motion.duration.standard
397        };
398        let (phase_opacity, phase_y) = if phase_elapsed < phase_dur.as_secs_f64() {
399            let t = (phase_elapsed / phase_dur.as_secs_f64()).clamp(0.0, 1.0) as f32;
400            window.request_animation_frame();
401            let eased = if reduced {
402                t
403            } else {
404                CubicBezier::from_spec(motion.ease.enter).sample(t)
405            };
406            let y_off = if reduced || is_icon_only {
407                0.0
408            } else {
409                2.0 * (1.0 - eased)
410            };
411            (eased, y_off)
412        } else {
413            (1.0, 0.0)
414        };
415
416        // 4. Loading spinner presence + label opacity fade.
417        let loader_presence = ArcPresence::new((self.id.clone(), "loader-presence"), self.loading)
418            .animate_initial(false)
419            .config(ArcPresenceConfig {
420                enter_duration: motion.duration.fast,
421                exit_duration: motion.duration.instant,
422                enter_ease: motion.ease.enter,
423                exit_ease: motion.ease.standard,
424                fade_on_reduced_motion: true,
425            })
426            .sample(window, cx);
427        let loader_scale = if reduced {
428            1.0
429        } else {
430            arc_spring(
431                (self.id.clone(), "loader-scale"),
432                if self.loading { 1.0 } else { 0.8 },
433                motion.spring.snappy,
434                window,
435                cx,
436            )
437        };
438        let label_visibility = arc_transition(
439            (self.id.clone(), "label-vis"),
440            if self.loading { 0.0 } else { 1.0 },
441            if reduced {
442                motion.duration.instant
443            } else {
444                motion.duration.fast
445            },
446            motion.ease.standard,
447            window,
448            cx,
449        );
450
451        // 5. Resolve variant colors, borders, shadows, and disabled preservation (`button.module.css`).
452        let is_hover = !inert && snap.hovered;
453        let is_press = !inert && snap.pressed;
454        let (mut bg, border, fg, show_shadow, root_opacity) = match self.variant {
455            ButtonVariant::Primary => {
456                if self.disabled {
457                    (
458                        colors.foreground,
459                        colors.foreground,
460                        colors.background,
461                        false,
462                        0.52_f32,
463                    )
464                } else {
465                    let op = if is_press {
466                        0.84
467                    } else if is_hover {
468                        0.91
469                    } else {
470                        1.0
471                    };
472                    (
473                        colors.foreground,
474                        colors.foreground,
475                        colors.background,
476                        is_hover && !is_press,
477                        op,
478                    )
479                }
480            }
481            ButtonVariant::Secondary => {
482                if self.disabled {
483                    (
484                        colors.surface_muted,
485                        colors.border,
486                        colors.text_muted,
487                        false,
488                        1.0,
489                    )
490                } else {
491                    let surface = if is_press || is_hover || self.selected {
492                        colors.surface_muted
493                    } else {
494                        colors.surface
495                    };
496                    (
497                        surface,
498                        colors.border,
499                        colors.foreground,
500                        is_hover && !is_press,
501                        1.0,
502                    )
503                }
504            }
505            ButtonVariant::Ghost => {
506                if self.disabled {
507                    (
508                        Hsla::transparent_black(),
509                        Hsla::transparent_black(),
510                        colors.text_muted,
511                        false,
512                        1.0,
513                    )
514                } else if is_press || is_hover || self.selected {
515                    (
516                        colors.surface_muted,
517                        Hsla::transparent_black(),
518                        colors.foreground,
519                        false,
520                        1.0,
521                    )
522                } else {
523                    (
524                        Hsla::transparent_black(),
525                        Hsla::transparent_black(),
526                        colors.text_secondary,
527                        false,
528                        1.0,
529                    )
530                }
531            }
532            ButtonVariant::Danger => {
533                if self.disabled {
534                    (
535                        colors.surface_muted,
536                        colors.border,
537                        oklab_mix(colors.danger, colors.surface_muted, 0.55),
538                        false,
539                        1.0,
540                    )
541                } else if is_press || is_hover {
542                    (
543                        colors.surface_muted,
544                        colors.danger,
545                        colors.danger,
546                        false,
547                        1.0,
548                    )
549                } else {
550                    (colors.surface, colors.border, colors.danger, false, 1.0)
551                }
552            }
553        };
554        if self.variant == ButtonVariant::Primary && root_opacity < 1.0 && !self.disabled {
555            bg.a *= root_opacity;
556        }
557
558        // Backdrop canvas paints the scaled button surface & shadow without reflowing siblings.
559        let btn_w_ref = snap.measured_button_width.clone();
560        let resting_shadows = Shadows::resting(theme.mode);
561        let backdrop_canvas = canvas(
562            move |rect, _, _| {
563                *btn_w_ref.borrow_mut() = f32::from(rect.size.width);
564            },
565            move |rect, _, window, _| {
566                let paint_rect = scaled_bounds(
567                    rect,
568                    animated_scale,
569                    animated_scale,
570                    TransformOrigin::CENTER,
571                );
572                let radii = Corners::all(Radii::CONTROL);
573                if show_shadow {
574                    window.paint_drop_shadows(paint_rect, radii, &resting_shadows);
575                }
576                if bg.a > 0.0 || border.a > 0.0 {
577                    window.paint_quad(quad(
578                        paint_rect,
579                        radii,
580                        bg,
581                        Edges::all(px(1.0)),
582                        border,
583                        BorderStyle::Solid,
584                    ));
585                }
586            },
587        )
588        .absolute()
589        .inset_0();
590
591        // Measure natural label content width so width morphing springs to the exact incoming size.
592        let content_w_ref = snap.measured_content_width.clone();
593        let has_measured_ref = snap.has_measured_content.clone();
594        let content_measure = canvas(
595            move |rect, window, _| {
596                let next_w = f32::from(rect.size.width);
597                let prev_w = *content_w_ref.borrow();
598                *content_w_ref.borrow_mut() = next_w;
599                if next_w > 0.0 {
600                    *has_measured_ref.borrow_mut() = true;
601                }
602                if (next_w - prev_w).abs() > 0.5 && prev_w > 0.0 {
603                    window.request_animation_frame();
604                }
605            },
606            |_, _, _, _| {},
607        )
608        .absolute()
609        .inset_0();
610
611        let label_content = div()
612            .relative()
613            .flex_none()
614            .flex()
615            .flex_row()
616            .items_center()
617            .justify_center()
618            .gap(Spacing::S2)
619            .mt(px(phase_y))
620            .opacity((phase_opacity * label_visibility).clamp(0.0, 1.0))
621            .child(content_measure)
622            .when_some(self.icon_start, |this, icon| this.child(icon))
623            .when_some(self.label.clone(), |this, text| this.child(text))
624            .when_some(self.custom_child, |this, elem| this.child(elem))
625            .when_some(self.icon_end, |this, icon| this.child(icon));
626
627        let label_slot = div()
628            .relative()
629            .flex()
630            .items_center()
631            .justify_center()
632            .when_some(morphed_slot_width, |this, w| {
633                this.w(px(w)).overflow_hidden()
634            })
635            .child(label_content);
636
637        // Centered rotating loading arc (700ms linear loop, static under reduce_motion).
638        let spinner_overlay = if loader_presence.should_render() {
639            let spinner_op = loader_presence.progress.clamp(0.0, 1.0);
640            let spinner_color = Hsla {
641                a: fg.a * spinner_op,
642                ..fg
643            };
644            let spin_angle = if reduced {
645                0.0
646            } else {
647                window.request_animation_frame();
648                ((now % 0.7) / 0.7) as f32 * std::f32::consts::TAU
649            };
650            let radius = 6.5 * loader_scale.clamp(0.6, 1.05);
651            Some(
652                div()
653                    .absolute()
654                    .inset_0()
655                    .flex()
656                    .items_center()
657                    .justify_center()
658                    .child(
659                        canvas(
660                            |_, _, _| {},
661                            move |rect, _, window, _| {
662                                let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
663                                let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
664                                paint_spinner_arc(
665                                    cx,
666                                    cy,
667                                    radius,
668                                    spin_angle,
669                                    spinner_color,
670                                    window,
671                                );
672                            },
673                        )
674                        .size(Spacing::S4),
675                    ),
676            )
677        } else {
678            None
679        };
680
681        let a11y_label = self
682            .accessibility_label
683            .clone()
684            .or_else(|| self.label.clone());
685
686        let state_hover = state.clone();
687        let state_down = state.clone();
688        let state_up = state.clone();
689        let state_up_out = state.clone();
690        let state_kd = state.clone();
691        let state_ku = state.clone();
692        let is_loading = self.loading;
693        let is_disabled = self.disabled;
694        let on_click = self.on_click;
695
696        let mut base = BaseButton::new(self.id.clone())
697            .disabled(self.disabled)
698            .tab_index(self.tab_index)
699            .tab_stop(self.tab_stop);
700
701        if let Some(label) = a11y_label {
702            base = base.accessibility_label(label);
703        }
704        if let Some(handle) = &self.focus_handle {
705            base = base.track_focus(handle);
706        }
707        if let Some(handler) = on_click {
708            base = base.on_click(move |event, window, cx| {
709                // Loading keeps focusable but swallows presses (matches button.tsx line 114).
710                if is_loading || is_disabled {
711                    return;
712                }
713                handler(event, window, cx);
714            });
715        }
716
717        let pad_x = if is_icon_only {
718            Spacing::S2
719        } else {
720            self.size.padding_x()
721        };
722
723        base.relative()
724            .self_start()
725            .flex()
726            .flex_row()
727            .items_center()
728            .justify_center()
729            .min_h(self.size.min_height())
730            .when(is_icon_only, |this| this.min_w(self.size.min_height()))
731            .px(pad_x)
732            .when_some(self.square_size, |this, side| {
733                this.w(side).h(side).min_w(side).min_h(side).px_0()
734            })
735            .rounded(Radii::CONTROL)
736            .text_size(Typography::TEXT_SM)
737            .text_color(fg)
738            .when(
739                self.disabled && self.variant == ButtonVariant::Primary,
740                |this| this.opacity(0.52),
741            )
742            .when(!inert, |this| this.cursor_pointer())
743            .on_hover(move |hovered, window, cx| {
744                state_hover.update(cx, |s, _| {
745                    s.hovered = *hovered;
746                    if !*hovered {
747                        s.pressed = false;
748                    }
749                });
750                window.refresh();
751            })
752            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
753                if inert {
754                    return;
755                }
756                state_down.update(cx, |s, _| s.pressed = true);
757                window.refresh();
758            })
759            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
760                state_up.update(cx, |s, _| s.pressed = false);
761                window.refresh();
762            })
763            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
764                state_up_out.update(cx, |s, _| s.pressed = false);
765                window.refresh();
766            })
767            .on_key_down(move |event: &KeyDownEvent, window, cx| {
768                if inert {
769                    return;
770                }
771                if event.keystroke.key == "space" || event.keystroke.key == "enter" {
772                    state_kd.update(cx, |s, _| s.pressed = true);
773                    window.refresh();
774                }
775            })
776            .on_key_up(move |event: &KeyUpEvent, window, cx| {
777                if event.keystroke.key == "space" || event.keystroke.key == "enter" {
778                    state_ku.update(cx, |s, _| s.pressed = false);
779                    window.refresh();
780                }
781            })
782            .child(backdrop_canvas)
783            .child(label_slot)
784            .when_some(spinner_overlay, |this, loader| this.child(loader))
785    }
786}
787
788#[cfg(test)]
789mod tests {
790    use std::{cell::Cell, rc::Rc};
791
792    use arc_motion::{
793        CurveTrace, ReducedMotionChoice, SpringSolver, max_curve_error_pct, set_reduced_motion,
794    };
795    use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
796    use gpui_kit::{
797        Context, MouseButton, Render, Role, TestAppContext, div,
798        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
799    };
800
801    use super::*;
802
803    struct ButtonHost {
804        clicks: Rc<Cell<usize>>,
805        loading: bool,
806        disabled: bool,
807        label: SharedString,
808    }
809
810    impl Render for ButtonHost {
811        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
812            let clicks = self.clicks.clone();
813            div().p(Spacing::S4).child(
814                Button::new("save-btn")
815                    .variant(ButtonVariant::Primary)
816                    .size(ButtonSize::Md)
817                    .label(self.label.clone())
818                    .loading(self.loading)
819                    .disabled(self.disabled)
820                    .on_click(cx.listener(move |_, _, _, _| {
821                        clicks.set(clicks.get() + 1);
822                    })),
823            )
824        }
825    }
826
827    #[gpui_kit::test]
828    fn button_click_keyboard_loading_swallow_and_disabled(cx: &mut TestAppContext) {
829        cx.update(|cx| {
830            gpui_kit::init(cx);
831            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
832        });
833
834        let clicks = Rc::new(Cell::new(0usize));
835        let (view, cx) = cx.add_window_view(|_, _| ButtonHost {
836            clicks: clicks.clone(),
837            loading: false,
838            disabled: false,
839            label: "Save".into(),
840        });
841
842        cx.update(|window, cx| {
843            window.render_frame(cx);
844            let btn = window.find_by_label("Save");
845            assert_eq!(btn.role(), Some(Role::Button));
846            assert_ne!(btn.disabled(), Some(true));
847
848            // Click activates
849            let center = btn.bounds().center();
850            window.pointer_down(center, MouseButton::Left, cx);
851            window.pointer_up(center, MouseButton::Left, cx);
852            assert_eq!(clicks.get(), 1);
853
854            // Keyboard Space activates focused button
855            window.press("space", cx);
856            assert_eq!(clicks.get(), 2);
857        });
858
859        // Loading keeps button focusable (not disabled) but swallows clicks
860        view.update(cx, |v, cx| {
861            v.loading = true;
862            cx.notify();
863        });
864        cx.update(|window, cx| {
865            window.render_frame(cx);
866            let btn = window.find_by_label("Save");
867            assert_ne!(btn.disabled(), Some(true));
868            let center = btn.bounds().center();
869            window.pointer_down(center, MouseButton::Left, cx);
870            window.pointer_up(center, MouseButton::Left, cx);
871            assert_eq!(clicks.get(), 2);
872        });
873
874        // Disabled blocks clicks and reports disabled to AccessKit
875        view.update(cx, |v, cx| {
876            v.loading = false;
877            v.disabled = true;
878            cx.notify();
879        });
880        cx.update(|window, cx| {
881            window.render_frame(cx);
882            let btn = window.find_by_label("Save");
883            assert_eq!(btn.disabled(), Some(true));
884            let center = btn.bounds().center();
885            window.pointer_down(center, MouseButton::Left, cx);
886            window.pointer_up(center, MouseButton::Left, cx);
887            assert_eq!(clicks.get(), 2);
888        });
889    }
890
891    #[test]
892    fn adaptive_press_scale_matches_arc_width_breakpoints() {
893        assert!((adaptive_press_scale(36.0) - 0.96).abs() < 1e-6);
894        assert!((adaptive_press_scale(48.0) - 0.96).abs() < 1e-6);
895        assert!((adaptive_press_scale(120.0) - 0.97).abs() < 1e-6);
896        assert!((adaptive_press_scale(220.0) - 0.97).abs() < 1e-6);
897        assert!((adaptive_press_scale(260.0) - 0.985).abs() < 1e-6);
898    }
899
900    #[test]
901    fn button_width_morph_spring_matches_motion_reference_within_5_percent() {
902        let spec = ArcMotionTokens::DEFAULT.spring.morph;
903        let solver = SpringSolver::new(spec, 60.0, 128.0, 0.0);
904        let omega0 = std::f64::consts::TAU / (0.42 * 1.2);
905        let mut actual = CurveTrace::new("button", "slot_width");
906        let mut expected = CurveTrace::new("button", "slot_width");
907        for frame in 0..=45 {
908            let t_ms = frame as f64 * 16.0;
909            let t = t_ms / 1000.0;
910            let ref_w = 128.0 - (-omega0 * t).exp() * (68.0 + omega0 * 68.0 * t);
911            expected.push(t_ms, ref_w);
912            actual.push(t_ms, f64::from(solver.sample(t).value));
913        }
914        let err = max_curve_error_pct(&actual, &expected);
915        assert!(err < 5.0, "Button width morph error {err:.3}% >= 5%");
916        assert!(
917            err < 1.0,
918            "Expected tight morph spring match, got {err:.3}%"
919        );
920    }
921
922    #[gpui_kit::test]
923    fn button_reduced_motion_and_label_morph_do_not_crash(cx: &mut TestAppContext) {
924        cx.update(|cx| {
925            gpui_kit::init(cx);
926            install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
927            set_reduced_motion(ReducedMotionChoice::Reduce, cx);
928        });
929        let (view, cx) = cx.add_window_view(|_, _| ButtonHost {
930            clicks: Rc::new(Cell::new(0)),
931            loading: false,
932            disabled: false,
933            label: "Save".into(),
934        });
935        cx.update(|window, cx| {
936            window.render_frame(cx);
937        });
938        view.update(cx, |v, cx| {
939            v.label = "Saved changes".into();
940            cx.notify();
941        });
942        cx.update(|window, cx| {
943            window.render_frame(cx);
944            assert_eq!(
945                window.find_by_label("Saved changes").role(),
946                Some(Role::Button)
947            );
948        });
949    }
950}