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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Source: `Arc源码/arc-library/registry/components/stepper/stepper.tsx` & `stepper.module.css`
//!
//! A steps indicator (`stepper`) for onboarding, checkout, and setup flows:
//! - Horizontal (`grid` equal columns + trailing auto column) or vertical orientation.
//! - Cascading connector fill/drain (`stepper_step_stagger_delay`, `0.045s` `Stagger::LINE` per
//!   step crossed) driven by `motion.spring.smooth`.
//! - Delayed halo ring (`stepper_ring_delay`) that blooms behind the active `28px` marker disc once
//!   the incoming connector finishes arriving.
//! - Self-drawing checkmark (`M5.5 12.5 l4.25 4.25 L18.5 8`) and exclamation alert glyph
//!   (`M12 6.75 v6.5` + `cx=12, cy=17.4, r=1.4` dot) via `stepper_glyph_draw_sample`.
//! - Interactive mode (`on_step_select`) allowing users to click or use arrow keys (`ArrowLeft` /
//!   `ArrowRight` / `ArrowUp` / `ArrowDown` / `Home` / `End`) to revisit completed steps.

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

use arc_motion::{CubicBezier, PathPoint, PolylinePath, arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, Bounds, Corners, Edges, ElementId, FocusHandle, IntoElement, KeyDownEvent,
    MouseButton, ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
    base::StyledExt as _, canvas, div, point, prelude::*, px, quad,
};

type StepSelectCallback = Rc<dyn Fn(&usize, &mut Window, &mut App)>;

/// Marker disc diameter (`1.75rem = 28px`).
pub const STEPPER_MARKER_SIZE_PX: f32 = 28.0;

/// Halo ring inset expansion around the marker disc (`4px`).
pub const STEPPER_HALO_PX: f32 = 4.0;

/// Stagger step delay (`45ms`, matching `motionTokens.stagger.line`).
pub const STEPPER_LINE_STAGGER_SECS: f64 = 0.045;

/// Layout orientation of [`Stepper`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum StepperOrientation {
    #[default]
    Horizontal,
    Vertical,
}

/// Which step descriptions are visible under step labels.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum StepperDetails {
    /// Shows every step's description (`error` always takes precedence).
    #[default]
    All,
    /// Shows only the current step's description (plus any step with an `error`).
    Current,
}

/// Visual status of an individual step in [`Stepper`].
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum StepperStatus {
    Complete,
    Current,
    Upcoming,
    Error,
}

/// Single step definition for [`Stepper`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StepperStep {
    pub id: SharedString,
    pub label: SharedString,
    pub description: Option<SharedString>,
    pub error: Option<SharedString>,
}

impl StepperStep {
    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            description: None,
            error: None,
        }
    }

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

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

/// Computes the cascading stagger delay (`seconds`) for step `index` when transitioning from
/// `from_active` to `to_active`.
///
/// Mirrors `delayAt(index)` in `stepper.tsx`:
/// - Moving forward (`to_active > from_active`): steps in `from_active..to_active` fire in order
///   `(index - from_active) * Stagger::LINE`.
/// - Moving backward (`to_active < from_active`): steps in `to_active..from_active` drain in
///   reverse `(from_active - 1 - index) * Stagger::LINE`.
#[inline]
pub fn stepper_step_stagger_delay(
    index: usize,
    from_active: usize,
    to_active: usize,
    reduced: bool,
) -> f64 {
    if reduced || from_active == to_active {
        return 0.0;
    }
    let gap = STEPPER_LINE_STAGGER_SECS;
    if to_active > from_active {
        if index >= from_active && index < to_active {
            (index - from_active) as f64 * gap
        } else {
            0.0
        }
    } else if index >= to_active && index < from_active {
        (from_active - 1 - index) as f64 * gap
    } else {
        0.0
    }
}

/// Computes the arrival delay (`seconds`) before the active step's halo ring blooms out from behind
/// the marker disc.
#[inline]
pub fn stepper_ring_delay(from_active: usize, to_active: usize, reduced: bool) -> f64 {
    if reduced || from_active == to_active {
        return 0.0;
    }
    let steps_crossed = to_active.abs_diff(from_active);
    let extra = steps_crossed.saturating_sub(1) as f64;
    extra * STEPPER_LINE_STAGGER_SECS + 0.12
}

