1use std::collections::HashMap;
2
3use gpui::{
4 AccessibleAction, AnyElement, App, Axis, ElementId, FocusHandle, Hsla, InteractiveElement,
5 IntoElement, ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
6 Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button as BaseButton, TestSupportExt};
9use gpui_material_foundation::{color, current_material_theme, move_roving_focus, text_style};
10use gpui_material_theme::{ColorRole, Direction, StateLayer, TypeRole, TypographyEmphasis};
11
12use crate::{Icon, IconName, Text};
13
14use super::{
15 StepItem, StepSelect, StepStatus, Stepper, StepperColors, StepperOrientation,
16 resolve_step_status, step_is_interactive,
17};
18
19#[derive(Default)]
20struct StepperFocusState {
21 handles: HashMap<SharedString, FocusHandle>,
22}
23
24#[derive(Clone, Copy)]
25struct ResolvedColors {
26 active_container: Hsla,
27 active_content: Hsla,
28 completed_container: Hsla,
29 completed_content: Hsla,
30 upcoming_container: Hsla,
31 upcoming_content: Hsla,
32 error_container: Hsla,
33 error_content: Hsla,
34 disabled_container: Hsla,
35 disabled_content: Hsla,
36 connector: Hsla,
37 active_connector: Hsla,
38 label: Hsla,
39 muted_label: Hsla,
40 error_label: Hsla,
41 supporting: Hsla,
42 state_layer: Hsla,
43 ring: Hsla,
44}
45
46impl StepperColors {
47 fn resolve(self, window: &Window, cx: &App) -> ResolvedColors {
48 use ColorRole::*;
49 let theme = current_material_theme(window, cx);
50 let role = |r| color(theme.colors.color(r));
51 let on_surface = role(OnSurface);
52 ResolvedColors {
53 active_container: self.active_container.unwrap_or_else(|| role(Primary)),
54 active_content: self.active_content.unwrap_or_else(|| role(OnPrimary)),
55 completed_container: self.completed_container.unwrap_or_else(|| role(Primary)),
56 completed_content: self.completed_content.unwrap_or_else(|| role(OnPrimary)),
57 upcoming_container: self
58 .upcoming_container
59 .unwrap_or_else(|| role(SurfaceContainerHighest)),
60 upcoming_content: self
61 .upcoming_content
62 .unwrap_or_else(|| role(OnSurfaceVariant)),
63 error_container: self.error_container.unwrap_or_else(|| role(Error)),
64 error_content: self.error_content.unwrap_or_else(|| role(OnError)),
65 disabled_container: on_surface.opacity(0.12),
66 disabled_content: on_surface.opacity(0.38),
67 connector: self.connector.unwrap_or_else(|| role(OutlineVariant)),
68 active_connector: self.active_connector.unwrap_or_else(|| role(Primary)),
69 label: self.label.unwrap_or(on_surface),
70 muted_label: role(OnSurfaceVariant),
71 error_label: role(Error),
72 supporting: self.supporting.unwrap_or_else(|| role(OnSurfaceVariant)),
73 state_layer: on_surface,
74 ring: role(Secondary),
75 }
76 }
77}
78
79fn badge_colors(status: StepStatus, colors: &ResolvedColors) -> (Hsla, Hsla) {
80 match status {
81 StepStatus::Active => (colors.active_container, colors.active_content),
82 StepStatus::Completed => (colors.completed_container, colors.completed_content),
83 StepStatus::Error => (colors.error_container, colors.error_content),
84 StepStatus::Upcoming => (colors.upcoming_container, colors.upcoming_content),
85 StepStatus::Disabled => (colors.disabled_container, colors.disabled_content),
86 }
87}
88
89fn label_color(status: StepStatus, colors: &ResolvedColors) -> Hsla {
90 match status {
91 StepStatus::Active | StepStatus::Completed => colors.label,
92 StepStatus::Error => colors.error_label,
93 StepStatus::Upcoming => colors.muted_label,
94 StepStatus::Disabled => colors.disabled_content,
95 }
96}
97
98fn render_badge(
99 index: usize,
100 status: StepStatus,
101 custom_icon: Option<AnyElement>,
102 colors: &ResolvedColors,
103 window: &Window,
104 cx: &App,
105) -> AnyElement {
106 let (bg, fg) = badge_colors(status, colors);
107 let glyph = if let Some(icon) = custom_icon {
108 div().text_size(px(16.)).child(icon).into_any_element()
109 } else {
110 match status {
111 StepStatus::Completed => Icon::new(IconName::Check).size(px(16.)).into_any_element(),
112 StepStatus::Error => Icon::new(IconName::Error).size(px(16.)).into_any_element(),
113 StepStatus::Active | StepStatus::Upcoming | StepStatus::Disabled => text_style(
114 div(),
115 TypeRole::LabelMedium.style(TypographyEmphasis::Baseline),
116 1.,
117 window,
118 cx,
119 )
120 .child((index + 1).to_string())
121 .into_any_element(),
122 }
123 };
124
125 div()
126 .flex_none()
127 .size(px(28.))
128 .rounded_full()
129 .bg(bg)
130 .text_color(fg)
131 .flex()
132 .items_center()
133 .justify_center()
134 .child(glyph)
135 .into_any_element()
136}
137
138#[allow(clippy::too_many_arguments)]
139fn render_step_header(
140 stepper_id: &ElementId,
141 index: usize,
142 count: usize,
143 item_id: SharedString,
144 label: SharedString,
145 supporting: Option<SharedString>,
146 status: StepStatus,
147 custom_icon: Option<AnyElement>,
148 interactive: bool,
149 focus: FocusHandle,
150 is_tab_stop: bool,
151 on_select: Option<StepSelect>,
152 colors: &ResolvedColors,
153 rtl: bool,
154 window: &Window,
155 cx: &App,
156) -> AnyElement {
157 let badge = render_badge(index, status, custom_icon, colors, window, cx);
158 let title_color = label_color(status, colors);
159 let supporting_color = if status == StepStatus::Disabled {
160 colors.disabled_content
161 } else if status == StepStatus::Error {
162 colors.error_label
163 } else {
164 colors.supporting
165 };
166
167 let step_elem_id: ElementId = (stepper_id.clone(), item_id).into();
168
169 let labels = div()
170 .flex()
171 .flex_col()
172 .min_w_0()
173 .when(rtl, Styled::items_end)
174 .child(
175 div().text_color(title_color).child(
176 Text::new(label.clone())
177 .id((step_elem_id.clone(), "label"))
178 .role(if status == StepStatus::Active {
179 TypeRole::TitleSmall
180 } else {
181 TypeRole::BodyMedium
182 })
183 .wrap(),
184 ),
185 )
186 .children(supporting.map(|text| {
187 div().text_color(supporting_color).child(
188 Text::new(text)
189 .id((step_elem_id.clone(), "supporting"))
190 .role(TypeRole::BodySmall)
191 .wrap(),
192 )
193 }));
194
195 let row = div()
196 .flex()
197 .items_center()
198 .gap(px(10.))
199 .px(px(6.))
200 .py(px(6.))
201 .rounded(px(12.))
202 .when(rtl, Styled::flex_row_reverse)
203 .child(badge)
204 .child(labels);
205
206 let aria_name: SharedString = format!("{label}, {}", status.accessible_label()).into();
207
208 if interactive {
209 let state_layer = colors.state_layer;
210 let ring = colors.ring;
211 let click_select = on_select.clone();
212 let a11y_select = on_select;
213 BaseButton::new(step_elem_id)
214 .role(Role::Button)
215 .accessibility_label(aria_name)
216 .aria_selected(status == StepStatus::Active)
217 .aria_position_in_set(index + 1)
218 .aria_size_of_set(count)
219 .track_focus(&focus)
220 .tab_stop(is_tab_stop)
221 .rounded(px(12.))
222 .border_2()
223 .border_color(gpui::transparent_black())
224 .hover(move |style| style.bg(state_layer.opacity(StateLayer::Hover.opacity())))
225 .active(move |style| style.bg(state_layer.opacity(StateLayer::Pressed.opacity())))
226 .focus_visible(move |style| style.border_color(ring))
227 .when_some(click_select, |button, handler| {
228 button.on_click(move |_, window, cx| {
229 cx.stop_propagation();
230 handler(index, window, cx);
231 })
232 })
233 .when_some(a11y_select, |button, handler| {
234 button.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
235 handler(index, window, cx);
236 })
237 })
238 .child(row)
239 .into_any_element()
240 } else {
241 div()
242 .id(step_elem_id)
243 .test_support()
244 .role(Role::ListItem)
245 .aria_label(aria_name)
246 .aria_selected(status == StepStatus::Active)
247 .aria_position_in_set(index + 1)
248 .aria_size_of_set(count)
249 .child(row)
250 .into_any_element()
251 }
252}
253
254impl RenderOnce for Stepper {
255 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
256 let theme = current_material_theme(window, cx);
257 let direction = theme.layout.direction;
258 let rtl = direction == Direction::Rtl;
259 let colors = self.colors.resolve(window, cx);
260 let count = self.steps.len();
261
262 let focus_state = window.use_keyed_state((self.id.clone(), "stepper-focus"), cx, |_, _| {
263 StepperFocusState::default()
264 });
265 let handles: Vec<FocusHandle> = focus_state.update(cx, |state, cx| {
266 let mut previous = std::mem::take(&mut state.handles);
267 let mut ordered = Vec::with_capacity(self.steps.len());
268 for step in &self.steps {
269 let handle = previous
270 .remove(&step.id)
271 .unwrap_or_else(|| cx.focus_handle());
272 ordered.push(handle.clone());
273 state.handles.insert(step.id.clone(), handle);
274 }
275 ordered
276 });
277
278 let has_on_select = self.on_select.is_some();
279 let resolved: Vec<(StepStatus, bool)> = self
280 .steps
281 .iter()
282 .enumerate()
283 .map(|(index, step)| {
284 let status = resolve_step_status(step.status, index, self.active_step);
285 let interactive =
286 step_is_interactive(status, step.editable, self.non_linear, has_on_select);
287 (status, interactive)
288 })
289 .collect();
290
291 let tab_stop = handles
292 .iter()
293 .enumerate()
294 .position(|(ix, handle)| resolved[ix].1 && handle.is_focused(window))
295 .or_else(|| {
296 resolved
297 .iter()
298 .position(|(status, interactive)| *interactive && *status == StepStatus::Active)
299 })
300 .or_else(|| resolved.iter().position(|(_, interactive)| *interactive));
301
302 let axis = match self.orientation {
303 StepperOrientation::Horizontal => Axis::Horizontal,
304 StepperOrientation::Vertical => Axis::Vertical,
305 };
306 let nav_handles = handles.clone();
307 let nav_enabled: Vec<bool> = resolved
308 .iter()
309 .map(|(_, interactive)| *interactive)
310 .collect();
311
312 let container = div()
313 .id(self.id.clone())
314 .test_support()
315 .role(Role::List)
316 .aria_label(self.accessible_label)
317 .w_full()
318 .on_key_down(move |event, window, cx| {
319 if event.keystroke.modifiers.modified() {
320 return;
321 }
322 if !nav_handles.iter().any(|handle| handle.is_focused(window)) {
323 return;
324 }
325 let items: Vec<_> = nav_handles
326 .iter()
327 .zip(&nav_enabled)
328 .map(|(handle, enabled)| (handle, *enabled))
329 .collect();
330 if move_roving_focus(&items, &event.keystroke.key, axis, direction, window, cx)
331 .is_some()
332 {
333 cx.stop_propagation();
334 window.refresh();
335 }
336 });
337
338 match self.orientation {
339 StepperOrientation::Horizontal => {
340 let mut children: Vec<AnyElement> = Vec::with_capacity(count.saturating_mul(2));
341 for (index, step) in self.steps.into_iter().enumerate() {
342 let StepItem {
343 id: item_id,
344 label,
345 supporting,
346 icon,
347 ..
348 } = step;
349 let (status, interactive) = resolved[index];
350 let header = render_step_header(
351 &self.id,
352 index,
353 count,
354 item_id,
355 label,
356 supporting,
357 status,
358 icon,
359 interactive,
360 handles[index].clone(),
361 tab_stop == Some(index),
362 self.on_select.clone(),
363 &colors,
364 rtl,
365 window,
366 cx,
367 );
368 children.push(header);
369 if index + 1 < count {
370 let line_color = if status == StepStatus::Completed {
371 colors.active_connector
372 } else {
373 colors.connector
374 };
375 children.push(
376 div()
377 .id((self.id.clone(), format!("connector-{index}")))
378 .flex_1()
379 .min_w(px(16.))
380 .h(px(2.))
381 .mx(px(4.))
382 .rounded_full()
383 .bg(line_color)
384 .into_any_element(),
385 );
386 }
387 }
388 container
389 .flex()
390 .items_center()
391 .when(rtl, Styled::flex_row_reverse)
392 .children(children)
393 }
394 StepperOrientation::Vertical => {
395 let mut rows: Vec<AnyElement> = Vec::with_capacity(count);
396 for (index, step) in self.steps.into_iter().enumerate() {
397 let StepItem {
398 id: item_id,
399 label,
400 supporting,
401 icon,
402 content,
403 ..
404 } = step;
405 let (status, interactive) = resolved[index];
406 let show_content = content.is_some()
407 && (status == StepStatus::Active || self.active_step == Some(index));
408 let has_connector = index + 1 < count;
409 let header = render_step_header(
410 &self.id,
411 index,
412 count,
413 item_id.clone(),
414 label,
415 supporting,
416 status,
417 icon,
418 interactive,
419 handles[index].clone(),
420 tab_stop == Some(index),
421 self.on_select.clone(),
422 &colors,
423 rtl,
424 window,
425 cx,
426 );
427 let line_color = if status == StepStatus::Completed {
428 colors.active_connector
429 } else {
430 colors.connector
431 };
432 let body = (show_content || has_connector).then(|| {
433 let rail = div()
434 .w(px(40.))
435 .flex_none()
436 .flex()
437 .justify_center()
438 .py(px(2.))
439 .when(has_connector, |rail| {
440 rail.child(
441 div()
442 .w(px(2.))
443 .h_full()
444 .min_h(px(20.))
445 .rounded_full()
446 .bg(line_color),
447 )
448 });
449 div()
450 .flex()
451 .w_full()
452 .when(rtl, Styled::flex_row_reverse)
453 .child(rail)
454 .child(
455 div()
456 .flex_1()
457 .min_w_0()
458 .when(show_content, |slot| slot.py(px(8.)).children(content)),
459 )
460 });
461 rows.push(
462 div()
463 .id((self.id.clone(), format!("step-row-{index}")))
464 .flex()
465 .flex_col()
466 .w_full()
467 .child(header)
468 .children(body)
469 .into_any_element(),
470 );
471 }
472 container.flex().flex_col().children(rows)
473 }
474 }
475 }
476}