Skip to main content

arc_ui/feedback/
stepper.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Source: `Arc源码/arc-library/registry/components/stepper/stepper.tsx` & `stepper.module.css`
3//!
4//! A steps indicator (`stepper`) for onboarding, checkout, and setup flows:
5//! - Horizontal (`grid` equal columns + trailing auto column) or vertical orientation.
6//! - Cascading connector fill/drain (`stepper_step_stagger_delay`, `0.045s` `Stagger::LINE` per
7//!   step crossed) driven by `motion.spring.smooth`.
8//! - Delayed halo ring (`stepper_ring_delay`) that blooms behind the active `28px` marker disc once
9//!   the incoming connector finishes arriving.
10//! - Self-drawing checkmark (`M5.5 12.5 l4.25 4.25 L18.5 8`) and exclamation alert glyph
11//!   (`M12 6.75 v6.5` + `cx=12, cy=17.4, r=1.4` dot) via `stepper_glyph_draw_sample`.
12//! - Interactive mode (`on_step_select`) allowing users to click or use arrow keys (`ArrowLeft` /
13//!   `ArrowRight` / `ArrowUp` / `ArrowDown` / `Home` / `End`) to revisit completed steps.
14
15use std::{cell::RefCell, rc::Rc};
16
17use arc_motion::{CubicBezier, PathPoint, PolylinePath, arc_spring, is_reduced_motion, motion_now};
18use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
19use gpui_kit::{
20    AnyElement, App, Bounds, Corners, Edges, ElementId, FocusHandle, IntoElement, KeyDownEvent,
21    MouseButton, ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
22    base::StyledExt as _, canvas, div, point, prelude::*, px, quad,
23};
24
25type StepSelectCallback = Rc<dyn Fn(&usize, &mut Window, &mut App)>;
26
27/// Marker disc diameter (`1.75rem = 28px`).
28pub const STEPPER_MARKER_SIZE_PX: f32 = 28.0;
29
30/// Halo ring inset expansion around the marker disc (`4px`).
31pub const STEPPER_HALO_PX: f32 = 4.0;
32
33/// Stagger step delay (`45ms`, matching `motionTokens.stagger.line`).
34pub const STEPPER_LINE_STAGGER_SECS: f64 = 0.045;
35
36/// Layout orientation of [`Stepper`].
37#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
38pub enum StepperOrientation {
39    #[default]
40    Horizontal,
41    Vertical,
42}
43
44/// Which step descriptions are visible under step labels.
45#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
46pub enum StepperDetails {
47    /// Shows every step's description (`error` always takes precedence).
48    #[default]
49    All,
50    /// Shows only the current step's description (plus any step with an `error`).
51    Current,
52}
53
54/// Visual status of an individual step in [`Stepper`].
55#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
56pub enum StepperStatus {
57    Complete,
58    Current,
59    Upcoming,
60    Error,
61}
62
63/// Single step definition for [`Stepper`].
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub struct StepperStep {
66    pub id: SharedString,
67    pub label: SharedString,
68    pub description: Option<SharedString>,
69    pub error: Option<SharedString>,
70}
71
72impl StepperStep {
73    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
74        Self {
75            id: id.into(),
76            label: label.into(),
77            description: None,
78            error: None,
79        }
80    }
81
82    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
83        self.description = Some(description.into());
84        self
85    }
86
87    pub fn error(mut self, error: impl Into<SharedString>) -> Self {
88        self.error = Some(error.into());
89        self
90    }
91}
92
93/// Computes the cascading stagger delay (`seconds`) for step `index` when transitioning from
94/// `from_active` to `to_active`.
95///
96/// Mirrors `delayAt(index)` in `stepper.tsx`:
97/// - Moving forward (`to_active > from_active`): steps in `from_active..to_active` fire in order
98///   `(index - from_active) * Stagger::LINE`.
99/// - Moving backward (`to_active < from_active`): steps in `to_active..from_active` drain in
100///   reverse `(from_active - 1 - index) * Stagger::LINE`.
101#[inline]
102pub fn stepper_step_stagger_delay(
103    index: usize,
104    from_active: usize,
105    to_active: usize,
106    reduced: bool,
107) -> f64 {
108    if reduced || from_active == to_active {
109        return 0.0;
110    }
111    let gap = STEPPER_LINE_STAGGER_SECS;
112    if to_active > from_active {
113        if index >= from_active && index < to_active {
114            (index - from_active) as f64 * gap
115        } else {
116            0.0
117        }
118    } else if index >= to_active && index < from_active {
119        (from_active - 1 - index) as f64 * gap
120    } else {
121        0.0
122    }
123}
124
125/// Computes the arrival delay (`seconds`) before the active step's halo ring blooms out from behind
126/// the marker disc.
127#[inline]
128pub fn stepper_ring_delay(from_active: usize, to_active: usize, reduced: bool) -> f64 {
129    if reduced || from_active == to_active {
130        return 0.0;
131    }
132    let steps_crossed = to_active.abs_diff(from_active);
133    let extra = steps_crossed.saturating_sub(1) as f64;
134    extra * STEPPER_LINE_STAGGER_SECS + 0.12
135}
136
137/// Computes `(pop_scale, stroke_progress, dot_scale)` for a step marker's check or error glyph at
138/// `elapsed_secs` after the step transition started, respecting `delay_secs`.
139pub fn stepper_glyph_draw_sample(
140    elapsed_secs: f64,
141    delay_secs: f64,
142    reduced: bool,
143) -> (f32, f32, f32) {
144    if reduced {
145        return (1.0, 1.0, 1.0);
146    }
147    let local = elapsed_secs - delay_secs;
148    if local <= 0.0 {
149        return (0.5, 0.0, 0.0);
150    }
151    let ease_enter = CubicBezier::new(0.22, 1.0, 0.36, 1.0);
152    let pop_t = (local / 0.22).clamp(0.0, 1.0) as f32;
153    let pop_scale = 0.5 + 0.5 * ease_enter.sample(pop_t);
154
155    let draw_local = local - 0.04;
156    let stroke_progress = if draw_local <= 0.0 {
157        0.0
158    } else {
159        let t = (draw_local / 0.22).clamp(0.0, 1.0) as f32;
160        ease_enter.sample(t)
161    };
162
163    let dot_local = local - 0.16;
164    let dot_scale = if dot_local <= 0.0 {
165        0.0
166    } else {
167        let t = (dot_local / 0.18).clamp(0.0, 1.0) as f32;
168        ease_enter.sample(t)
169    };
170
171    (pop_scale, stroke_progress, dot_scale)
172}
173
174#[derive(Clone)]
175struct StepperTravelState {
176    from_active: usize,
177    to_active: usize,
178    transition_started_at: f64,
179    focused_index: usize,
180    pressed_index: Option<usize>,
181    focus_handle: FocusHandle,
182}
183
184/// Steps indicator component (`stepper`).
185#[derive(IntoElement)]
186pub struct Stepper {
187    id: ElementId,
188    steps: Vec<StepperStep>,
189    current: usize,
190    orientation: StepperOrientation,
191    details: StepperDetails,
192    compact: bool,
193    label: SharedString,
194    complete_label: SharedString,
195    on_step_select: Option<StepSelectCallback>,
196}
197
198impl Stepper {
199    pub fn new(
200        id: impl Into<ElementId>,
201        steps: impl IntoIterator<Item = StepperStep>,
202        current: usize,
203    ) -> Self {
204        Self {
205            id: id.into(),
206            steps: steps.into_iter().collect(),
207            current,
208            orientation: StepperOrientation::Horizontal,
209            details: StepperDetails::All,
210            compact: false,
211            label: SharedString::from("Progress"),
212            complete_label: SharedString::from("All steps complete"),
213            on_step_select: None,
214        }
215    }
216
217    pub fn orientation(mut self, orientation: StepperOrientation) -> Self {
218        self.orientation = orientation;
219        self
220    }
221
222    pub fn details(mut self, details: StepperDetails) -> Self {
223        self.details = details;
224        self
225    }
226
227    pub fn compact(mut self, compact: bool) -> Self {
228        self.compact = compact;
229        self
230    }
231
232    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
233        self.label = label.into();
234        self
235    }
236
237    pub fn complete_label(mut self, label: impl Into<SharedString>) -> Self {
238        self.complete_label = label.into();
239        self
240    }
241
242    pub fn on_step_select(
243        mut self,
244        callback: impl Fn(&usize, &mut Window, &mut App) + 'static,
245    ) -> Self {
246        self.on_step_select = Some(Rc::new(callback));
247        self
248    }
249}
250
251impl RenderOnce for Stepper {
252    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
253        let theme = cx.arc_theme();
254        let colors = theme.colors;
255        let motion = theme.motion;
256        let reduced = is_reduced_motion(cx);
257        let now = motion_now(cx);
258
259        let count = self.steps.len();
260        let active = self.current.min(count);
261        let interactive = self.on_step_select.is_some();
262        let vertical = self.orientation == StepperOrientation::Vertical;
263
264        let state_cell = window
265            .use_keyed_state(
266                ElementId::NamedChild(self.id.clone().into(), SharedString::from("stepper-travel")),
267                cx,
268                |_, cx| {
269                    Rc::new(RefCell::new(StepperTravelState {
270                        from_active: active,
271                        to_active: active,
272                        transition_started_at: now - 10.0,
273                        focused_index: active.min(count.saturating_sub(1)),
274                        pressed_index: None,
275                        focus_handle: cx.focus_handle(),
276                    }))
277                },
278            )
279            .read(cx)
280            .clone();
281
282        let (from_active, transition_started_at, pressed_index, focus_handle) = {
283            let mut st = state_cell.borrow_mut();
284            if st.to_active != active {
285                st.from_active = st.to_active;
286                st.to_active = active;
287                st.transition_started_at = now;
288                st.focused_index = active.min(count.saturating_sub(1));
289            }
290            (
291                st.from_active,
292                st.transition_started_at,
293                st.pressed_index,
294                st.focus_handle.clone(),
295            )
296        };
297
298        let elapsed = (now - transition_started_at).max(0.0);
299        let ring_delay = stepper_ring_delay(from_active, active, reduced);
300        let ring_progress = if reduced {
301            1.0
302        } else if elapsed <= ring_delay {
303            0.0
304        } else {
305            let t = ((elapsed - ring_delay) / 0.22).clamp(0.0, 1.0) as f32;
306            CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t)
307        };
308
309        let mut needs_anim_frame = !reduced && elapsed < (ring_delay + 0.45);
310
311        let mut step_elements: Vec<AnyElement> = Vec::with_capacity(count);
312        for (index, step) in self.steps.iter().enumerate() {
313            let is_current = index == active;
314            let has_error = step.error.is_some();
315            let status = if has_error {
316                StepperStatus::Error
317            } else if index < active {
318                StepperStatus::Complete
319            } else if is_current {
320                StepperStatus::Current
321            } else {
322                StepperStatus::Upcoming
323            };
324
325            let clickable = interactive && index < active;
326            let step_delay = stepper_step_stagger_delay(index, from_active, active, reduced);
327
328            // Connector fill progress (`0.0..=1.0`) for steps `0..count - 1`
329            let connector_target = if index < active && elapsed >= step_delay {
330                1.0
331            } else {
332                0.0
333            };
334            let connector_fill = if reduced {
335                if index < active { 1.0 } else { 0.0 }
336            } else {
337                let sample = arc_spring(
338                    ElementId::NamedChild(
339                        self.id.clone().into(),
340                        SharedString::from(format!("conn-{index}")),
341                    ),
342                    connector_target,
343                    motion.spring.smooth,
344                    window,
345                    cx,
346                );
347                if (sample - connector_target).abs() > 0.002 {
348                    needs_anim_frame = true;
349                }
350                sample.clamp(0.0, 1.0)
351            };
352
353            let (pop_scale, stroke_progress, dot_scale) =
354                stepper_glyph_draw_sample(elapsed, step_delay, reduced);
355            if !reduced
356                && (status == StepperStatus::Complete || status == StepperStatus::Error)
357                && elapsed < step_delay + 0.38
358            {
359                needs_anim_frame = true;
360            }
361
362            let is_pressed = clickable && pressed_index == Some(index);
363            let disc_press_scale = if is_pressed && !reduced { 0.92 } else { 1.0 };
364
365            let (disc_bg, disc_border, disc_fg, halo_color) = match status {
366                StepperStatus::Complete => (
367                    colors.accent,
368                    colors.accent,
369                    colors.accent_foreground,
370                    colors.accent_subtle,
371                ),
372                StepperStatus::Current => (
373                    colors.surface,
374                    colors.accent,
375                    colors.foreground,
376                    colors.accent_subtle,
377                ),
378                StepperStatus::Error => (
379                    oklab_mix(colors.danger, colors.surface, 0.10),
380                    colors.danger,
381                    colors.danger,
382                    oklab_mix(colors.danger, colors.surface, 0.16),
383                ),
384                StepperStatus::Upcoming => (
385                    colors.surface,
386                    colors.border_strong,
387                    colors.text_muted,
388                    colors.accent_subtle,
389                ),
390            };
391
392            let border_width = match status {
393                StepperStatus::Current | StepperStatus::Error => 1.5,
394                _ => 1.0,
395            };
396
397            let show_ring = is_current || status == StepperStatus::Error;
398            let ring_alpha = if is_current {
399                ring_progress
400            } else if status == StepperStatus::Error {
401                1.0
402            } else {
403                0.0
404            };
405
406            let step_num_text = SharedString::from(format!("{}", index + 1));
407
408            // Marker canvas (halo ring + 28px disc + vector check / alert glyph)
409            let marker = div()
410                .relative()
411                .size(px(STEPPER_MARKER_SIZE_PX))
412                .flex_none()
413                .flex()
414                .items_center()
415                .justify_center()
416                .child(
417                    canvas(
418                        move |bounds, _window, _cx| bounds,
419                        move |bounds: Bounds<gpui_kit::Pixels>, _, window, _cx| {
420                            let cx_pt = bounds.origin.x + bounds.size.width * 0.5;
421                            let cy_pt = bounds.origin.y + bounds.size.height * 0.5;
422
423                            // 1. Halo ring behind the disc
424                            if show_ring && ring_alpha > 0.01 {
425                                let ring_scale = 0.6 + 0.4 * ring_alpha;
426                                let full_extent =
427                                    (STEPPER_MARKER_SIZE_PX + STEPPER_HALO_PX * 2.0) * ring_scale;
428                                let half = full_extent * 0.5;
429                                let mut c = halo_color;
430                                c.a *= ring_alpha;
431                                window.paint_quad(quad(
432                                    Bounds::new(
433                                        point(cx_pt - px(half), cy_pt - px(half)),
434                                        gpui_kit::size(px(full_extent), px(full_extent)),
435                                    ),
436                                    Corners::all(px(full_extent)),
437                                    c,
438                                    Edges::all(px(0.0)),
439                                    gpui_kit::transparent_black(),
440                                    gpui_kit::BorderStyle::default(),
441                                ));
442                            }
443
444                            // 2. Disc
445                            let disc_size = STEPPER_MARKER_SIZE_PX * disc_press_scale;
446                            let disc_half = disc_size * 0.5;
447                            window.paint_quad(quad(
448                                Bounds::new(
449                                    point(cx_pt - px(disc_half), cy_pt - px(disc_half)),
450                                    gpui_kit::size(px(disc_size), px(disc_size)),
451                                ),
452                                Corners::all(px(disc_size)),
453                                disc_bg,
454                                Edges::all(px(border_width)),
455                                disc_border,
456                                gpui_kit::BorderStyle::default(),
457                            ));
458
459                            // 3. Vector check or error glyph inside 14x14 icon box (24x24 viewBox)
460                            let icon_scale = (14.0 / 24.0) * pop_scale * disc_press_scale;
461                            let map_pt = |vx: f32, vy: f32| {
462                                point(
463                                    cx_pt + px((vx - 12.0) * icon_scale),
464                                    cy_pt + px((vy - 12.0) * icon_scale),
465                                )
466                            };
467
468                            if status == StepperStatus::Complete && stroke_progress > 0.01 {
469                                let path = PolylinePath::new(vec![
470                                    PathPoint::new(5.5, 12.5),
471                                    PathPoint::new(9.75, 16.75),
472                                    PathPoint::new(18.5, 8.0),
473                                ]);
474                                let sliced = path.slice(0.0, stroke_progress);
475                                let pts = &sliced.points;
476                                if pts.len() >= 2 {
477                                    let mut builder = PathBuilder::stroke(px(2.0 * pop_scale));
478                                    builder.move_to(map_pt(pts[0].x, pts[0].y));
479                                    for p in &pts[1..] {
480                                        builder.line_to(map_pt(p.x, p.y));
481                                    }
482                                    if let Ok(stroke) = builder.build() {
483                                        window.paint_path(stroke, disc_fg);
484                                    }
485                                }
486                            } else if status == StepperStatus::Error {
487                                if stroke_progress > 0.01 {
488                                    let y_end = 6.75 + 6.5 * stroke_progress;
489                                    let mut builder = PathBuilder::stroke(px(2.0 * pop_scale));
490                                    builder.move_to(map_pt(12.0, 6.75));
491                                    builder.line_to(map_pt(12.0, y_end));
492                                    if let Ok(stroke) = builder.build() {
493                                        window.paint_path(stroke, disc_fg);
494                                    }
495                                }
496                                if dot_scale > 0.01 {
497                                    let r = 1.6 * dot_scale * disc_press_scale;
498                                    let dot_center = map_pt(12.0, 17.4);
499                                    window.paint_quad(quad(
500                                        Bounds::new(
501                                            point(dot_center.x - px(r), dot_center.y - px(r)),
502                                            gpui_kit::size(px(r * 2.0), px(r * 2.0)),
503                                        ),
504                                        Corners::all(px(r * 2.0)),
505                                        disc_fg,
506                                        Edges::all(px(0.0)),
507                                        gpui_kit::transparent_black(),
508                                        gpui_kit::BorderStyle::default(),
509                                    ));
510                                }
511                            }
512                        },
513                    )
514                    .size_full(),
515                )
516                .when(
517                    status == StepperStatus::Current || status == StepperStatus::Upcoming,
518                    |this| {
519                        this.child(
520                            div()
521                                .text_size(Typography::TEXT_XS)
522                                .font_medium()
523                                .text_color(disc_fg)
524                                .child(step_num_text),
525                        )
526                    },
527                );
528
529            let detail_text: Option<(SharedString, bool)> = if let Some(err) = &step.error {
530                Some((err.clone(), true))
531            } else if self.details == StepperDetails::All || is_current {
532                step.description.clone().map(|d| (d, false))
533            } else {
534                None
535            };
536
537            let label_color = match status {
538                StepperStatus::Complete => colors.text_secondary,
539                StepperStatus::Current | StepperStatus::Error => colors.foreground,
540                StepperStatus::Upcoming => colors.text_muted,
541            };
542
543            let text_block = if self.compact {
544                None
545            } else {
546                Some(
547                    div()
548                        .min_w_0()
549                        .flex()
550                        .flex_col()
551                        .gap(px(2.0))
552                        .when(vertical, |this| this.pt(px(3.0)))
553                        .child(
554                            div()
555                                .text_size(Typography::TEXT_SM)
556                                .font_medium()
557                                .text_color(label_color)
558                                .child(step.label.clone()),
559                        )
560                        .when_some(detail_text, |this, (txt, is_err)| {
561                            this.child(
562                                div()
563                                    .text_size(Typography::TEXT_XS)
564                                    .text_color(if is_err {
565                                        colors.danger
566                                    } else {
567                                        colors.text_muted
568                                    })
569                                    .child(txt),
570                            )
571                        }),
572                )
573            };
574
575            // Marker row + horizontal connector or vertical side-by-side head
576            let is_last = index + 1 == count;
577            let select_cb = self.on_step_select.clone();
578            let press_state = state_cell.clone();
579            let up_state = state_cell.clone();
580
581            let item_el = if vertical {
582                div()
583                    .id(ElementId::NamedChild(
584                        self.id.clone().into(),
585                        SharedString::from(format!("step-{index}")),
586                    ))
587                    .w_full()
588                    .flex()
589                    .flex_row()
590                    .items_stretch()
591                    .gap(Spacing::S3)
592                    .when(clickable, |this| this.cursor_pointer())
593                    .on_mouse_down(MouseButton::Left, move |_, window, _cx| {
594                        if clickable {
595                            press_state.borrow_mut().pressed_index = Some(index);
596                            window.refresh();
597                        }
598                    })
599                    .on_mouse_up(MouseButton::Left, move |_, window, cx| {
600                        let was_pressed = up_state.borrow_mut().pressed_index.take().is_some();
601                        if clickable && was_pressed {
602                            if let Some(cb) = &select_cb {
603                                cb(&index, window, cx);
604                            }
605                            window.refresh();
606                        }
607                    })
608                    .child(
609                        div()
610                            .w(px(STEPPER_MARKER_SIZE_PX))
611                            .flex_none()
612                            .flex()
613                            .flex_col()
614                            .items_center()
615                            .child(marker)
616                            .when(!is_last, |this| {
617                                this.child(
618                                    div()
619                                        .w(px(2.0))
620                                        .flex_1()
621                                        .min_h(if self.compact { px(24.0) } else { px(28.0) })
622                                        .my(px(6.0))
623                                        .rounded(Radii::PILL)
624                                        .bg(colors.border)
625                                        .overflow_hidden()
626                                        .child(
627                                            div()
628                                                .w_full()
629                                                .h(gpui_kit::relative(connector_fill))
630                                                .rounded(Radii::PILL)
631                                                .bg(colors.accent),
632                                        ),
633                                )
634                            }),
635                    )
636                    .when_some(text_block, |this, tb| {
637                        this.child(
638                            div()
639                                .flex_1()
640                                .min_w_0()
641                                .when(!is_last, |d| d.pb(Spacing::S5))
642                                .child(tb),
643                        )
644                    })
645                    .into_any_element()
646            } else {
647                // Horizontal step item
648                let mut col = div()
649                    .id(ElementId::NamedChild(
650                        self.id.clone().into(),
651                        SharedString::from(format!("step-{index}")),
652                    ))
653                    .min_w_0()
654                    .flex()
655                    .flex_col()
656                    .gap(Spacing::S3)
657                    .when(!is_last, |this| this.flex_1().pr(Spacing::S3))
658                    .when(is_last, |this| this.flex_none())
659                    .when(clickable, |this| this.cursor_pointer())
660                    .on_mouse_down(MouseButton::Left, move |_, window, _cx| {
661                        if clickable {
662                            press_state.borrow_mut().pressed_index = Some(index);
663                            window.refresh();
664                        }
665                    })
666                    .on_mouse_up(MouseButton::Left, move |_, window, cx| {
667                        let was_pressed = up_state.borrow_mut().pressed_index.take().is_some();
668                        if clickable && was_pressed {
669                            if let Some(cb) = &select_cb {
670                                cb(&index, window, cx);
671                            }
672                            window.refresh();
673                        }
674                    })
675                    .child(
676                        div()
677                            .w_full()
678                            .flex()
679                            .flex_row()
680                            .items_center()
681                            .child(marker)
682                            .when(!is_last, |this| {
683                                this.child(
684                                    div()
685                                        .flex_1()
686                                        .h(px(2.0))
687                                        .ml(px(8.0))
688                                        .rounded(Radii::PILL)
689                                        .bg(colors.border)
690                                        .overflow_hidden()
691                                        .child(
692                                            div()
693                                                .h_full()
694                                                .w(gpui_kit::relative(connector_fill))
695                                                .rounded(Radii::PILL)
696                                                .bg(colors.accent),
697                                        ),
698                                )
699                            }),
700                    );
701
702                if let Some(tb) = text_block {
703                    col = col.child(tb);
704                }
705                col.into_any_element()
706            };
707
708            step_elements.push(item_el);
709        }
710
711        if needs_anim_frame {
712            window.request_animation_frame();
713        }
714
715        // Compact horizontal caption underneath the markers
716        let compact_caption = if !vertical && self.compact {
717            let current_step = self.steps.get(active);
718            let title = current_step
719                .map(|s| s.label.clone())
720                .unwrap_or_else(|| self.complete_label.clone());
721            let sub: Option<(SharedString, bool)> = current_step.and_then(|s| {
722                if let Some(err) = &s.error {
723                    Some((err.clone(), true))
724                } else {
725                    s.description.clone().map(|d| (d, false))
726                }
727            });
728
729            Some(
730                div()
731                    .mt(Spacing::S3)
732                    .flex()
733                    .flex_col()
734                    .gap(px(2.0))
735                    .child(
736                        div()
737                            .text_size(Typography::TEXT_SM)
738                            .font_medium()
739                            .text_color(colors.foreground)
740                            .child(title),
741                    )
742                    .when_some(sub, |this, (txt, is_err)| {
743                        this.child(
744                            div()
745                                .text_size(Typography::TEXT_XS)
746                                .text_color(if is_err {
747                                    colors.danger
748                                } else {
749                                    colors.text_muted
750                                })
751                                .child(txt),
752                        )
753                    }),
754            )
755        } else {
756            None
757        };
758
759        let key_state = state_cell.clone();
760        let key_cb = self.on_step_select.clone();
761        let max_reachable = active.min(count.saturating_sub(1));
762
763        div()
764            .id(self.id)
765            .role(Role::Group)
766            .track_focus(&focus_handle)
767            .w_full()
768            .flex()
769            .flex_col()
770            .on_key_down(move |event: &KeyDownEvent, window, cx| {
771                if !interactive || count == 0 {
772                    return;
773                }
774                let key = event.keystroke.key.as_str();
775                let mut st = key_state.borrow_mut();
776                match key {
777                    "left" | "arrowleft" | "up" | "arrowup" => {
778                        st.focused_index = st.focused_index.saturating_sub(1);
779                    }
780                    "right" | "arrowright" | "down" | "arrowdown" => {
781                        st.focused_index = (st.focused_index + 1).min(max_reachable);
782                    }
783                    "home" => {
784                        st.focused_index = 0;
785                    }
786                    "end" => {
787                        st.focused_index = max_reachable;
788                    }
789                    "enter" | " " | "space" => {
790                        let target = st.focused_index;
791                        drop(st);
792                        if target < active
793                            && let Some(cb) = &key_cb
794                        {
795                            cb(&target, window, cx);
796                        }
797                        window.refresh();
798                        return;
799                    }
800                    _ => return,
801                }
802                window.refresh();
803            })
804            .child(
805                div()
806                    .w_full()
807                    .flex()
808                    .when(vertical, |this| this.flex_col())
809                    .when(!vertical, |this| this.flex_row().items_start())
810                    .children(step_elements),
811            )
812            .when_some(compact_caption, |this, cap| this.child(cap))
813    }
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819
820    #[test]
821    fn stepper_step_stagger_delay_cascades_forward_and_backward() {
822        let gap = STEPPER_LINE_STAGGER_SECS;
823        // Forward jump from step 0 -> step 3: connectors 0, 1, 2 stagger in order
824        assert!((stepper_step_stagger_delay(0, 0, 3, false) - 0.0).abs() < 1e-6);
825        assert!((stepper_step_stagger_delay(1, 0, 3, false) - gap).abs() < 1e-6);
826        assert!((stepper_step_stagger_delay(2, 0, 3, false) - 2.0 * gap).abs() < 1e-6);
827        assert!((stepper_step_stagger_delay(3, 0, 3, false) - 0.0).abs() < 1e-6);
828
829        // Backward jump from step 3 -> step 0: connectors 2, 1, 0 drain in reverse order
830        assert!((stepper_step_stagger_delay(2, 3, 0, false) - 0.0).abs() < 1e-6);
831        assert!((stepper_step_stagger_delay(1, 3, 0, false) - gap).abs() < 1e-6);
832        assert!((stepper_step_stagger_delay(0, 3, 0, false) - 2.0 * gap).abs() < 1e-6);
833
834        // Ring delay waits for multi-step connector cascade + 120ms
835        assert!((stepper_ring_delay(0, 3, false) - (2.0 * gap + 0.12)).abs() < 1e-6);
836        assert_eq!(stepper_ring_delay(0, 3, true), 0.0);
837    }
838
839    #[test]
840    fn stepper_glyph_draw_sample_draws_stroke_and_dot_on_schedule() {
841        let (scale0, stroke0, dot0) = stepper_glyph_draw_sample(0.0, 0.0, false);
842        assert!((scale0 - 0.5).abs() < 1e-5);
843        assert_eq!(stroke0, 0.0);
844        assert_eq!(dot0, 0.0);
845
846        let (scale_mid, stroke_mid, dot_mid) = stepper_glyph_draw_sample(0.15, 0.0, false);
847        assert!(scale_mid > 0.8);
848        assert!(stroke_mid > 0.3 && stroke_mid < 1.0);
849        assert_eq!(dot_mid, 0.0);
850
851        let (scale_done, stroke_done, dot_done) = stepper_glyph_draw_sample(0.40, 0.0, false);
852        assert!((scale_done - 1.0).abs() < 1e-5);
853        assert!((stroke_done - 1.0).abs() < 1e-5);
854        assert!((dot_done - 1.0).abs() < 1e-5);
855    }
856}