arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/button/button.tsx` & `button.module.css`
//!
//! P2 Component #1: `button`
//!
//! - Behavior & Accessibility: `gpui_kit::base::Button` (`Role::Button`, focus handle,
//!   Enter/Space keyboard activation, disabled semantics). Loading keeps the button focusable
//!   (preventing mid-action focus loss) while swallowing clicks.
//! - Visual Variants: `Primary`, `Secondary`, `Ghost`, `Danger` across `Sm` (36px), `Md` (44px),
//!   and `Lg` (50px) heights. Disabled outlined/ghost buttons keep their shape and mute only text.
//! - Motion:
//!   - Adaptive press scale (`whileTap`): `0.985` for wide (>220px), `0.96` for compact/icon
//!     (<=48px), `0.97` otherwise; suppressed for `anchors_layer`, `disabled`, `loading`, and
//!     `reduce_motion`. Painted in backdrop canvas via `scaled_bounds` so sibling layout never shifts.
//!   - Label morph width (`useMorphWidth`): springs slot width with `motion.spring.morph` when
//!     content key changes within a 700ms armed window; first paint snaps cleanly with zero wobble.
//!   - Label crossfade (`LabelPhase`): incoming text rises `2px → 0px` (`duration.standard` +
//!     `ease.enter`); icon-only enters via `scale 0.85 → 1.0`.
//!   - Loading spinner: `ArcPresence` scale `0.6 → 1.0` + `700ms` rotating arc (`PathBuilder`),
//!     static under `reduce_motion`, while label fades smoothly to `opacity: 0`.

use std::{cell::RefCell, rc::Rc};

use arc_motion::{
    ArcPresence, ArcPresenceConfig, CubicBezier, TransformOrigin, arc_spring,
    arc_spring_with_options, arc_transition, is_reduced_motion, motion_now, scaled_bounds,
    spring::SpringOptions,
};
use arc_tokens::{
    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
};
use gpui_kit::{
    AnyElement, App, BorderStyle, ClickEvent, Corners, Edges, ElementId, FocusHandle, Hsla,
    IntoElement, KeyDownEvent, KeyUpEvent, MouseButton, ParentElement, PathBuilder, Pixels,
    RenderOnce, SharedString, Styled, Window, assets::IconName, base::Button as BaseButton, canvas,
    div, point, prelude::*, px, quad,
};

type ClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;

/// Visual hierarchy variant matching Arc `ButtonVariant`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ButtonVariant {
    #[default]
    Primary,
    Secondary,
    Ghost,
    Danger,
}

/// Control height & horizontal padding preset matching Arc `ButtonSize`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ButtonSize {
    Sm,
    #[default]
    Md,
    Lg,
}

impl ButtonSize {
    pub const fn min_height(self) -> Pixels {
        match self {
            Self::Sm => ControlHeights::SM,
            Self::Md => ControlHeights::MD,
            Self::Lg => ControlHeights::LG,
        }
    }

    pub const fn padding_x(self) -> Pixels {
        match self {
            Self::Sm => px(10.0),
            Self::Md => Spacing::S3,
            Self::Lg => Spacing::S4,
        }
    }
}

/// Computes Arc's width-adaptive press scale (`button.tsx` lines 20-25):
/// compact icon buttons (`<= 48px`) press deeper (`0.96`), wide buttons (`> 220px`) press less
/// (`0.985`), and standard buttons press to `0.97`.
pub fn adaptive_press_scale(button_width_px: f32) -> f32 {
    if button_width_px > 220.0 {
        0.985
    } else if button_width_px > 0.0 && button_width_px <= 48.0 {
        0.96
    } else {
        0.97
    }
}

#[derive(Clone)]
struct ButtonInternalState {
    pressed: bool,
    hovered: bool,
    last_content_key: SharedString,
    morph_armed_until_secs: f64,
    phase_started_at_secs: f64,
    measured_button_width: Rc<RefCell<f32>>,
    measured_content_width: Rc<RefCell<f32>>,
    has_measured_content: Rc<RefCell<bool>>,
}

impl ButtonInternalState {
    fn new(initial_key: SharedString, now: f64) -> Self {
        Self {
            pressed: false,
            hovered: false,
            last_content_key: initial_key,
            morph_armed_until_secs: f64::NEG_INFINITY,
            phase_started_at_secs: now - 10.0,
            measured_button_width: Rc::new(RefCell::new(0.0)),
            measured_content_width: Rc::new(RefCell::new(0.0)),
            has_measured_content: Rc::new(RefCell::new(false)),
        }
    }
}

/// Arc `Button` component with adaptive press scale, width-morphing label slot,
/// loading spinner presence, and full keyboard/accessibility behavior.
#[derive(IntoElement)]
pub struct Button {
    id: ElementId,
    variant: ButtonVariant,
    size: ButtonSize,
    square_size: Option<Pixels>,
    label: Option<SharedString>,
    icon_start: Option<IconName>,
    icon_end: Option<IconName>,
    custom_child: Option<AnyElement>,
    content_key_override: Option<SharedString>,
    loading: bool,
    disabled: bool,
    anchors_layer: bool,
    selected: bool,
    accessibility_label: Option<SharedString>,
    tab_index: isize,
    tab_stop: bool,
    focus_handle: Option<FocusHandle>,
    on_click: Option<ClickHandler>,
}

impl Button {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            variant: ButtonVariant::Primary,
            size: ButtonSize::Md,
            square_size: None,
            label: None,
            icon_start: None,
            icon_end: None,
            custom_child: None,
            content_key_override: None,
            loading: false,
            disabled: false,
            anchors_layer: false,
            selected: false,
            accessibility_label: None,
            tab_index: 0,
            tab_stop: true,
            focus_handle: None,
            on_click: None,
        }
    }

    pub fn variant(mut self, variant: ButtonVariant) -> Self {
        self.variant = variant;
        self
    }

    pub fn size(mut self, size: ButtonSize) -> Self {
        self.size = size;
        self
    }

    /// 固定正方形图标按钮,复用相同的按压、焦点和键盘行为。
    pub fn square(mut self, size: Pixels) -> Self {
        self.square_size = Some(size);
        self
    }

    /// Primary button text label. Changes to this string automatically morph button width via
    /// `motion.spring.morph` and crossfade cleanly.
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Optional leading icon (or standalone icon when `.label(...)` is omitted).
    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon_start = Some(icon);
        self
    }

    /// Optional trailing icon shown after the label.
    pub fn icon_end(mut self, icon: IconName) -> Self {
        self.icon_end = Some(icon);
        self
    }

    /// Optional custom child element inside the label slot (pair with `.content_key(...)` to
    /// drive width morphing and crossfade when custom content changes).
    pub fn child(mut self, element: impl IntoElement) -> Self {
        self.custom_child = Some(element.into_any_element());
        self
    }

    /// Explicit key identifying the current label phase (overrides auto-derived label/icon key).
    pub fn content_key(mut self, key: impl Into<SharedString>) -> Self {
        self.content_key_override = Some(key.into());
        self
    }

    /// Shows a centered spinning arc and fades the label out while keeping focusable and
    /// swallowing pointer/keyboard clicks.
    pub fn loading(mut self, loading: bool) -> Self {
        self.loading = loading;
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Marks this button as a trigger anchoring a menu, popover, or dialog so press scaling is
    /// suppressed and floating layers never measure a shrunken anchor.
    pub fn anchors_layer(mut self, anchors_layer: bool) -> Self {
        self.anchors_layer = anchors_layer;
        self
    }

    /// Persistent selected visual state (e.g. while an anchored popover or menu is open).
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }

    /// Explicit accessible name overriding `.label(...)`. Required for icon-only buttons.
    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
        self.accessibility_label = Some(label.into());
        self
    }

    pub fn tab_index(mut self, tab_index: isize) -> Self {
        self.tab_index = tab_index;
        self
    }

    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
        self.tab_stop = tab_stop;
        self
    }

    pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
        self.focus_handle = Some(handle.clone());
        self
    }

    pub fn on_click(
        mut self,
        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_click = Some(Rc::new(handler));
        self
    }

    fn derive_content_key(&self) -> SharedString {
        if let Some(key) = &self.content_key_override {
            return key.clone();
        }
        let mut out = String::new();
        if let Some(icon) = self.icon_start {
            out.push_str(&format!("<{icon:?}>"));
        }
        if let Some(label) = &self.label {
            out.push_str(label.as_ref());
        }
        if let Some(icon) = self.icon_end {
            out.push_str(&format!("<{icon:?}>"));
        }
        SharedString::from(out)
    }
}

fn paint_spinner_arc(
    center_x: f32,
    center_y: f32,
    radius: f32,
    angle_rad: f32,
    color: Hsla,
    window: &mut Window,
) {
    let steps = 20usize;
    let sweep = std::f32::consts::TAU * 0.72;
    let mut builder = PathBuilder::stroke(px(1.5));
    for i in 0..=steps {
        let a = angle_rad + sweep * (i as f32 / steps as f32);
        let p = point(
            px(center_x + radius * a.cos()),
            px(center_y + radius * a.sin()),
        );
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    if let Ok(path) = builder.build() {
        window.paint_path(path, color);
    }
}

impl RenderOnce for Button {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let content_key = self.derive_content_key();
        let is_icon_only = self.label.as_ref().is_none_or(|s| s.trim().is_empty())
            && self.custom_child.is_none()
            && (self.icon_start.is_some() || self.icon_end.is_some());

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-button-state".into());
        let state = window.use_keyed_state(state_id, cx, |_, _| {
            ButtonInternalState::new(content_key.clone(), now)
        });

        // Detect label / icon change to arm width morphing (700ms window) and trigger phase enter.
        {
            let prev_key = state.read(cx).last_content_key.clone();
            if prev_key != content_key {
                state.update(cx, |s, _| {
                    s.last_content_key = content_key.clone();
                    s.morph_armed_until_secs = now + 0.7;
                    s.phase_started_at_secs = now;
                });
            }
        }

        let snap = state.read(cx).clone();
        let inert = self.disabled || self.loading;

        // 1. Adaptive press scale (`whileTap` in button.tsx).
        let button_w = *snap.measured_button_width.borrow();
        let target_scale = if !inert && !self.anchors_layer && !reduced && snap.pressed {
            adaptive_press_scale(button_w)
        } else {
            1.0
        };
        let animated_scale = if reduced {
            1.0
        } else {
            arc_spring(
                (self.id.clone(), "press-scale"),
                target_scale,
                motion.spring.snappy,
                window,
                cx,
            )
        };

        // 2. Label width morph (`useMorphWidth` in button.tsx).
        let measured_content_w = *snap.measured_content_width.borrow();
        let morph_active = !reduced
            && *snap.has_measured_content.borrow()
            && measured_content_w > 0.0
            && now <= snap.morph_armed_until_secs;
        let morphed_slot_width = if measured_content_w > 0.0 {
            let sample = arc_spring_with_options(
                (self.id.clone(), "slot-width"),
                measured_content_w,
                SpringOptions::new(motion.spring.morph),
                window,
                cx,
            );
            if morph_active {
                Some(sample.value)
            } else {
                None
            }
        } else {
            None
        };

        // 3. Label phase enter crossfade (`LabelPhase` in button.tsx).
        let phase_elapsed = (now - snap.phase_started_at_secs).max(0.0);
        let phase_dur = if reduced {
            motion.duration.instant
        } else if is_icon_only {
            motion.duration.fast
        } else {
            motion.duration.standard
        };
        let (phase_opacity, phase_y) = if phase_elapsed < phase_dur.as_secs_f64() {
            let t = (phase_elapsed / phase_dur.as_secs_f64()).clamp(0.0, 1.0) as f32;
            window.request_animation_frame();
            let eased = if reduced {
                t
            } else {
                CubicBezier::from_spec(motion.ease.enter).sample(t)
            };
            let y_off = if reduced || is_icon_only {
                0.0
            } else {
                2.0 * (1.0 - eased)
            };
            (eased, y_off)
        } else {
            (1.0, 0.0)
        };

        // 4. Loading spinner presence + label opacity fade.
        let loader_presence = ArcPresence::new((self.id.clone(), "loader-presence"), self.loading)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.fast,
                exit_duration: motion.duration.instant,
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);
        let loader_scale = if reduced {
            1.0
        } else {
            arc_spring(
                (self.id.clone(), "loader-scale"),
                if self.loading { 1.0 } else { 0.8 },
                motion.spring.snappy,
                window,
                cx,
            )
        };
        let label_visibility = arc_transition(
            (self.id.clone(), "label-vis"),
            if self.loading { 0.0 } else { 1.0 },
            if reduced {
                motion.duration.instant
            } else {
                motion.duration.fast
            },
            motion.ease.standard,
            window,
            cx,
        );

        // 5. Resolve variant colors, borders, shadows, and disabled preservation (`button.module.css`).
        let is_hover = !inert && snap.hovered;
        let is_press = !inert && snap.pressed;
        let (mut bg, border, fg, show_shadow, root_opacity) = match self.variant {
            ButtonVariant::Primary => {
                if self.disabled {
                    (
                        colors.foreground,
                        colors.foreground,
                        colors.background,
                        false,
                        0.52_f32,
                    )
                } else {
                    let op = if is_press {
                        0.84
                    } else if is_hover {
                        0.91
                    } else {
                        1.0
                    };
                    (
                        colors.foreground,
                        colors.foreground,
                        colors.background,
                        is_hover && !is_press,
                        op,
                    )
                }
            }
            ButtonVariant::Secondary => {
                if self.disabled {
                    (
                        colors.surface_muted,
                        colors.border,
                        colors.text_muted,
                        false,
                        1.0,
                    )
                } else {
                    let surface = if is_press || is_hover || self.selected {
                        colors.surface_muted
                    } else {
                        colors.surface
                    };
                    (
                        surface,
                        colors.border,
                        colors.foreground,
                        is_hover && !is_press,
                        1.0,
                    )
                }
            }
            ButtonVariant::Ghost => {
                if self.disabled {
                    (
                        Hsla::transparent_black(),
                        Hsla::transparent_black(),
                        colors.text_muted,
                        false,
                        1.0,
                    )
                } else if is_press || is_hover || self.selected {
                    (
                        colors.surface_muted,
                        Hsla::transparent_black(),
                        colors.foreground,
                        false,
                        1.0,
                    )
                } else {
                    (
                        Hsla::transparent_black(),
                        Hsla::transparent_black(),
                        colors.text_secondary,
                        false,
                        1.0,
                    )
                }
            }
            ButtonVariant::Danger => {
                if self.disabled {
                    (
                        colors.surface_muted,
                        colors.border,
                        oklab_mix(colors.danger, colors.surface_muted, 0.55),
                        false,
                        1.0,
                    )
                } else if is_press || is_hover {
                    (
                        colors.surface_muted,
                        colors.danger,
                        colors.danger,
                        false,
                        1.0,
                    )
                } else {
                    (colors.surface, colors.border, colors.danger, false, 1.0)
                }
            }
        };
        if self.variant == ButtonVariant::Primary && root_opacity < 1.0 && !self.disabled {
            bg.a *= root_opacity;
        }

        // Backdrop canvas paints the scaled button surface & shadow without reflowing siblings.
        let btn_w_ref = snap.measured_button_width.clone();
        let resting_shadows = Shadows::resting(theme.mode);
        let backdrop_canvas = canvas(
            move |rect, _, _| {
                *btn_w_ref.borrow_mut() = f32::from(rect.size.width);
            },
            move |rect, _, window, _| {
                let paint_rect = scaled_bounds(
                    rect,
                    animated_scale,
                    animated_scale,
                    TransformOrigin::CENTER,
                );
                let radii = Corners::all(Radii::CONTROL);
                if show_shadow {
                    window.paint_drop_shadows(paint_rect, radii, &resting_shadows);
                }
                if bg.a > 0.0 || border.a > 0.0 {
                    window.paint_quad(quad(
                        paint_rect,
                        radii,
                        bg,
                        Edges::all(px(1.0)),
                        border,
                        BorderStyle::Solid,
                    ));
                }
            },
        )
        .absolute()
        .inset_0();

        // Measure natural label content width so width morphing springs to the exact incoming size.
        let content_w_ref = snap.measured_content_width.clone();
        let has_measured_ref = snap.has_measured_content.clone();
        let content_measure = canvas(
            move |rect, window, _| {
                let next_w = f32::from(rect.size.width);
                let prev_w = *content_w_ref.borrow();
                *content_w_ref.borrow_mut() = next_w;
                if next_w > 0.0 {
                    *has_measured_ref.borrow_mut() = true;
                }
                if (next_w - prev_w).abs() > 0.5 && prev_w > 0.0 {
                    window.request_animation_frame();
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();

        let label_content = div()
            .relative()
            .flex_none()
            .flex()
            .flex_row()
            .items_center()
            .justify_center()
            .gap(Spacing::S2)
            .mt(px(phase_y))
            .opacity((phase_opacity * label_visibility).clamp(0.0, 1.0))
            .child(content_measure)
            .when_some(self.icon_start, |this, icon| this.child(icon))
            .when_some(self.label.clone(), |this, text| this.child(text))
            .when_some(self.custom_child, |this, elem| this.child(elem))
            .when_some(self.icon_end, |this, icon| this.child(icon));

        let label_slot = div()
            .relative()
            .flex()
            .items_center()
            .justify_center()
            .when_some(morphed_slot_width, |this, w| {
                this.w(px(w)).overflow_hidden()
            })
            .child(label_content);

        // Centered rotating loading arc (700ms linear loop, static under reduce_motion).
        let spinner_overlay = if loader_presence.should_render() {
            let spinner_op = loader_presence.progress.clamp(0.0, 1.0);
            let spinner_color = Hsla {
                a: fg.a * spinner_op,
                ..fg
            };
            let spin_angle = if reduced {
                0.0
            } else {
                window.request_animation_frame();
                ((now % 0.7) / 0.7) as f32 * std::f32::consts::TAU
            };
            let radius = 6.5 * loader_scale.clamp(0.6, 1.05);
            Some(
                div()
                    .absolute()
                    .inset_0()
                    .flex()
                    .items_center()
                    .justify_center()
                    .child(
                        canvas(
                            |_, _, _| {},
                            move |rect, _, window, _| {
                                let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
                                let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
                                paint_spinner_arc(
                                    cx,
                                    cy,
                                    radius,
                                    spin_angle,
                                    spinner_color,
                                    window,
                                );
                            },
                        )
                        .size(Spacing::S4),
                    ),
            )
        } else {
            None
        };

        let a11y_label = self
            .accessibility_label
            .clone()
            .or_else(|| self.label.clone());

        let state_hover = state.clone();
        let state_down = state.clone();
        let state_up = state.clone();
        let state_up_out = state.clone();
        let state_kd = state.clone();
        let state_ku = state.clone();
        let is_loading = self.loading;
        let is_disabled = self.disabled;
        let on_click = self.on_click;

        let mut base = BaseButton::new(self.id.clone())
            .disabled(self.disabled)
            .tab_index(self.tab_index)
            .tab_stop(self.tab_stop);

        if let Some(label) = a11y_label {
            base = base.accessibility_label(label);
        }
        if let Some(handle) = &self.focus_handle {
            base = base.track_focus(handle);
        }
        if let Some(handler) = on_click {
            base = base.on_click(move |event, window, cx| {
                // Loading keeps focusable but swallows presses (matches button.tsx line 114).
                if is_loading || is_disabled {
                    return;
                }
                handler(event, window, cx);
            });
        }

        let pad_x = if is_icon_only {
            Spacing::S2
        } else {
            self.size.padding_x()
        };

        base.relative()
            .self_start()
            .flex()
            .flex_row()
            .items_center()
            .justify_center()
            .min_h(self.size.min_height())
            .when(is_icon_only, |this| this.min_w(self.size.min_height()))
            .px(pad_x)
            .when_some(self.square_size, |this, side| {
                this.w(side).h(side).min_w(side).min_h(side).px_0()
            })
            .rounded(Radii::CONTROL)
            .text_size(Typography::TEXT_SM)
            .text_color(fg)
            .when(
                self.disabled && self.variant == ButtonVariant::Primary,
                |this| this.opacity(0.52),
            )
            .when(!inert, |this| this.cursor_pointer())
            .on_hover(move |hovered, window, cx| {
                state_hover.update(cx, |s, _| {
                    s.hovered = *hovered;
                    if !*hovered {
                        s.pressed = false;
                    }
                });
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                if inert {
                    return;
                }
                state_down.update(cx, |s, _| s.pressed = true);
                window.refresh();
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                state_up.update(cx, |s, _| s.pressed = false);
                window.refresh();
            })
            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                state_up_out.update(cx, |s, _| s.pressed = false);
                window.refresh();
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if inert {
                    return;
                }
                if event.keystroke.key == "space" || event.keystroke.key == "enter" {
                    state_kd.update(cx, |s, _| s.pressed = true);
                    window.refresh();
                }
            })
            .on_key_up(move |event: &KeyUpEvent, window, cx| {
                if event.keystroke.key == "space" || event.keystroke.key == "enter" {
                    state_ku.update(cx, |s, _| s.pressed = false);
                    window.refresh();
                }
            })
            .child(backdrop_canvas)
            .child(label_slot)
            .when_some(spinner_overlay, |this, loader| this.child(loader))
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use arc_motion::{
        CurveTrace, ReducedMotionChoice, SpringSolver, max_curve_error_pct, set_reduced_motion,
    };
    use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, MouseButton, Render, Role, TestAppContext, div,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    struct ButtonHost {
        clicks: Rc<Cell<usize>>,
        loading: bool,
        disabled: bool,
        label: SharedString,
    }

    impl Render for ButtonHost {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let clicks = self.clicks.clone();
            div().p(Spacing::S4).child(
                Button::new("save-btn")
                    .variant(ButtonVariant::Primary)
                    .size(ButtonSize::Md)
                    .label(self.label.clone())
                    .loading(self.loading)
                    .disabled(self.disabled)
                    .on_click(cx.listener(move |_, _, _, _| {
                        clicks.set(clicks.get() + 1);
                    })),
            )
        }
    }

    #[gpui_kit::test]
    fn button_click_keyboard_loading_swallow_and_disabled(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let clicks = Rc::new(Cell::new(0usize));
        let (view, cx) = cx.add_window_view(|_, _| ButtonHost {
            clicks: clicks.clone(),
            loading: false,
            disabled: false,
            label: "Save".into(),
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let btn = window.find_by_label("Save");
            assert_eq!(btn.role(), Some(Role::Button));
            assert_ne!(btn.disabled(), Some(true));

            // Click activates
            let center = btn.bounds().center();
            window.pointer_down(center, MouseButton::Left, cx);
            window.pointer_up(center, MouseButton::Left, cx);
            assert_eq!(clicks.get(), 1);

            // Keyboard Space activates focused button
            window.press("space", cx);
            assert_eq!(clicks.get(), 2);
        });

        // Loading keeps button focusable (not disabled) but swallows clicks
        view.update(cx, |v, cx| {
            v.loading = true;
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            let btn = window.find_by_label("Save");
            assert_ne!(btn.disabled(), Some(true));
            let center = btn.bounds().center();
            window.pointer_down(center, MouseButton::Left, cx);
            window.pointer_up(center, MouseButton::Left, cx);
            assert_eq!(clicks.get(), 2);
        });

        // Disabled blocks clicks and reports disabled to AccessKit
        view.update(cx, |v, cx| {
            v.loading = false;
            v.disabled = true;
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            let btn = window.find_by_label("Save");
            assert_eq!(btn.disabled(), Some(true));
            let center = btn.bounds().center();
            window.pointer_down(center, MouseButton::Left, cx);
            window.pointer_up(center, MouseButton::Left, cx);
            assert_eq!(clicks.get(), 2);
        });
    }

    #[test]
    fn adaptive_press_scale_matches_arc_width_breakpoints() {
        assert!((adaptive_press_scale(36.0) - 0.96).abs() < 1e-6);
        assert!((adaptive_press_scale(48.0) - 0.96).abs() < 1e-6);
        assert!((adaptive_press_scale(120.0) - 0.97).abs() < 1e-6);
        assert!((adaptive_press_scale(220.0) - 0.97).abs() < 1e-6);
        assert!((adaptive_press_scale(260.0) - 0.985).abs() < 1e-6);
    }

    #[test]
    fn button_width_morph_spring_matches_motion_reference_within_5_percent() {
        let spec = ArcMotionTokens::DEFAULT.spring.morph;
        let solver = SpringSolver::new(spec, 60.0, 128.0, 0.0);
        let omega0 = std::f64::consts::TAU / (0.42 * 1.2);
        let mut actual = CurveTrace::new("button", "slot_width");
        let mut expected = CurveTrace::new("button", "slot_width");
        for frame in 0..=45 {
            let t_ms = frame as f64 * 16.0;
            let t = t_ms / 1000.0;
            let ref_w = 128.0 - (-omega0 * t).exp() * (68.0 + omega0 * 68.0 * t);
            expected.push(t_ms, ref_w);
            actual.push(t_ms, f64::from(solver.sample(t).value));
        }
        let err = max_curve_error_pct(&actual, &expected);
        assert!(err < 5.0, "Button width morph error {err:.3}% >= 5%");
        assert!(
            err < 1.0,
            "Expected tight morph spring match, got {err:.3}%"
        );
    }

    #[gpui_kit::test]
    fn button_reduced_motion_and_label_morph_do_not_crash(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
            set_reduced_motion(ReducedMotionChoice::Reduce, cx);
        });
        let (view, cx) = cx.add_window_view(|_, _| ButtonHost {
            clicks: Rc::new(Cell::new(0)),
            loading: false,
            disabled: false,
            label: "Save".into(),
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
        });
        view.update(cx, |v, cx| {
            v.label = "Saved changes".into();
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            assert_eq!(
                window.find_by_label("Saved changes").role(),
                Some(Role::Button)
            );
        });
    }
}