/// Computes `(pop_scale, stroke_progress, dot_scale)` for a step marker's check or error glyph at
/// `elapsed_secs` after the step transition started, respecting `delay_secs`.
pub fn stepper_glyph_draw_sample(
    elapsed_secs: f64,
    delay_secs: f64,
    reduced: bool,
) -> (f32, f32, f32) {
    if reduced {
        return (1.0, 1.0, 1.0);
    }
    let local = elapsed_secs - delay_secs;
    if local <= 0.0 {
        return (0.5, 0.0, 0.0);
    }
    let ease_enter = CubicBezier::new(0.22, 1.0, 0.36, 1.0);
    let pop_t = (local / 0.22).clamp(0.0, 1.0) as f32;
    let pop_scale = 0.5 + 0.5 * ease_enter.sample(pop_t);

    let draw_local = local - 0.04;
    let stroke_progress = if draw_local <= 0.0 {
        0.0
    } else {
        let t = (draw_local / 0.22).clamp(0.0, 1.0) as f32;
        ease_enter.sample(t)
    };

    let dot_local = local - 0.16;
    let dot_scale = if dot_local <= 0.0 {
        0.0
    } else {
        let t = (dot_local / 0.18).clamp(0.0, 1.0) as f32;
        ease_enter.sample(t)
    };

    (pop_scale, stroke_progress, dot_scale)
}

#[derive(Clone)]
struct StepperTravelState {
    from_active: usize,
    to_active: usize,
    transition_started_at: f64,
    focused_index: usize,
    pressed_index: Option<usize>,
    focus_handle: FocusHandle,
}

/// Steps indicator component (`stepper`).
#[derive(IntoElement)]
pub struct Stepper {
    id: ElementId,
    steps: Vec<StepperStep>,
    current: usize,
    orientation: StepperOrientation,
    details: StepperDetails,
    compact: bool,
    label: SharedString,
    complete_label: SharedString,
    on_step_select: Option<StepSelectCallback>,
}

impl Stepper {
    pub fn new(
        id: impl Into<ElementId>,
        steps: impl IntoIterator<Item = StepperStep>,
        current: usize,
    ) -> Self {
        Self {
            id: id.into(),
            steps: steps.into_iter().collect(),
            current,
            orientation: StepperOrientation::Horizontal,
            details: StepperDetails::All,
            compact: false,
            label: SharedString::from("Progress"),
            complete_label: SharedString::from("All steps complete"),
            on_step_select: None,
        }
    }

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

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

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

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

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

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

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

        let count = self.steps.len();
        let active = self.current.min(count);
        let interactive = self.on_step_select.is_some();
        let vertical = self.orientation == StepperOrientation::Vertical;

        let state_cell = window
            .use_keyed_state(
                ElementId::NamedChild(self.id.clone().into(), SharedString::from("stepper-travel")),
                cx,
                |_, cx| {
                    Rc::new(RefCell::new(StepperTravelState {
                        from_active: active,
                        to_active: active,
                        transition_started_at: now - 10.0,
                        focused_index: active.min(count.saturating_sub(1)),
                        pressed_index: None,
                        focus_handle: cx.focus_handle(),
                    }))
                },
            )
            .read(cx)
            .clone();

        let (from_active, transition_started_at, pressed_index, focus_handle) = {
            let mut st = state_cell.borrow_mut();
            if st.to_active != active {
                st.from_active = st.to_active;
                st.to_active = active;
                st.transition_started_at = now;
                st.focused_index = active.min(count.saturating_sub(1));
            }
            (
                st.from_active,
                st.transition_started_at,
                st.pressed_index,
                st.focus_handle.clone(),
            )
        };

