Skip to main content

gpui_material_components/navigation/stepper/
render.rs

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