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::{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 labels = div()
168        .flex()
169        .flex_col()
170        .min_w_0()
171        .when(rtl, Styled::items_end)
172        .child(
173            div().text_color(title_color).child(
174                Text::new(label.clone())
175                    .id((ElementId::from(item_id.clone()), "label"))
176                    .role(if status == StepStatus::Active {
177                        TypeRole::TitleSmall
178                    } else {
179                        TypeRole::BodyMedium
180                    })
181                    .wrap(),
182            ),
183        )
184        .children(supporting.map(|text| {
185            div().text_color(supporting_color).child(
186                Text::new(text)
187                    .id((ElementId::from(item_id.clone()), "supporting"))
188                    .role(TypeRole::BodySmall)
189                    .wrap(),
190            )
191        }));
192
193    let row = div()
194        .flex()
195        .items_center()
196        .gap(px(10.))
197        .px(px(6.))
198        .py(px(6.))
199        .rounded(px(12.))
200        .when(rtl, Styled::flex_row_reverse)
201        .child(badge)
202        .child(labels);
203
204    let aria_name: SharedString = format!("{label}, {}", status.accessible_label()).into();
205    let step_elem_id: ElementId = (stepper_id.clone(), item_id).into();
206
207    if interactive {
208        let state_layer = colors.state_layer;
209        let ring = colors.ring;
210        let click_select = on_select.clone();
211        let a11y_select = on_select;
212        BaseButton::new(step_elem_id)
213            .role(Role::ListBoxOption)
214            .accessibility_label(aria_name)
215            .aria_selected(status == StepStatus::Active)
216            .aria_position_in_set(index + 1)
217            .aria_size_of_set(count)
218            .track_focus(&focus)
219            .tab_stop(is_tab_stop)
220            .rounded(px(12.))
221            .border_2()
222            .border_color(gpui::transparent_black())
223            .hover(move |style| style.bg(state_layer.opacity(StateLayer::Hover.opacity())))
224            .active(move |style| style.bg(state_layer.opacity(StateLayer::Pressed.opacity())))
225            .focus_visible(move |style| style.border_color(ring))
226            .when_some(click_select, |button, handler| {
227                button.on_click(move |_, window, cx| {
228                    cx.stop_propagation();
229                    handler(index, window, cx);
230                })
231            })
232            .when_some(a11y_select, |button, handler| {
233                button.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
234                    handler(index, window, cx);
235                })
236            })
237            .child(row)
238            .into_any_element()
239    } else {
240        div()
241            .id(step_elem_id)
242            .test_support()
243            .role(Role::ListItem)
244            .aria_label(aria_name)
245            .aria_selected(status == StepStatus::Active)
246            .aria_position_in_set(index + 1)
247            .aria_size_of_set(count)
248            .child(row)
249            .into_any_element()
250    }
251}
252
253impl RenderOnce for Stepper {
254    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
255        let theme = current_material_theme(window, cx);
256        let direction = theme.layout.direction;
257        let rtl = direction == Direction::Rtl;
258        let colors = self.colors.resolve(window, cx);
259        let count = self.steps.len();
260
261        let focus_state = window.use_keyed_state((self.id.clone(), "stepper-focus"), cx, |_, _| {
262            StepperFocusState::default()
263        });
264        let handles: Vec<FocusHandle> = focus_state.update(cx, |state, cx| {
265            let mut previous = std::mem::take(&mut state.handles);
266            let mut ordered = Vec::with_capacity(self.steps.len());
267            for step in &self.steps {
268                let handle = previous
269                    .remove(&step.id)
270                    .unwrap_or_else(|| cx.focus_handle());
271                ordered.push(handle.clone());
272                state.handles.insert(step.id.clone(), handle);
273            }
274            ordered
275        });
276
277        let has_on_select = self.on_select.is_some();
278        let resolved: Vec<(StepStatus, bool)> = self
279            .steps
280            .iter()
281            .enumerate()
282            .map(|(index, step)| {
283                let status = resolve_step_status(step.status, index, self.active_step);
284                let interactive =
285                    step_is_interactive(status, step.editable, self.non_linear, has_on_select);
286                (status, interactive)
287            })
288            .collect();
289
290        let tab_stop = handles
291            .iter()
292            .enumerate()
293            .position(|(ix, handle)| resolved[ix].1 && handle.is_focused(window))
294            .or_else(|| {
295                resolved
296                    .iter()
297                    .position(|(status, interactive)| *interactive && *status == StepStatus::Active)
298            })
299            .or_else(|| resolved.iter().position(|(_, interactive)| *interactive));
300
301        let axis = match self.orientation {
302            StepperOrientation::Horizontal => Axis::Horizontal,
303            StepperOrientation::Vertical => Axis::Vertical,
304        };
305        let nav_handles = handles.clone();
306        let nav_enabled: Vec<bool> = resolved
307            .iter()
308            .map(|(_, interactive)| *interactive)
309            .collect();
310
311        let container = div()
312            .id(self.id.clone())
313            .test_support()
314            .role(Role::List)
315            .aria_label(self.accessible_label)
316            .w_full()
317            .on_key_down(move |event, window, cx| {
318                if !nav_handles.iter().any(|handle| handle.is_focused(window)) {
319                    return;
320                }
321                let items: Vec<_> = nav_handles
322                    .iter()
323                    .zip(&nav_enabled)
324                    .map(|(handle, enabled)| (handle, *enabled))
325                    .collect();
326                if move_roving_focus(&items, &event.keystroke.key, axis, direction, window, cx)
327                    .is_some()
328                {
329                    cx.stop_propagation();
330                    window.refresh();
331                }
332            });
333
334        match self.orientation {
335            StepperOrientation::Horizontal => {
336                let mut children: Vec<AnyElement> = Vec::with_capacity(count.saturating_mul(2));
337                for (index, step) in self.steps.into_iter().enumerate() {
338                    let StepItem {
339                        id: item_id,
340                        label,
341                        supporting,
342                        icon,
343                        ..
344                    } = step;
345                    let (status, interactive) = resolved[index];
346                    let header = render_step_header(
347                        &self.id,
348                        index,
349                        count,
350                        item_id,
351                        label,
352                        supporting,
353                        status,
354                        icon,
355                        interactive,
356                        handles[index].clone(),
357                        tab_stop == Some(index),
358                        self.on_select.clone(),
359                        &colors,
360                        rtl,
361                        window,
362                        cx,
363                    );
364                    children.push(header);
365                    if index + 1 < count {
366                        let line_color = if status == StepStatus::Completed {
367                            colors.active_connector
368                        } else {
369                            colors.connector
370                        };
371                        children.push(
372                            div()
373                                .id((self.id.clone(), format!("connector-{index}")))
374                                .flex_1()
375                                .min_w(px(16.))
376                                .h(px(2.))
377                                .mx(px(4.))
378                                .rounded_full()
379                                .bg(line_color)
380                                .into_any_element(),
381                        );
382                    }
383                }
384                container
385                    .flex()
386                    .items_center()
387                    .when(rtl, Styled::flex_row_reverse)
388                    .children(children)
389            }
390            StepperOrientation::Vertical => {
391                let mut rows: Vec<AnyElement> = Vec::with_capacity(count);
392                for (index, step) in self.steps.into_iter().enumerate() {
393                    let StepItem {
394                        id: item_id,
395                        label,
396                        supporting,
397                        icon,
398                        content,
399                        ..
400                    } = step;
401                    let (status, interactive) = resolved[index];
402                    let show_content = content.is_some()
403                        && (status == StepStatus::Active || self.active_step == Some(index));
404                    let has_connector = index + 1 < count;
405                    let header = render_step_header(
406                        &self.id,
407                        index,
408                        count,
409                        item_id.clone(),
410                        label,
411                        supporting,
412                        status,
413                        icon,
414                        interactive,
415                        handles[index].clone(),
416                        tab_stop == Some(index),
417                        self.on_select.clone(),
418                        &colors,
419                        rtl,
420                        window,
421                        cx,
422                    );
423                    let line_color = if status == StepStatus::Completed {
424                        colors.active_connector
425                    } else {
426                        colors.connector
427                    };
428                    let body = (show_content || has_connector).then(|| {
429                        let rail = div()
430                            .w(px(40.))
431                            .flex_none()
432                            .flex()
433                            .justify_center()
434                            .py(px(2.))
435                            .when(has_connector, |rail| {
436                                rail.child(
437                                    div()
438                                        .w(px(2.))
439                                        .h_full()
440                                        .min_h(px(20.))
441                                        .rounded_full()
442                                        .bg(line_color),
443                                )
444                            });
445                        div()
446                            .flex()
447                            .w_full()
448                            .when(rtl, Styled::flex_row_reverse)
449                            .child(rail)
450                            .child(
451                                div()
452                                    .flex_1()
453                                    .min_w_0()
454                                    .when(show_content, |slot| slot.py(px(8.)).children(content)),
455                            )
456                    });
457                    rows.push(
458                        div()
459                            .id((self.id.clone(), format!("step-row-{index}")))
460                            .flex()
461                            .flex_col()
462                            .w_full()
463                            .child(header)
464                            .children(body)
465                            .into_any_element(),
466                    );
467                }
468                container.flex().flex_col().children(rows)
469            }
470        }
471    }
472}