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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/action-swap/action-swap.tsx` & `.module.css`
//!
//! P2 Component #7: `action-swap`
//!
//! - Compact pill action that morphs smoothly through a cycle of related states (`ActionSwapState`):
//!   width, horizontal padding (`fold` into a circular spinner when working without `pending_label`),
//!   semantic tone (`Neutral | Accent | Success | Warning | Quiet`), icon, and label move together
//!   on `motion.spring.morph`.
//! - Supports controlled (`value`) and uncontrolled (`default_value`) modes, timed `hold_for`
//!   auto-advance (e.g. brief "Sent" confirmation), and optional `working_duration` step.

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

use arc_motion::{
    BlurFallback, CubicBezier, arc_spring, arc_spring_with_options, is_reduced_motion, motion_now,
    spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
    App, 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,
};

type ValueChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;

/// Visual tone for an [`ActionSwapState`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ActionSwapTone {
    #[default]
    Neutral,
    Accent,
    Success,
    Warning,
    Quiet,
}

/// Height and horizontal padding scale for [`ActionSwap`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ActionSwapSize {
    Sm,
    #[default]
    Md,
    Lg,
}

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

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

/// One state entry inside an [`ActionSwap`] cycle.
#[derive(Clone)]
pub struct ActionSwapState {
    pub id: SharedString,
    pub label: SharedString,
    pub icon: Option<IconName>,
    pub tone: ActionSwapTone,
    /// Optional label shown while working into this state; when omitted the pill folds into a circle.
    pub pending_label: Option<SharedString>,
    /// Optional duration to hold this state before automatically advancing to the next state.
    pub hold_for: Option<Duration>,
}

impl ActionSwapState {
    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            icon: None,
            tone: ActionSwapTone::Neutral,
            pending_label: None,
            hold_for: None,
        }
    }

    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

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

    pub fn pending_label(mut self, label: impl Into<SharedString>) -> Self {
        self.pending_label = Some(label.into());
        self
    }

    pub fn hold_for(mut self, duration: Duration) -> Self {
        self.hold_for = Some(duration);
        self
    }
}

#[derive(Clone)]
struct ActionSwapInternal {
    uncontrolled_value: SharedString,
    working_target_id: Option<SharedString>,
    working_until_secs: Option<f64>,
    hold_until_secs: Option<f64>,
    last_view_key: SharedString,
    morph_armed_until_secs: f64,
    phase_changed_at_secs: f64,
    hovered: bool,
    pressed: bool,
    measured_label_w: Rc<RefCell<f32>>,
    has_measured: Rc<RefCell<bool>>,
}

impl ActionSwapInternal {
    fn new(initial: SharedString, now: f64) -> Self {
        Self {
            uncontrolled_value: initial.clone(),
            working_target_id: None,
            working_until_secs: None,
            hold_until_secs: None,
            last_view_key: initial,
            morph_armed_until_secs: f64::NEG_INFINITY,
            phase_changed_at_secs: now - 10.0,
            hovered: false,
            pressed: false,
            measured_label_w: Rc::new(RefCell::new(0.0)),
            has_measured: Rc::new(RefCell::new(false)),
        }
    }
}

/// Arc `ActionSwap` — compact multi-state morphing pill button.
#[derive(IntoElement)]
pub struct ActionSwap {
    id: ElementId,
    states: Vec<ActionSwapState>,
    value: Option<SharedString>,
    default_value: Option<SharedString>,
    working_duration: Duration,
    size: ActionSwapSize,
    disabled: bool,
    focus_handle: Option<FocusHandle>,
    on_value_change: Option<ValueChangeHandler>,
}

impl ActionSwap {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            states: Vec::new(),
            value: None,
            default_value: None,
            working_duration: Duration::ZERO,
            size: ActionSwapSize::Md,
            disabled: false,
            focus_handle: None,
            on_value_change: None,
        }
    }

    pub fn state(mut self, state: ActionSwapState) -> Self {
        self.states.push(state);
        self
    }

    pub fn states(mut self, states: impl IntoIterator<Item = ActionSwapState>) -> Self {
        self.states.extend(states);
        self
    }

    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
        self.value = Some(value.into());
        self
    }

    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
        self.default_value = Some(value.into());
        self
    }

    /// Optional duration spent in the working/spinner phase before committing the next state
    /// (minimum `450ms` recommended so the folded circle reads cleanly as a step).
    pub fn working_duration(mut self, duration: Duration) -> Self {
        self.working_duration = duration;
        self
    }

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

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

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

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

fn paint_ring_spinner(
    cx: f32,
    cy: f32,
    radius: f32,
    angle_rad: f32,
    fg: Hsla,
    window: &mut Window,
) {
    // Faint full ring (24% opacity) + bright rotating top arc (matches action-swap.module.css line 32)
    let track_c = Hsla {
        a: fg.a * 0.24,
        ..fg
    };
    let mut track = PathBuilder::stroke(px(1.5));
    for i in 0..=24 {
        let a = std::f32::consts::TAU * (i as f32 / 24.0);
        let p = point(px(cx + radius * a.cos()), px(cy + radius * a.sin()));
        if i == 0 {
            track.move_to(p);
        } else {
            track.line_to(p);
        }
    }
    if let Ok(path) = track.build() {
        window.paint_path(path, track_c);
    }

    let mut arc = PathBuilder::stroke(px(1.5));
    let sweep = std::f32::consts::FRAC_PI_2 * 1.15;
    for i in 0..=12 {
        let a = angle_rad + sweep * (i as f32 / 12.0);
        let p = point(px(cx + radius * a.cos()), px(cy + radius * a.sin()));
        if i == 0 {
            arc.move_to(p);
        } else {
            arc.line_to(p);
        }
    }
    if let Ok(path) = arc.build() {
        window.paint_path(path, fg);
    }
}

impl RenderOnce for ActionSwap {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        if self.states.is_empty() {
            return div().id(self.id).into_any_element();
        }
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let is_controlled = self.value.is_some();
        let initial_id = self
            .default_value
            .clone()
            .unwrap_or_else(|| self.states[0].id.clone());
        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-action-swap-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, _| {
            ActionSwapInternal::new(initial_id.clone(), now)
        });

        // Tick working & hold_for timers.
        {
            let snap = internal.read(cx).clone();
            let mut committed_next: Option<SharedString> = None;
            let mut keep_ticking = false;
            if let Some(work_until) = snap.working_until_secs {
                if now >= work_until {
                    let next_id = snap.working_target_id.clone();
                    if let Some(target_id) = next_id {
                        let hold = self
                            .states
                            .iter()
                            .find(|s| s.id == target_id)
                            .and_then(|s| s.hold_for);
                        internal.update(cx, |s, _| {
                            s.working_target_id = None;
                            s.working_until_secs = None;
                            if !is_controlled {
                                s.uncontrolled_value = target_id.clone();
                            }
                            s.hold_until_secs = hold.map(|d| now + d.as_secs_f64());
                        });
                        committed_next = Some(target_id);
                    }
                } else {
                    keep_ticking = true;
                }
            } else if let Some(hold_until) = snap.hold_until_secs {
                if now >= hold_until {
                    let cur_val = self
                        .value
                        .clone()
                        .unwrap_or_else(|| snap.uncontrolled_value.clone());
                    let cur_idx = self
                        .states
                        .iter()
                        .position(|s| s.id == cur_val)
                        .unwrap_or(0);
                    let next_state = &self.states[(cur_idx + 1) % self.states.len()];
                    let next_id = next_state.id.clone();
                    let next_hold = next_state.hold_for;
                    internal.update(cx, |s, _| {
                        if !is_controlled {
                            s.uncontrolled_value = next_id.clone();
                        }
                        s.hold_until_secs = next_hold.map(|d| now + d.as_secs_f64());
                    });
                    committed_next = Some(next_id);
                } else {
                    keep_ticking = true;
                }
            }
            if let Some(next_id) = committed_next
                && let Some(handler) = &self.on_value_change
            {
                handler(&next_id, window, cx);
            }
            if keep_ticking {
                window.request_animation_frame();
            }
        }

        let snap = internal.read(cx).clone();
        let active_value = self
            .value
            .clone()
            .unwrap_or_else(|| snap.uncontrolled_value.clone());
        let active_idx = self
            .states
            .iter()
            .position(|s| s.id == active_value)
            .unwrap_or(0);
        let active_state = &self.states[active_idx];
        let next_state = &self.states[(active_idx + 1) % self.states.len()];
        let working_target = snap
            .working_target_id
            .as_ref()
            .and_then(|id| self.states.iter().find(|s| &s.id == id));
        let working = working_target.is_some();
        let folded = working_target.is_some_and(|t| t.pending_label.is_none());

        let (view_key, view_label, view_tone, view_icon): (
            SharedString,
            SharedString,
            ActionSwapTone,
            Option<IconName>,
        ) = if let Some(target) = working_target {
            let lbl = target.pending_label.clone().unwrap_or_default();
            (
                SharedString::from(format!("working:{lbl}")),
                lbl,
                active_state.tone,
                None,
            )
        } else {
            (
                SharedString::from(format!("state:{}", active_state.id)),
                active_state.label.clone(),
                active_state.tone,
                active_state.icon,
            )
        };

        if snap.last_view_key != view_key {
            internal.update(cx, |s, _| {
                s.last_view_key = view_key.clone();
                s.morph_armed_until_secs = now + 0.7;
                s.phase_changed_at_secs = now;
            });
        }

        let snap = internal.read(cx).clone();
        let inactive = self.disabled || self.states.len() < 2;
        let inert = inactive || working;

        // Fold spring (`0 -> 1`): eases horizontal padding down until the pill becomes a circle.
        let fold = if reduced {
            if folded { 1.0 } else { 0.0 }
        } else {
            arc_spring(
                (self.id.clone(), "fold"),
                if folded { 1.0 } else { 0.0 },
                motion.spring.morph,
                window,
                cx,
            )
            .clamp(0.0, 1.0)
        };
        let h_px = f32::from(self.size.height());
        let base_pad = f32::from(self.size.pad_x());
        let circle_pad = ((h_px - 18.0) * 0.5).max(8.0);
        let pad_x = base_pad + (circle_pad - base_pad) * fold;

        // Label width morph (`motion.spring.morph`).
        let target_label_w = if folded {
            0.0
        } else {
            *snap.measured_label_w.borrow()
        };
        let morph_active =
            !reduced && *snap.has_measured.borrow() && now <= snap.morph_armed_until_secs;
        let morphed_label_w = if *snap.has_measured.borrow() {
            let sample = arc_spring_with_options(
                (self.id.clone(), "label-width"),
                target_label_w,
                SpringOptions::new(motion.spring.morph),
                window,
                cx,
            );
            if morph_active || folded {
                Some(sample.value.max(0.0))
            } else {
                None
            }
        } else {
            None
        };

        let elapsed = (now - snap.phase_changed_at_secs).max(0.0);
        let dur = if reduced {
            motion.duration.instant.as_secs_f64()
        } else {
            motion.duration.standard.as_secs_f64()
        };
        let (phase_op, phase_y) = if elapsed < dur {
            window.request_animation_frame();
            let t = (elapsed / dur).clamp(0.0, 1.0) as f32;
            let e = if reduced {
                t
            } else {
                CubicBezier::from_spec(motion.ease.enter).sample(t)
            };
            let blur = BlurFallback::evaluate(px((1.0 - e) * f32::from(motion.blur.soft)), reduced);
            (
                (e * blur.opacity_multiplier).clamp(0.0, 1.0),
                if reduced { 0.0 } else { 4.0 * (1.0 - e) },
            )
        } else {
            (1.0, 0.0)
        };

        // Tone palette resolution matching `action-swap.module.css` lines 11-23.
        let hovered = !inert && snap.hovered;
        let (bg, border, fg, icon_tint) = match view_tone {
            ActionSwapTone::Neutral => {
                let c = if hovered {
                    colors.text_secondary
                } else {
                    colors.foreground
                };
                (c, c, colors.background, colors.background)
            }
            ActionSwapTone::Accent => {
                let c = if hovered {
                    colors.accent_strong
                } else {
                    colors.accent
                };
                (c, c, colors.accent_foreground, colors.accent_foreground)
            }
            ActionSwapTone::Quiet => (
                if hovered {
                    colors.surface_muted
                } else {
                    colors.surface
                },
                if hovered {
                    colors.border_strong
                } else {
                    colors.border
                },
                colors.foreground,
                colors.foreground,
            ),
            ActionSwapTone::Success => (
                oklab_mix(colors.success, colors.surface, 0.10),
                oklab_mix(
                    colors.success,
                    colors.border,
                    if hovered { 0.42 } else { 0.25 },
                ),
                colors.foreground,
                colors.success,
            ),
            ActionSwapTone::Warning => (
                oklab_mix(colors.warning, colors.surface, 0.12),
                oklab_mix(
                    colors.warning,
                    colors.border,
                    if hovered { 0.48 } else { 0.30 },
                ),
                colors.foreground,
                colors.warning,
            ),
        };

        // 背景用真实元素绘制:本组件的绝对定位画布在 GPUI 下拿不到绘制回调,
        // 底色与描边整块不出现(白字落在白底上等于消失)。按压反馈改为轻微压暗。
        let backdrop = div()
            .absolute()
            .inset_0()
            .rounded(Radii::PILL)
            .bg(bg)
            .border_1()
            .border_color(border)
            .when(snap.pressed && !inert, |this| this.opacity(0.92));

        let label_w_ref = snap.measured_label_w.clone();
        let has_m_ref = snap.has_measured.clone();
        let label_probe = canvas(
            move |rect, window, _| {
                let w = f32::from(rect.size.width);
                let prev = *label_w_ref.borrow();
                if w > 0.0 {
                    *label_w_ref.borrow_mut() = w;
                    *has_m_ref.borrow_mut() = true;
                }
                if (w - prev).abs() > 0.5 && prev > 0.0 {
                    window.request_animation_frame();
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();

        let icon_slot = if working {
            let spin_angle = if reduced {
                0.0
            } else {
                window.request_animation_frame();
                ((now % 0.75) / 0.75) as f32 * std::f32::consts::TAU
            };
            Some(
                div()
                    .w(px(16.0))
                    .h(px(16.0))
                    .flex_none()
                    .child(
                        canvas(
                            |_, _, _| {},
                            move |rect, _, window, _| {
                                let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
                                let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
                                paint_ring_spinner(cx, cy, 6.2, spin_angle, fg, window);
                            },
                        )
                        .size_full(),
                    )
                    .into_any_element(),
            )
        } else {
            view_icon.map(|icon| {
                div()
                    .w(px(16.0))
                    .h(px(16.0))
                    .flex_none()
                    .flex()
                    .items_center()
                    .justify_center()
                    .text_color(icon_tint)
                    .opacity(phase_op)
                    .child(icon)
                    .into_any_element()
            })
        };

        let has_icon = icon_slot.is_some();
        let has_text = !view_label.is_empty();
        let next_id_for_click = next_state.id.clone();
        let next_hold_for_click = next_state.hold_for;
        let work_secs = self.working_duration.as_secs_f64();
        let on_change = self.on_value_change;
        let int_click = internal.clone();
        let int_hover = internal.clone();
        let int_down = internal.clone();
        let int_up = internal.clone();
        let int_out = internal.clone();
        let int_kd = internal.clone();
        let int_ku = internal.clone();

        let mut base = BaseButton::new(self.id.clone())
            .disabled(inactive)
            .accessibility_label(if view_label.is_empty() {
                active_state.label.clone()
            } else {
                view_label.clone()
            })
            .on_click(move |_, window, cx| {
                if inert {
                    return;
                }
                let t_now = motion_now(cx);
                if work_secs > 0.0 {
                    int_click.update(cx, |s, _| {
                        s.hold_until_secs = None;
                        s.working_target_id = Some(next_id_for_click.clone());
                        s.working_until_secs = Some(t_now + work_secs);
                    });
                } else {
                    int_click.update(cx, |s, _| {
                        if !is_controlled {
                            s.uncontrolled_value = next_id_for_click.clone();
                        }
                        s.hold_until_secs = next_hold_for_click.map(|d| t_now + d.as_secs_f64());
                    });
                    if let Some(handler) = &on_change {
                        handler(&next_id_for_click, window, cx);
                    }
                }
                window.refresh();
            });

        if let Some(handle) = &self.focus_handle {
            base = base.track_focus(handle);
        }

        base.relative()
            .self_start()
            .flex()
            .flex_row()
            .items_center()
            .justify_center()
            .min_w(self.size.height())
            .min_h(self.size.height())
            .px(px(pad_x))
            .rounded(Radii::PILL)
            .overflow_hidden()
            .text_size(Typography::TEXT_SM)
            .text_color(fg)
            .when(inactive, |this| this.opacity(0.6))
            .when(!inert, |this| this.cursor_pointer())
            .on_hover(move |hovered, window, cx| {
                int_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;
                }
                int_down.update(cx, |s, _| s.pressed = true);
                window.refresh();
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                int_up.update(cx, |s, _| s.pressed = false);
                window.refresh();
            })
            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                int_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" {
                    int_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" {
                    int_ku.update(cx, |s, _| s.pressed = false);
                    window.refresh();
                }
            })
            .child(backdrop)
            .when_some(icon_slot, |this, icon| this.child(icon))
            .child(
                div()
                    .relative()
                    .flex()
                    .items_center()
                    .when_some(morphed_label_w, |this, w| this.w(px(w)).overflow_hidden())
                    .child(
                        div()
                            .relative()
                            .flex_none()
                            .when(has_icon && has_text, |this| this.pl(Spacing::S2))
                            .mt(px(phase_y))
                            .opacity(if folded { 0.0 } else { phase_op })
                            .child(label_probe)
                            .child(view_label),
                    ),
            )
            .into_any_element()
    }
}

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

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, MouseButton, Render, Role, TestAppContext, div,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    struct SwapHost {
        last: Rc<RefCell<SharedString>>,
    }

    impl Render for SwapHost {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let last = self.last.clone();
            div().p(Spacing::S4).child(
                ActionSwap::new("send-swap")
                    .default_value("send")
                    .states([
                        ActionSwapState::new("send", "Send").tone(ActionSwapTone::Neutral),
                        ActionSwapState::new("sent", "Sent").tone(ActionSwapTone::Success),
                    ])
                    .on_value_change(cx.listener(move |_, val: &SharedString, _, _| {
                        *last.borrow_mut() = val.clone();
                    })),
            )
        }
    }

    #[gpui_kit::test]
    fn action_swap_advances_through_state_cycle(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let last = Rc::new(RefCell::new(SharedString::from("")));
        let (_view, cx) = cx.add_window_view(|_, _| SwapHost { last: last.clone() });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let btn = window.find_by_label("Send");
            assert_eq!(btn.role(), Some(Role::Button));
            let pos = btn.bounds().center();
            window.pointer_down(pos, MouseButton::Left, cx);
            window.pointer_up(pos, MouseButton::Left, cx);
            assert_eq!(*last.borrow(), "sent");
        });
    }
}