use std::{
cell::RefCell,
collections::{HashMap, HashSet},
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, Hsla, IntoElement,
KeyDownEvent, MouseButton, ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled,
Window, assets::IconName, base::StyledExt as _, canvas, div, point, prelude::*, px, quad, svg,
};
use crate::text::animated_counter::AnimatedCounter;
type CompletedChangeCallback = Rc<dyn Fn(&Vec<SharedString>, &mut Window, &mut App)>;
type HiddenChangeCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
type StepActionCallback =
Rc<dyn Fn(&SharedString, &mut Window, &mut App) -> Result<(), SharedString>>;
pub const ONBOARDING_SETTLE_SECS: f64 = 0.72;
#[derive(Clone)]
pub struct OnboardingStep {
pub id: SharedString,
pub title: SharedString,
pub description: Option<SharedString>,
pub action_label: Option<SharedString>,
pub on_action: Option<StepActionCallback>,
}
impl OnboardingStep {
pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
description: None,
action_label: None,
on_action: None,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn action_label(mut self, label: impl Into<SharedString>) -> Self {
self.action_label = Some(label.into());
self
}
pub fn on_action(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) -> Result<(), SharedString> + 'static,
) -> Self {
self.on_action = Some(Rc::new(handler));
self
}
}
pub fn onboarding_ordered_ids(
ids: &[SharedString],
step_ids: &[SharedString],
) -> Vec<SharedString> {
let set: HashSet<&str> = ids.iter().map(SharedString::as_ref).collect();
let mut out = Vec::new();
for id in step_ids {
if set.contains(id.as_ref()) && !out.iter().any(|existing: &SharedString| existing == id) {
out.push(id.clone());
}
}
out
}
pub fn onboarding_next_expanded_id(
step_ids: &[SharedString],
done_ids: &[SharedString],
current_expanded: Option<&str>,
just_settled_id: &str,
) -> Option<SharedString> {
if step_ids.is_empty() {
return None;
}
if current_expanded != Some(just_settled_id) {
return current_expanded.map(|s| SharedString::from(s.to_string()));
}
let done_set: HashSet<&str> = done_ids.iter().map(SharedString::as_ref).collect();
let start = step_ids
.iter()
.position(|id| id.as_ref() == just_settled_id)
.unwrap_or(0);
let len = step_ids.len();
for offset in 0..len {
let candidate = &step_ids[(start + offset + 1) % len];
if !done_set.contains(candidate.as_ref()) {
return Some(candidate.clone());
}
}
None
}
#[inline]
pub fn onboarding_strike_progress(is_done: bool, elapsed_since_toggle: f64, reduced: bool) -> f32 {
if reduced {
return if is_done { 1.0 } else { 0.0 };
}
let ease_enter = CubicBezier::new(0.22, 1.0, 0.36, 1.0);
let ease_standard = CubicBezier::new(0.4, 0.0, 0.2, 1.0);
if is_done {
let delay = 0.08;
let duration = 0.32;
if elapsed_since_toggle <= delay {
0.0
} else {
let t = ((elapsed_since_toggle - delay) / duration).clamp(0.0, 1.0) as f32;
ease_enter.sample(t).clamp(0.0, 1.0)
}
} else {
let duration = 0.14;
let t = (elapsed_since_toggle / duration).clamp(0.0, 1.0) as f32;
(1.0_f32 - ease_standard.sample(t)).clamp(0.0, 1.0)
}
}
#[derive(Clone)]
struct ChecklistInternalState {
done: Vec<SharedString>,
settled: Vec<SharedString>,
settle_deadlines: HashMap<SharedString, (f64, f64)>, uncheck_times: HashMap<SharedString, f64>,
expanded: Option<SharedString>,
pending: HashSet<SharedString>,
errors: HashMap<SharedString, SharedString>,
group_open: bool,
hidden: bool,
complete_since: Option<f64>,
focus_handle: FocusHandle,
focused_index: usize,
measured_panel_heights: Rc<RefCell<HashMap<SharedString, f32>>>,
measured_row_heights: Rc<RefCell<HashMap<SharedString, f32>>>,
measured_completed_height: Rc<RefCell<f32>>,
measured_body_height: Rc<RefCell<f32>>,
}
#[derive(IntoElement)]
pub struct OnboardingChecklist {
id: ElementId,
title: SharedString,
done_title: SharedString,
steps: Vec<OnboardingStep>,
default_completed: Vec<SharedString>,
completed_override: Option<Vec<SharedString>>,
default_hidden: bool,
hidden_override: Option<bool>,
hide_label: SharedString,
show_label: SharedString,
completed_suffix: SharedString,
on_completed_change: Option<CompletedChangeCallback>,
on_hidden_change: Option<HiddenChangeCallback>,
}
impl OnboardingChecklist {
pub fn new(
id: impl Into<ElementId>,
title: impl Into<SharedString>,
steps: impl IntoIterator<Item = OnboardingStep>,
) -> Self {
Self {
id: id.into(),
title: title.into(),
done_title: "You’re all set".into(),
steps: steps.into_iter().collect(),
default_completed: Vec::new(),
completed_override: None,
default_hidden: false,
hidden_override: None,
hide_label: "Hide".into(),
show_label: "Show".into(),
completed_suffix: "completed".into(),
on_completed_change: None,
on_hidden_change: None,
}
}
pub fn done_title(mut self, done_title: impl Into<SharedString>) -> Self {
self.done_title = done_title.into();
self
}
pub fn default_completed(
mut self,
completed: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.default_completed = completed.into_iter().map(Into::into).collect();
self
}
pub fn completed(
mut self,
completed: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.completed_override = Some(completed.into_iter().map(Into::into).collect());
self
}
pub fn default_hidden(mut self, hidden: bool) -> Self {
self.default_hidden = hidden;
self
}
pub fn hidden(mut self, hidden: bool) -> Self {
self.hidden_override = Some(hidden);
self
}
pub fn hide_show_labels(
mut self,
hide_label: impl Into<SharedString>,
show_label: impl Into<SharedString>,
) -> Self {
self.hide_label = hide_label.into();
self.show_label = show_label.into();
self
}
pub fn completed_suffix(mut self, suffix: impl Into<SharedString>) -> Self {
self.completed_suffix = suffix.into();
self
}
pub fn on_completed_change(
mut self,
handler: impl Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_completed_change = Some(Rc::new(handler));
self
}
pub fn on_hidden_change(
mut self,
handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_hidden_change = Some(Rc::new(handler));
self
}
}
fn paint_progress_ring(
bounds: Bounds<gpui_kit::Pixels>,
ratio: f32,
tick_draw: f32,
track_color: Hsla,
fill_color: Hsla,
window: &mut Window,
) {
let cx_px = bounds.origin.x + bounds.size.width * 0.5;
let cy_px = bounds.origin.y + bounds.size.height * 0.5;
let scale = (bounds.size.width / px(40.0)).min(bounds.size.height / px(40.0));
let r = 17.0 * scale;
let stroke_w = px(3.0 * scale);
let segments = 48;
let mut track_builder = PathBuilder::stroke(stroke_w);
for i in 0..=segments {
let angle = (i as f32 / segments as f32) * std::f32::consts::TAU;
let pt = point(cx_px + px(r * angle.cos()), cy_px + px(r * angle.sin()));
if i == 0 {
track_builder.move_to(pt);
} else {
track_builder.line_to(pt);
}
}
if let Ok(path) = track_builder.build() {
window.paint_path(path, track_color);
}
let clamped = ratio.clamp(0.0, 1.0);
if clamped > 0.005 {
let active_segs = ((segments as f32 * clamped).ceil() as usize).max(2);
let mut arc_builder = PathBuilder::stroke(stroke_w);
for i in 0..=active_segs {
let frac = (i as f32 / active_segs as f32) * clamped;
let angle = -std::f32::consts::FRAC_PI_2 + frac * std::f32::consts::TAU;
let pt = point(cx_px + px(r * angle.cos()), cy_px + px(r * angle.sin()));
if i == 0 {
arc_builder.move_to(pt);
} else {
arc_builder.line_to(pt);
}
}
if let Ok(path) = arc_builder.build() {
window.paint_path(path, fill_color);
}
}
if tick_draw > 0.01 {
let poly = PolylinePath::new(vec![
PathPoint::new(13.5, 20.5),
PathPoint::new(18.0, 25.0),
PathPoint::new(26.5, 15.5),
]);
let sliced = poly.slice(0.0, tick_draw.clamp(0.0, 1.0));
if sliced.points.len() >= 2 {
let mut tick_builder = PathBuilder::stroke(px(2.25 * scale));
for (idx, pt) in sliced.points.iter().enumerate() {
let p = point(
bounds.origin.x + px(pt.x * scale),
bounds.origin.y + px(pt.y * scale),
);
if idx == 0 {
tick_builder.move_to(p);
} else {
tick_builder.line_to(p);
}
}
if let Ok(path) = tick_builder.build() {
window.paint_path(path, fill_color);
}
}
}
}
struct CheckboxDiscColors {
border: Hsla,
surface: Hsla,
accent: Hsla,
tick: Hsla,
}
fn paint_checkbox_disc(
bounds: Bounds<gpui_kit::Pixels>,
fill_scale: f32,
tick_draw: f32,
colors: CheckboxDiscColors,
window: &mut Window,
) {
let CheckboxDiscColors {
border: border_color,
surface: surface_color,
accent: accent_color,
tick: tick_color,
} = colors;
let size = bounds.size.width.min(bounds.size.height);
let radius = size * 0.5;
window.paint_quad(quad(
bounds,
Corners::all(radius),
surface_color,
Edges::all(px(1.5)),
border_color,
gpui_kit::BorderStyle::Solid,
));
let s = fill_scale.clamp(0.0, 1.0);
if s > 0.02 {
let fill_size = size * s;
let offset = (size - fill_size) * 0.5;
let fill_bounds = Bounds::new(
point(bounds.origin.x + offset, bounds.origin.y + offset),
gpui_kit::size(fill_size, fill_size),
);
window.paint_quad(quad(
fill_bounds,
Corners::all(fill_size * 0.5),
accent_color.opacity(s),
Edges::all(px(0.0)),
gpui_kit::transparent_black(),
gpui_kit::BorderStyle::Solid,
));
}
if tick_draw > 0.01 {
let scale = (size / px(22.0)).max(0.5);
let poly = PolylinePath::new(vec![
PathPoint::new(6.75, 11.25),
PathPoint::new(9.75, 14.25),
PathPoint::new(15.25, 8.25),
]);
let sliced = poly.slice(0.0, tick_draw.clamp(0.0, 1.0));
if sliced.points.len() >= 2 {
let mut builder = PathBuilder::stroke(px(1.85 * scale));
for (idx, pt) in sliced.points.iter().enumerate() {
let p = point(
bounds.origin.x + px(pt.x * scale),
bounds.origin.y + px(pt.y * scale),
);
if idx == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, tick_color);
}
}
}
}
impl RenderOnce for OnboardingChecklist {
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 ease_enter = CubicBezier::new(0.22, 1.0, 0.36, 1.0);
let step_ids: Vec<SharedString> = self.steps.iter().map(|s| s.id.clone()).collect();
let init_done = onboarding_ordered_ids(&self.default_completed, &step_ids);
let init_expanded = step_ids.iter().find(|id| !init_done.contains(id)).cloned();
let init_hidden = self.default_hidden;
let state_cell = window
.use_keyed_state(
(self.id.clone(), "onboarding-checklist-state"),
cx,
|_, cx| {
Rc::new(RefCell::new(ChecklistInternalState {
done: init_done.clone(),
settled: init_done,
settle_deadlines: HashMap::new(),
uncheck_times: HashMap::new(),
expanded: init_expanded,
pending: HashSet::new(),
errors: HashMap::new(),
group_open: false,
hidden: init_hidden,
complete_since: None,
focus_handle: cx.focus_handle(),
focused_index: 0,
measured_panel_heights: Rc::new(RefCell::new(HashMap::new())),
measured_row_heights: Rc::new(RefCell::new(HashMap::new())),
measured_completed_height: Rc::new(RefCell::new(0.0)),
measured_body_height: Rc::new(RefCell::new(260.0)),
}))
},
)
.read(cx)
.clone();
let mut request_anim = false;
{
let mut st = state_cell.borrow_mut();
if let Some(ref ext_done) = self.completed_override {
let ordered = onboarding_ordered_ids(ext_done, &step_ids);
if st.done != ordered {
st.done = ordered.clone();
st.settled = ordered;
st.settle_deadlines.clear();
st.expanded = step_ids.iter().find(|id| !st.done.contains(id)).cloned();
}
}
if let Some(ext_hidden) = self.hidden_override {
st.hidden = ext_hidden;
}
let mut newly_settled = Vec::new();
for (id, &(_checked_at, deadline)) in st.settle_deadlines.iter() {
if now >= deadline {
newly_settled.push(id.clone());
} else {
request_anim = true;
}
}
for id in newly_settled {
st.settle_deadlines.remove(&id);
if st.done.contains(&id) && !st.settled.contains(&id) {
let next_exp = onboarding_next_expanded_id(
&step_ids,
&st.done,
st.expanded.as_deref(),
id.as_ref(),
);
let mut next_settled = st.settled.clone();
next_settled.push(id);
st.settled = onboarding_ordered_ids(&next_settled, &step_ids);
st.expanded = next_exp;
}
}
let all_done_now = !step_ids.is_empty() && st.done.len() == step_ids.len();
if all_done_now {
if st.complete_since.is_none() {
st.complete_since = Some(now);
}
if let Some(since) = st.complete_since
&& now - since < 0.5
{
request_anim = true;
}
} else {
st.complete_since = None;
}
}
if request_anim {
window.request_animation_frame();
}
let snapshot = state_cell.borrow().clone();
let total = self.steps.len();
let done_count = snapshot.done.len();
let all_done = total > 0 && done_count == total;
let target_ratio = if total > 0 {
done_count as f32 / total as f32
} else {
0.0
};
let anim_ratio = if reduced {
target_ratio
} else {
arc_spring(
(self.id.clone(), "ring-ratio"),
target_ratio,
motion.spring.morph,
window,
cx,
)
};
let ring_tick_draw = if all_done {
if reduced {
1.0
} else if let Some(since) = snapshot.complete_since {
let delay = 0.12;
let duration = 0.24;
if now <= since + delay {
0.0
} else {
let t = ((now - since - delay) / duration).clamp(0.0, 1.0) as f32;
ease_enter.sample(t).clamp(0.0, 1.0)
}
} else {
1.0
}
} else {
0.0
};
let open_steps: Vec<OnboardingStep> = self
.steps
.iter()
.filter(|s| !snapshot.settled.contains(&s.id))
.cloned()
.collect();
let completed_steps: Vec<OnboardingStep> = self
.steps
.iter()
.filter(|s| snapshot.settled.contains(&s.id))
.cloned()
.collect();
let header_title = if all_done {
self.done_title.clone()
} else {
self.title.clone()
};
let hide_btn_text = if snapshot.hidden {
self.show_label.clone()
} else {
self.hide_label.clone()
};
let track_color = colors.border;
let fill_color = colors.accent;
let progress_ring = div().w(px(40.0)).h(px(40.0)).flex_shrink_0().child(
canvas(
move |_, _, _| {},
move |bounds, _, window, _| {
paint_progress_ring(
bounds,
anim_ratio,
ring_tick_draw,
track_color,
fill_color,
window,
);
},
)
.size_full(),
);
let count_subline = div()
.flex()
.items_center()
.gap(px(4.0))
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(
AnimatedCounter::new((self.id.clone(), "done-counter"), done_count as f64)
.decimals(0)
.text_size(Typography::TEXT_SM),
)
.child(format!("of {total} done"));
let state_for_hide = state_cell.clone();
let on_hidden_cb = self.on_hidden_change.clone();
let hide_icon = if snapshot.hidden {
IconName::ChevronDown
} else {
IconName::ChevronUp
};
let hide_btn = div()
.id((self.id.clone(), "hide-toggle"))
.h(px(32.0))
.px(Spacing::S3)
.rounded(Radii::CONTROL)
.flex()
.items_center()
.gap(Spacing::S1)
.cursor_pointer()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.text_secondary)
.hover(move |s| s.bg(colors.surface_muted).text_color(colors.foreground))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let next_hidden = {
let mut st = state_for_hide.borrow_mut();
st.hidden = !st.hidden;
st.hidden
};
if let Some(ref cb) = on_hidden_cb {
cb(&next_hidden, window, cx);
}
window.refresh();
})
.child(hide_btn_text)
.child(
svg()
.path(hide_icon.path())
.size(px(14.0))
.text_color(colors.text_secondary),
);
let header = div()
.w_full()
.p(Spacing::S5)
.flex()
.items_center()
.justify_between()
.gap(Spacing::S3)
.child(
div()
.flex()
.items_center()
.gap(Spacing::S3)
.min_w(px(0.0))
.child(progress_ring)
.child(
div()
.flex()
.flex_col()
.gap(px(2.0))
.min_w(px(0.0))
.child(
div()
.text_size(Typography::TEXT_BASE)
.font_medium()
.text_color(colors.foreground)
.child(header_title),
)
.child(count_subline),
),
)
.child(hide_btn);
let mut open_rows: Vec<AnyElement> = Vec::with_capacity(self.steps.len());
for step in &self.steps {
let step_id = step.id.clone();
let is_settled = snapshot.settled.contains(&step_id);
let is_done = snapshot.done.contains(&step_id);
let is_expanded = !is_settled && snapshot.expanded.as_ref() == Some(&step_id);
let step_err = snapshot.errors.get(&step_id).cloned();
let target_presence = if is_settled { 0.0_f32 } else { 1.0_f32 };
let row_presence = if reduced {
target_presence
} else {
arc_spring(
(self.id.clone(), format!("row-presence-{step_id}")),
target_presence,
motion.spring.smooth,
window,
cx,
)
};
let target_panel = if is_expanded { 1.0_f32 } else { 0.0_f32 };
let panel_prog = if reduced {
target_panel
} else {
arc_spring(
(self.id.clone(), format!("panel-open-{step_id}")),
target_panel,
motion.spring.smooth,
window,
cx,
)
};
if is_settled && row_presence < 0.015 {
continue;
}
let checked_elapsed = if is_done {
snapshot
.settle_deadlines
.get(&step_id)
.map(|&(checked_at, _)| (now - checked_at).max(0.0))
.unwrap_or(1.0)
} else {
snapshot
.uncheck_times
.get(&step_id)
.map(|&t| (now - t).max(0.0))
.unwrap_or(1.0)
};
let strike_prog = onboarding_strike_progress(is_done, checked_elapsed, reduced);
let target_check = if is_done { 1.0 } else { 0.0 };
let check_fill = if reduced {
target_check
} else {
arc_spring(
(self.id.clone(), format!("check-fill-{step_id}")),
target_check,
motion.spring.snappy,
window,
cx,
)
};
let check_tick = if is_done {
if reduced {
1.0
} else {
let delay = 0.05;
let duration = 0.22;
if checked_elapsed <= delay {
0.0
} else {
let t = ((checked_elapsed - delay) / duration).clamp(0.0, 1.0) as f32;
ease_enter.sample(t).clamp(0.0, 1.0)
}
}
} else {
0.0
};
let disc_border = if is_done {
colors.accent
} else {
colors.border_strong
};
let disc_surface = colors.surface;
let disc_accent = colors.accent;
let disc_tick_color = colors.accent_foreground;
let state_for_toggle = state_cell.clone();
let step_id_for_toggle = step_id.clone();
let all_ids_for_toggle = step_ids.clone();
let on_completed_cb = self.on_completed_change.clone();
let check_btn = div()
.id((self.id.clone(), format!("step-check-{step_id}")))
.w(px(40.0))
.h(px(40.0))
.flex_shrink_0()
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let t_now = motion_now(cx);
let red_now = is_reduced_motion(cx);
let updated_done = {
let mut st = state_for_toggle.borrow_mut();
if st.done.contains(&step_id_for_toggle) {
st.done.retain(|id| id != &step_id_for_toggle);
st.settled.retain(|id| id != &step_id_for_toggle);
st.settle_deadlines.remove(&step_id_for_toggle);
st.uncheck_times.insert(step_id_for_toggle.clone(), t_now);
if st.expanded.is_none() {
st.expanded = Some(step_id_for_toggle.clone());
}
} else {
let mut next_done = st.done.clone();
next_done.push(step_id_for_toggle.clone());
st.done = onboarding_ordered_ids(&next_done, &all_ids_for_toggle);
st.pending.remove(&step_id_for_toggle);
st.errors.remove(&step_id_for_toggle);
let settle_delay = if red_now {
0.18
} else {
ONBOARDING_SETTLE_SECS
};
st.settle_deadlines
.insert(step_id_for_toggle.clone(), (t_now, t_now + settle_delay));
}
st.done.clone()
};
if let Some(ref cb) = on_completed_cb {
cb(&updated_done, window, cx);
}
window.refresh();
})
.child(
div().w(px(22.0)).h(px(22.0)).child(
canvas(
move |_, _, _| {},
move |bounds, _, window, _| {
paint_checkbox_disc(
bounds,
check_fill,
check_tick,
CheckboxDiscColors {
border: disc_border,
surface: disc_surface,
accent: disc_accent,
tick: disc_tick_color,
},
window,
);
},
)
.size_full(),
),
);
let state_for_expand = state_cell.clone();
let step_id_for_expand = step_id.clone();
let title_color = if is_done {
colors.text_muted
} else {
colors.foreground
};
let title_text = step.title.clone();
let strike_color = title_color;
let title_btn = div()
.id((self.id.clone(), format!("step-title-{step_id}")))
.w_full()
.min_h(px(40.0))
.flex()
.items_center()
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, _| {
{
let mut st = state_for_expand.borrow_mut();
if st.expanded.as_ref() == Some(&step_id_for_expand) {
st.expanded = None;
} else {
st.expanded = Some(step_id_for_expand.clone());
}
}
window.refresh();
})
.child(
div()
.relative()
.flex()
.items_center()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(title_color)
.child(title_text)
.when(strike_prog > 0.01, |el| {
el.child(
div()
.absolute()
.left_0()
.top(px(10.0))
.h(px(1.5))
.w(gpui_kit::relative(strike_prog))
.bg(strike_color),
)
}),
);
let panel_el: Option<AnyElement> = if panel_prog > 0.01 {
let state_for_run = state_cell.clone();
let step_id_for_run = step_id.clone();
let all_ids_for_run = step_ids.clone();
let action_handler = step.on_action.clone();
let on_completed_for_run = self.on_completed_change.clone();
let action_btn: Option<AnyElement> = step.action_label.as_ref().map(|label| {
let label_text = label.clone();
let icon_name = if is_done {
IconName::Check
} else {
IconName::ArrowRight
};
div()
.id((self.id.clone(), format!("step-action-{step_id}")))
.mt(Spacing::S3)
.h(px(32.0))
.pl(Spacing::S4)
.pr(Spacing::S3)
.rounded(Radii::CONTROL)
.bg(colors.foreground)
.text_color(colors.background)
.text_size(Typography::TEXT_SM)
.font_medium()
.flex()
.items_center()
.gap(Spacing::S2)
.cursor_pointer()
.hover(|s| s.opacity(0.92))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let is_already_done = {
let st = state_for_run.borrow();
st.done.contains(&step_id_for_run)
|| st.pending.contains(&step_id_for_run)
};
if is_already_done {
return;
}
let result = if let Some(ref handler) = action_handler {
handler(&step_id_for_run, window, cx)
} else {
Ok(())
};
match result {
Ok(()) => {
let t_now = motion_now(cx);
let red_now = is_reduced_motion(cx);
let updated_done = {
let mut st = state_for_run.borrow_mut();
let mut next_done = st.done.clone();
next_done.push(step_id_for_run.clone());
st.done =
onboarding_ordered_ids(&next_done, &all_ids_for_run);
st.pending.remove(&step_id_for_run);
st.errors.remove(&step_id_for_run);
let settle_delay = if red_now {
0.18
} else {
ONBOARDING_SETTLE_SECS
};
st.settle_deadlines.insert(
step_id_for_run.clone(),
(t_now, t_now + settle_delay),
);
st.done.clone()
};
if let Some(ref cb) = on_completed_for_run {
cb(&updated_done, window, cx);
}
}
Err(err_msg) => {
let mut st = state_for_run.borrow_mut();
st.pending.remove(&step_id_for_run);
st.errors.insert(step_id_for_run.clone(), err_msg);
}
}
window.refresh();
})
.child(label_text)
.child(
svg()
.path(icon_name.path())
.size(px(14.0))
.text_color(colors.background),
)
.into_any_element()
});
let panel_heights_ref = snapshot.measured_panel_heights.clone();
let default_panel_h =
28.0 + if step.description.is_some() {
38.0
} else {
0.0
} + if step_err.is_some() { 26.0 } else { 0.0 }
+ if step.action_label.is_some() {
44.0
} else {
0.0
};
let natural_panel_h = panel_heights_ref
.borrow()
.get(&step_id)
.copied()
.unwrap_or(default_panel_h)
.max(24.0);
let animated_panel_h = (natural_panel_h * panel_prog.clamp(0.0, 1.0)).max(0.0);
let panel_alpha = (panel_prog * 1.25).clamp(0.0, 1.0);
let panel_dy = if reduced {
0.0
} else {
-5.0 * (1.0 - panel_prog.clamp(0.0, 1.0))
};
let measure_panel_ref = panel_heights_ref.clone();
let measure_panel_id = step_id.clone();
let inner_panel = div()
.w_full()
.pb(Spacing::S3)
.mt(px(panel_dy))
.opacity(panel_alpha)
.flex()
.flex_col()
.items_start()
.when_some(step.description.clone(), |el, desc| {
el.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.child(desc),
)
})
.when_some(step_err, |el, err| {
el.child(
div()
.pt(Spacing::S2)
.text_size(Typography::TEXT_SM)
.text_color(colors.danger)
.child(err),
)
})
.when_some(action_btn, |el, btn| el.child(btn))
.on_children_prepainted(move |children_bounds, _, _| {
let mut min_y = f32::INFINITY;
let mut max_y = f32::NEG_INFINITY;
for b in children_bounds {
min_y = min_y.min(f32::from(b.origin.y));
max_y = max_y.max(f32::from(b.origin.y + b.size.height));
}
if max_y > min_y {
let h = (max_y - min_y) + 14.0;
measure_panel_ref
.borrow_mut()
.insert(measure_panel_id.clone(), h);
}
});
let mut panel_clip = div().w_full().overflow_hidden().child(inner_panel);
if panel_prog < 0.995 {
panel_clip = panel_clip.h(px(animated_panel_h));
}
Some(panel_clip.into_any_element())
} else {
None
};
let tint_t = panel_prog.clamp(0.0, 1.0);
let row_bg = if tint_t > 0.01 {
colors.surface_muted.opacity(tint_t)
} else {
gpui_kit::transparent_black()
};
let hover_bg = if is_expanded {
colors.surface_muted
} else {
oklab_mix(colors.surface_muted, colors.surface, 0.4)
};
let row_heights_ref = snapshot.measured_row_heights.clone();
let natural_row_h = row_heights_ref
.borrow()
.get(&step_id)
.copied()
.unwrap_or(52.0)
.max(44.0);
let measure_row_ref = row_heights_ref.clone();
let measure_row_id = step_id.clone();
let row_inner = div()
.w_full()
.px(Spacing::S3)
.py(Spacing::S1)
.rounded(Radii::PANEL)
.bg(row_bg)
.hover(move |s| s.bg(hover_bg))
.flex()
.items_start()
.gap(Spacing::S3)
.child(check_btn)
.child(
div()
.flex_1()
.min_w(px(0.0))
.flex()
.flex_col()
.child(title_btn)
.when_some(panel_el, |el, p| el.child(p)),
)
.on_children_prepainted(move |children_bounds, _, _| {
let mut max_h = 0.0_f32;
for b in children_bounds {
max_h = max_h.max(f32::from(b.size.height));
}
if max_h > 20.0 {
measure_row_ref
.borrow_mut()
.insert(measure_row_id.clone(), max_h + 10.0);
}
});
let row_clamped = row_presence.clamp(0.0, 1.0);
let mut row_wrapper = div()
.w_full()
.overflow_hidden()
.opacity(row_clamped)
.child(row_inner);
if row_clamped < 0.995 {
row_wrapper = row_wrapper.h(px((natural_row_h * row_clamped).max(0.0)));
}
open_rows.push(row_wrapper.into_any_element());
}
let completed_group_el: Option<AnyElement> = if !completed_steps.is_empty() {
let state_for_group = state_cell.clone();
let group_icon = if snapshot.group_open {
IconName::ChevronUp
} else {
IconName::ChevronDown
};
let hover_group_bg = oklab_mix(colors.surface_muted, colors.surface, 0.4);
let completed_len = completed_steps.len();
let suffix = self.completed_suffix.clone();
let group_toggle = div()
.id((self.id.clone(), "completed-group-toggle"))
.w_full()
.min_h(px(44.0))
.mt(px(2.0))
.pl(px(64.0))
.pr(Spacing::S3)
.rounded(Radii::PANEL)
.flex()
.items_center()
.justify_between()
.cursor_pointer()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.text_secondary)
.hover(move |s| s.bg(hover_group_bg).text_color(colors.foreground))
.on_mouse_down(MouseButton::Left, move |_, window, _| {
{
let mut st = state_for_group.borrow_mut();
st.group_open = !st.group_open;
}
window.refresh();
})
.child(
div()
.flex()
.items_center()
.gap(px(4.0))
.child(
AnimatedCounter::new(
(self.id.clone(), "completed-group-counter"),
completed_len as f64,
)
.decimals(0)
.text_size(Typography::TEXT_SM),
)
.child(suffix),
)
.child(
svg()
.path(group_icon.path())
.size(px(14.0))
.text_color(colors.text_secondary),
);
let group_open_target = if snapshot.group_open {
1.0_f32
} else {
0.0_f32
};
let group_prog = if reduced {
group_open_target
} else {
arc_spring(
(self.id.clone(), "completed-group-open"),
group_open_target,
motion.spring.smooth,
window,
cx,
)
};
let completed_list_el: Option<AnyElement> = if group_prog > 0.01 {
let mut completed_rows: Vec<AnyElement> = Vec::with_capacity(completed_steps.len());
for step in &completed_steps {
let step_id = step.id.clone();
let state_for_uncheck = state_cell.clone();
let step_id_for_uncheck = step_id.clone();
let on_completed_cb = self.on_completed_change.clone();
let disc_border = colors.accent;
let disc_surface = colors.surface;
let disc_accent = colors.accent;
let disc_tick = colors.accent_foreground;
let strike_color = colors.text_muted;
completed_rows.push(
div()
.w_full()
.px(Spacing::S3)
.py(Spacing::S1)
.rounded(Radii::PANEL)
.hover(move |s| s.bg(hover_group_bg))
.flex()
.items_center()
.gap(Spacing::S3)
.child(
div()
.id((self.id.clone(), format!("completed-uncheck-{step_id}")))
.w(px(40.0))
.h(px(40.0))
.flex_shrink_0()
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let t_now = motion_now(cx);
let updated_done = {
let mut st = state_for_uncheck.borrow_mut();
st.done.retain(|id| id != &step_id_for_uncheck);
st.settled.retain(|id| id != &step_id_for_uncheck);
st.settle_deadlines.remove(&step_id_for_uncheck);
st.uncheck_times
.insert(step_id_for_uncheck.clone(), t_now);
if st.expanded.is_none() {
st.expanded = Some(step_id_for_uncheck.clone());
}
st.done.clone()
};
if let Some(ref cb) = on_completed_cb {
cb(&updated_done, window, cx);
}
window.refresh();
})
.child(
div().w(px(22.0)).h(px(22.0)).child(
canvas(
move |_, _, _| {},
move |bounds, _, window, _| {
paint_checkbox_disc(
bounds,
1.0,
1.0,
CheckboxDiscColors {
border: disc_border,
surface: disc_surface,
accent: disc_accent,
tick: disc_tick,
},
window,
);
},
)
.size_full(),
),
),
)
.child(
div().min_h(px(40.0)).flex().items_center().child(
div()
.relative()
.flex()
.items_center()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.text_muted)
.child(step.title.clone())
.child(
div()
.absolute()
.left_0()
.top(px(10.0))
.h(px(1.5))
.w_full()
.bg(strike_color),
),
),
)
.into_any_element(),
);
}
let completed_h_ref = snapshot.measured_completed_height.clone();
let default_completed_h = (completed_steps.len() as f32) * 48.0;
let natural_completed_h = {
let h = *completed_h_ref.borrow();
if h > 10.0 { h } else { default_completed_h }
};
let measure_completed_ref = completed_h_ref.clone();
let group_clamped = group_prog.clamp(0.0, 1.0);
let inner_completed = div()
.w_full()
.flex()
.flex_col()
.opacity((group_clamped * 1.2).clamp(0.0, 1.0))
.children(completed_rows)
.on_children_prepainted(move |children_bounds, _, _| {
let mut min_y = f32::INFINITY;
let mut max_y = f32::NEG_INFINITY;
for b in children_bounds {
min_y = min_y.min(f32::from(b.origin.y));
max_y = max_y.max(f32::from(b.origin.y + b.size.height));
}
if max_y > min_y {
*measure_completed_ref.borrow_mut() = max_y - min_y;
}
});
let mut clip = div().w_full().overflow_hidden().child(inner_completed);
if group_clamped < 0.995 {
clip = clip.h(px((natural_completed_h * group_clamped).max(0.0)));
}
Some(clip.into_any_element())
} else {
None
};
Some(
div()
.w_full()
.flex()
.flex_col()
.child(group_toggle)
.when_some(completed_list_el, |el, list| el.child(list))
.into_any_element(),
)
} else {
None
};
let body_open_target = if snapshot.hidden { 0.0_f32 } else { 1.0_f32 };
let body_prog = if reduced {
body_open_target
} else {
arc_spring(
(self.id.clone(), "body-open"),
body_open_target,
motion.spring.smooth,
window,
cx,
)
};
let body_clamped = body_prog.clamp(0.0, 1.0);
let body_el: Option<AnyElement> = if body_clamped > 0.01 {
let body_h_ref = snapshot.measured_body_height.clone();
let natural_body_h = {
let h = *body_h_ref.borrow();
if h > 20.0 { h } else { 320.0 }
};
let measure_body_ref = body_h_ref.clone();
let inner_body = div()
.w_full()
.p(Spacing::S2)
.border_t_1()
.border_color(colors.border.opacity(body_clamped))
.opacity((body_clamped * 1.15).clamp(0.0, 1.0))
.flex()
.flex_col()
.children(open_rows)
.when_some(completed_group_el, |b, grp| b.child(grp))
.on_children_prepainted(move |children_bounds, _, _| {
let mut min_y = f32::INFINITY;
let mut max_y = f32::NEG_INFINITY;
for b in children_bounds {
min_y = min_y.min(f32::from(b.origin.y));
max_y = max_y.max(f32::from(b.origin.y + b.size.height));
}
if max_y > min_y {
*measure_body_ref.borrow_mut() = (max_y - min_y) + 18.0;
}
});
let mut body_clip = div().w_full().overflow_hidden().child(inner_body);
if body_clamped < 0.995 {
body_clip = body_clip.h(px((natural_body_h * body_clamped).max(0.0)));
}
Some(body_clip.into_any_element())
} else {
None
};
let focus_handle = snapshot.focus_handle.clone();
let state_for_key = state_cell.clone();
let open_ids: Vec<SharedString> = open_steps.iter().map(|s| s.id.clone()).collect();
div()
.id(self.id)
.role(Role::Region)
.track_focus(&focus_handle)
.w_full()
.rounded(Radii::SURFACE)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.text_color(colors.foreground)
.flex()
.flex_col()
.on_key_down(move |event: &KeyDownEvent, window, _| {
if open_ids.is_empty() {
return;
}
let key = event.keystroke.key.as_str();
let mut st = state_for_key.borrow_mut();
let len = open_ids.len();
match key {
"down" | "arrowdown" => {
st.focused_index = (st.focused_index + 1) % len;
st.expanded = Some(open_ids[st.focused_index].clone());
window.refresh();
}
"up" | "arrowup" => {
st.focused_index = (st.focused_index + len - 1) % len;
st.expanded = Some(open_ids[st.focused_index].clone());
window.refresh();
}
"home" => {
st.focused_index = 0;
st.expanded = Some(open_ids[0].clone());
window.refresh();
}
"end" => {
st.focused_index = len - 1;
st.expanded = Some(open_ids[len - 1].clone());
window.refresh();
}
_ => {}
}
})
.child(header)
.when_some(body_el, |el, body| el.child(body))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn onboarding_ordered_and_next_expanded_wrap_correctly() {
let step_ids: Vec<SharedString> =
vec!["domain".into(), "dns".into(), "ssl".into(), "invite".into()];
let done: Vec<SharedString> = vec!["ssl".into(), "domain".into()];
let ordered = onboarding_ordered_ids(&done, &step_ids);
assert_eq!(
ordered,
vec![SharedString::from("domain"), SharedString::from("ssl")]
);
let next = onboarding_next_expanded_id(&step_ids, &ordered, Some("ssl"), "ssl");
assert_eq!(next, Some("invite".into()));
let done_three: Vec<SharedString> = vec!["domain".into(), "ssl".into(), "invite".into()];
let wrapped = onboarding_next_expanded_id(&step_ids, &done_three, Some("invite"), "invite");
assert_eq!(wrapped, Some("dns".into()));
}
#[test]
fn onboarding_strike_progress_respects_delay_and_reduced_motion() {
assert_eq!(onboarding_strike_progress(true, 0.0, true), 1.0);
assert_eq!(onboarding_strike_progress(false, 0.0, true), 0.0);
assert_eq!(onboarding_strike_progress(true, 0.04, false), 0.0);
let mid = onboarding_strike_progress(true, 0.22, false);
assert!(mid > 0.2 && mid < 0.99);
assert!(onboarding_strike_progress(true, 0.45, false) >= 0.99);
}
}