        let elapsed = (now - transition_started_at).max(0.0);
        let ring_delay = stepper_ring_delay(from_active, active, reduced);
        let ring_progress = if reduced {
            1.0
        } else if elapsed <= ring_delay {
            0.0
        } else {
            let t = ((elapsed - ring_delay) / 0.22).clamp(0.0, 1.0) as f32;
            CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t)
        };

        let mut needs_anim_frame = !reduced && elapsed < (ring_delay + 0.45);

        let mut step_elements: Vec<AnyElement> = Vec::with_capacity(count);
        for (index, step) in self.steps.iter().enumerate() {
            let is_current = index == active;
            let has_error = step.error.is_some();
            let status = if has_error {
                StepperStatus::Error
            } else if index < active {
                StepperStatus::Complete
            } else if is_current {
                StepperStatus::Current
            } else {
                StepperStatus::Upcoming
            };

            let clickable = interactive && index < active;
            let step_delay = stepper_step_stagger_delay(index, from_active, active, reduced);

            // Connector fill progress (`0.0..=1.0`) for steps `0..count - 1`
            let connector_target = if index < active && elapsed >= step_delay {
                1.0
            } else {
                0.0
            };
            let connector_fill = if reduced {
                if index < active { 1.0 } else { 0.0 }
            } else {
                let sample = arc_spring(
                    ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("conn-{index}")),
                    ),
                    connector_target,
                    motion.spring.smooth,
                    window,
                    cx,
                );
                if (sample - connector_target).abs() > 0.002 {
                    needs_anim_frame = true;
                }
                sample.clamp(0.0, 1.0)
            };

            let (pop_scale, stroke_progress, dot_scale) =
                stepper_glyph_draw_sample(elapsed, step_delay, reduced);
            if !reduced
                && (status == StepperStatus::Complete || status == StepperStatus::Error)
                && elapsed < step_delay + 0.38
            {
                needs_anim_frame = true;
            }

            let is_pressed = clickable && pressed_index == Some(index);
            let disc_press_scale = if is_pressed && !reduced { 0.92 } else { 1.0 };

            let (disc_bg, disc_border, disc_fg, halo_color) = match status {
                StepperStatus::Complete => (
                    colors.accent,
                    colors.accent,
                    colors.accent_foreground,
                    colors.accent_subtle,
                ),
                StepperStatus::Current => (
                    colors.surface,
                    colors.accent,
                    colors.foreground,
                    colors.accent_subtle,
                ),
                StepperStatus::Error => (
                    oklab_mix(colors.danger, colors.surface, 0.10),
                    colors.danger,
                    colors.danger,
                    oklab_mix(colors.danger, colors.surface, 0.16),
                ),
                StepperStatus::Upcoming => (
                    colors.surface,
                    colors.border_strong,
                    colors.text_muted,
                    colors.accent_subtle,
                ),
            };

            let border_width = match status {
                StepperStatus::Current | StepperStatus::Error => 1.5,
                _ => 1.0,
            };

            let show_ring = is_current || status == StepperStatus::Error;
            let ring_alpha = if is_current {
                ring_progress
            } else if status == StepperStatus::Error {
                1.0
            } else {
                0.0
            };

            let step_num_text = SharedString::from(format!("{}", index + 1));

            // Marker canvas (halo ring + 28px disc + vector check / alert glyph)
            let marker = div()
                .relative()
                .size(px(STEPPER_MARKER_SIZE_PX))
                .flex_none()
                .flex()
                .items_center()
                .justify_center()
                .child(
                    canvas(
                        move |bounds, _window, _cx| bounds,
                        move |bounds: Bounds<gpui_kit::Pixels>, _, window, _cx| {
                            let cx_pt = bounds.origin.x + bounds.size.width * 0.5;
                            let cy_pt = bounds.origin.y + bounds.size.height * 0.5;

                            // 1. Halo ring behind the disc
                            if show_ring && ring_alpha > 0.01 {
                                let ring_scale = 0.6 + 0.4 * ring_alpha;
                                let full_extent =
                                    (STEPPER_MARKER_SIZE_PX + STEPPER_HALO_PX * 2.0) * ring_scale;
                                let half = full_extent * 0.5;
                                let mut c = halo_color;
                                c.a *= ring_alpha;
                                window.paint_quad(quad(
                                    Bounds::new(
                                        point(cx_pt - px(half), cy_pt - px(half)),
                                        gpui_kit::size(px(full_extent), px(full_extent)),
                                    ),
                                    Corners::all(px(full_extent)),
                                    c,
                                    Edges::all(px(0.0)),
                                    gpui_kit::transparent_black(),
                                    gpui_kit::BorderStyle::default(),
                                ));
                            }

                            // 2. Disc
                            let disc_size = STEPPER_MARKER_SIZE_PX * disc_press_scale;
                            let disc_half = disc_size * 0.5;
                            window.paint_quad(quad(
                                Bounds::new(
                                    point(cx_pt - px(disc_half), cy_pt - px(disc_half)),
                                    gpui_kit::size(px(disc_size), px(disc_size)),
                                ),
                                Corners::all(px(disc_size)),
                                disc_bg,
                                Edges::all(px(border_width)),
                                disc_border,
                                gpui_kit::BorderStyle::default(),
                            ));

                            // 3. Vector check or error glyph inside 14x14 icon box (24x24 viewBox)
                            let icon_scale = (14.0 / 24.0) * pop_scale * disc_press_scale;
                            let map_pt = |vx: f32, vy: f32| {
                                point(
                                    cx_pt + px((vx - 12.0) * icon_scale),
                                    cy_pt + px((vy - 12.0) * icon_scale),
                                )
                            };

                            if status == StepperStatus::Complete && stroke_progress > 0.01 {
                                let path = PolylinePath::new(vec![
                                    PathPoint::new(5.5, 12.5),
                                    PathPoint::new(9.75, 16.75),
                                    PathPoint::new(18.5, 8.0),
                                ]);
                                let sliced = path.slice(0.0, stroke_progress);
                                let pts = &sliced.points;
                                if pts.len() >= 2 {
                                    let mut builder = PathBuilder::stroke(px(2.0 * pop_scale));
                                    builder.move_to(map_pt(pts[0].x, pts[0].y));
                                    for p in &pts[1..] {
                                        builder.line_to(map_pt(p.x, p.y));
                                    }
                                    if let Ok(stroke) = builder.build() {
                                        window.paint_path(stroke, disc_fg);
                                    }
                                }
                            } else if status == StepperStatus::Error {
                                if stroke_progress > 0.01 {
                                    let y_end = 6.75 + 6.5 * stroke_progress;
                                    let mut builder = PathBuilder::stroke(px(2.0 * pop_scale));
                                    builder.move_to(map_pt(12.0, 6.75));
                                    builder.line_to(map_pt(12.0, y_end));
                                    if let Ok(stroke) = builder.build() {
                                        window.paint_path(stroke, disc_fg);
                                    }
                                }
                                if dot_scale > 0.01 {
                                    let r = 1.6 * dot_scale * disc_press_scale;
                                    let dot_center = map_pt(12.0, 17.4);
                                    window.paint_quad(quad(
                                        Bounds::new(
                                            point(dot_center.x - px(r), dot_center.y - px(r)),
                                            gpui_kit::size(px(r * 2.0), px(r * 2.0)),
                                        ),
                                        Corners::all(px(r * 2.0)),
                                        disc_fg,
                                        Edges::all(px(0.0)),
                                        gpui_kit::transparent_black(),
                                        gpui_kit::BorderStyle::default(),
                                    ));
                                }
                            }
                        },
                    )
                    .size_full(),
                )
                .when(
                    status == StepperStatus::Current || status == StepperStatus::Upcoming,
                    |this| {
                        this.child(
                            div()
                                .text_size(Typography::TEXT_XS)
                                .font_medium()
                                .text_color(disc_fg)
                                .child(step_num_text),
                        )
                    },
                );

            let detail_text: Option<(SharedString, bool)> = if let Some(err) = &step.error {
                Some((err.clone(), true))
            } else if self.details == StepperDetails::All || is_current {
                step.description.clone().map(|d| (d, false))
            } else {
                None
            };

            let label_color = match status {
                StepperStatus::Complete => colors.text_secondary,
                StepperStatus::Current | StepperStatus::Error => colors.foreground,
                StepperStatus::Upcoming => colors.text_muted,
            };

            let text_block = if self.compact {
                None
            } else {
                Some(
                    div()
                        .min_w_0()
                        .flex()
                        .flex_col()
                        .gap(px(2.0))
                        .when(vertical, |this| this.pt(px(3.0)))
                        .child(
                            div()
                                .text_size(Typography::TEXT_SM)
                                .font_medium()
                                .text_color(label_color)
                                .child(step.label.clone()),
                        )
                        .when_some(detail_text, |this, (txt, is_err)| {
                            this.child(
                                div()
                                    .text_size(Typography::TEXT_XS)
                                    .text_color(if is_err {
                                        colors.danger
                                    } else {
                                        colors.text_muted
                                    })
                                    .child(txt),
                            )
                        }),
                )
            };

            // Marker row + horizontal connector or vertical side-by-side head
            let is_last = index + 1 == count;
            let select_cb = self.on_step_select.clone();
            let press_state = state_cell.clone();
            let up_state = state_cell.clone();

            let item_el = if vertical {
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("step-{index}")),
                    ))
                    .w_full()
                    .flex()
                    .flex_row()
                    .items_stretch()
                    .gap(Spacing::S3)
                    .when(clickable, |this| this.cursor_pointer())
                    .on_mouse_down(MouseButton::Left, move |_, window, _cx| {
                        if clickable {
                            press_state.borrow_mut().pressed_index = Some(index);
                            window.refresh();
                        }
                    })
                    .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                        let was_pressed = up_state.borrow_mut().pressed_index.take().is_some();
                        if clickable && was_pressed {
                            if let Some(cb) = &select_cb {
                                cb(&index, window, cx);
                            }
                            window.refresh();
                        }
                    })
                    .child(
                        div()
                            .w(px(STEPPER_MARKER_SIZE_PX))
                            .flex_none()
                            .flex()
                            .flex_col()
                            .items_center()
                            .child(marker)
                            .when(!is_last, |this| {
                                this.child(
                                    div()
                                        .w(px(2.0))
                                        .flex_1()
                                        .min_h(if self.compact { px(24.0) } else { px(28.0) })
                                        .my(px(6.0))
                                        .rounded(Radii::PILL)
                                        .bg(colors.border)
                                        .overflow_hidden()
                                        .child(
                                            div()
                                                .w_full()
                                                .h(gpui_kit::relative(connector_fill))
                                                .rounded(Radii::PILL)
                                                .bg(colors.accent),
                                        ),
                                )
                            }),
                    )
                    .when_some(text_block, |this, tb| {
                        this.child(
                            div()
                                .flex_1()
                                .min_w_0()
                                .when(!is_last, |d| d.pb(Spacing::S5))
                                .child(tb),
                        )
                    })
                    .into_any_element()
            } else {
                // Horizontal step item
                let mut col = div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("step-{index}")),
                    ))
                    .min_w_0()
                    .flex()
                    .flex_col()
                    .gap(Spacing::S3)
                    .when(!is_last, |this| this.flex_1().pr(Spacing::S3))
                    .when(is_last, |this| this.flex_none())
                    .when(clickable, |this| this.cursor_pointer())
                    .on_mouse_down(MouseButton::Left, move |_, window, _cx| {
                        if clickable {
                            press_state.borrow_mut().pressed_index = Some(index);
                            window.refresh();
                        }
                    })
                    .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                        let was_pressed = up_state.borrow_mut().pressed_index.take().is_some();
                        if clickable && was_pressed {
                            if let Some(cb) = &select_cb {
                                cb(&index, window, cx);
                            }
                            window.refresh();
                        }
                    })
                    .child(
                        div()
                            .w_full()
                            .flex()
                            .flex_row()
                            .items_center()
                            .child(marker)
                            .when(!is_last, |this| {
                                this.child(
                                    div()
                                        .flex_1()
                                        .h(px(2.0))
                                        .ml(px(8.0))
                                        .rounded(Radii::PILL)
                                        .bg(colors.border)
                                        .overflow_hidden()
                                        .child(
                                            div()
                                                .h_full()
                                                .w(gpui_kit::relative(connector_fill))
                                                .rounded(Radii::PILL)
                                                .bg(colors.accent),
                                        ),
                                )
                            }),
                    );

                if let Some(tb) = text_block {
                    col = col.child(tb);
                }
                col.into_any_element()
            };

            step_elements.push(item_el);
        }

        if needs_anim_frame {
            window.request_animation_frame();
        }

        // Compact horizontal caption underneath the markers
        let compact_caption = if !vertical && self.compact {
            let current_step = self.steps.get(active);
            let title = current_step
                .map(|s| s.label.clone())
                .unwrap_or_else(|| self.complete_label.clone());
            let sub: Option<(SharedString, bool)> = current_step.and_then(|s| {
                if let Some(err) = &s.error {
                    Some((err.clone(), true))
                } else {
                    s.description.clone().map(|d| (d, false))
                }
            });

            Some(
                div()
                    .mt(Spacing::S3)
                    .flex()
                    .flex_col()
                    .gap(px(2.0))
                    .child(
                        div()
                            .text_size(Typography::TEXT_SM)
                            .font_medium()
                            .text_color(colors.foreground)
                            .child(title),
                    )
                    .when_some(sub, |this, (txt, is_err)| {
                        this.child(
                            div()
                                .text_size(Typography::TEXT_XS)
                                .text_color(if is_err {
                                    colors.danger
                                } else {
                                    colors.text_muted
                                })
                                .child(txt),
                        )
                    }),
            )
        } else {
            None
        };

        let key_state = state_cell.clone();
        let key_cb = self.on_step_select.clone();
        let max_reachable = active.min(count.saturating_sub(1));

        div()
            .id(self.id)
            .role(Role::Group)
            .track_focus(&focus_handle)
            .w_full()
            .flex()
            .flex_col()
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if !interactive || count == 0 {
                    return;
                }
                let key = event.keystroke.key.as_str();
                let mut st = key_state.borrow_mut();
                match key {
                    "left" | "arrowleft" | "up" | "arrowup" => {
                        st.focused_index = st.focused_index.saturating_sub(1);
                    }
                    "right" | "arrowright" | "down" | "arrowdown" => {
                        st.focused_index = (st.focused_index + 1).min(max_reachable);
                    }
                    "home" => {
                        st.focused_index = 0;
                    }
                    "end" => {
                        st.focused_index = max_reachable;
                    }
                    "enter" | " " | "space" => {
                        let target = st.focused_index;
                        drop(st);
                        if target < active
                            && let Some(cb) = &key_cb
                        {
                            cb(&target, window, cx);
                        }
                        window.refresh();
                        return;
                    }
                    _ => return,
                }
                window.refresh();
            })
            .child(
                div()
                    .w_full()
                    .flex()
                    .when(vertical, |this| this.flex_col())
                    .when(!vertical, |this| this.flex_row().items_start())
                    .children(step_elements),
            )
            .when_some(compact_caption, |this, cap| this.child(cap))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stepper_step_stagger_delay_cascades_forward_and_backward() {
        let gap = STEPPER_LINE_STAGGER_SECS;
        // Forward jump from step 0 -> step 3: connectors 0, 1, 2 stagger in order
        assert!((stepper_step_stagger_delay(0, 0, 3, false) - 0.0).abs() < 1e-6);
        assert!((stepper_step_stagger_delay(1, 0, 3, false) - gap).abs() < 1e-6);
        assert!((stepper_step_stagger_delay(2, 0, 3, false) - 2.0 * gap).abs() < 1e-6);
        assert!((stepper_step_stagger_delay(3, 0, 3, false) - 0.0).abs() < 1e-6);

        // Backward jump from step 3 -> step 0: connectors 2, 1, 0 drain in reverse order
        assert!((stepper_step_stagger_delay(2, 3, 0, false) - 0.0).abs() < 1e-6);
        assert!((stepper_step_stagger_delay(1, 3, 0, false) - gap).abs() < 1e-6);
        assert!((stepper_step_stagger_delay(0, 3, 0, false) - 2.0 * gap).abs() < 1e-6);

        // Ring delay waits for multi-step connector cascade + 120ms
        assert!((stepper_ring_delay(0, 3, false) - (2.0 * gap + 0.12)).abs() < 1e-6);
        assert_eq!(stepper_ring_delay(0, 3, true), 0.0);
    }

    #[test]
    fn stepper_glyph_draw_sample_draws_stroke_and_dot_on_schedule() {
        let (scale0, stroke0, dot0) = stepper_glyph_draw_sample(0.0, 0.0, false);
        assert!((scale0 - 0.5).abs() < 1e-5);
        assert_eq!(stroke0, 0.0);
        assert_eq!(dot0, 0.0);

        let (scale_mid, stroke_mid, dot_mid) = stepper_glyph_draw_sample(0.15, 0.0, false);
        assert!(scale_mid > 0.8);
        assert!(stroke_mid > 0.3 && stroke_mid < 1.0);
        assert_eq!(dot_mid, 0.0);

        let (scale_done, stroke_done, dot_done) = stepper_glyph_draw_sample(0.40, 0.0, false);
        assert!((scale_done - 1.0).abs() < 1e-5);
        assert!((stroke_done - 1.0).abs() < 1e-5);
        assert!((dot_done - 1.0).abs() < 1e-5);
    }
}