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)>;
pub const STEPPER_MARKER_SIZE_PX: f32 = 28.0;
pub const STEPPER_HALO_PX: f32 = 4.0;
pub const STEPPER_LINE_STAGGER_SECS: f64 = 0.045;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum StepperOrientation {
#[default]
Horizontal,
Vertical,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum StepperDetails {
#[default]
All,
Current,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum StepperStatus {
Complete,
Current,
Upcoming,
Error,
}
#[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
}
}
#[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
}
}
#[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
}
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,
}
#[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);
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));
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;
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(),
));
}
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(),
));
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),
)
}),
)
};
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 {
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();
}
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;
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);
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);
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);
}
}