Skip to main content

gpui_material_components/navigation/
items.rs

1use std::{collections::HashMap, rc::Rc};
2
3use gpui::{
4    AccessibleAction, AnyElement, App, ElementId, Entity, FocusHandle, InteractiveElement,
5    IntoElement, ParentElement, RenderOnce, Role, ScrollHandle, SharedString,
6    StatefulInteractiveElement, Styled, TextAlign, Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button, TestSupportExt};
9use gpui_material_foundation::{animate, color, text_style, window_material_theme};
10use gpui_material_theme::{
11    ColorRole, Direction, MotionKind, MotionSpeed, TypeRole, TypographyEmphasis,
12};
13
14use crate::Icon;
15
16/// One destination or tab with an ID unique within its collection.
17pub struct NavigationItem {
18    id: SharedString,
19    label: SharedString,
20    icon: Option<Icon>,
21    disabled: bool,
22}
23
24impl NavigationItem {
25    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
26        Self {
27            id: id.into(),
28            label: label.into(),
29            icon: None,
30            disabled: false,
31        }
32    }
33
34    pub fn icon(mut self, icon: Icon) -> Self {
35        self.icon = Some(icon);
36        self
37    }
38
39    pub fn disabled(mut self, disabled: bool) -> Self {
40        self.disabled = disabled;
41        self
42    }
43}
44
45type Select = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
46
47/// Controlled destinations. Use the same collection ID across adaptive
48/// presentations to preserve focus on the destination that currently owns it.
49pub struct NavigationItems {
50    id: ElementId,
51    label: SharedString,
52    items: Vec<NavigationItem>,
53    selected: Option<SharedString>,
54    on_select: Option<Select>,
55    font_scale: f32,
56    state: Option<Entity<RowState>>,
57}
58
59impl NavigationItems {
60    pub fn new(
61        id: impl Into<ElementId>,
62        label: impl Into<SharedString>,
63        items: impl IntoIterator<Item = NavigationItem>,
64    ) -> Self {
65        Self {
66            id: id.into(),
67            label: label.into(),
68            items: items.into_iter().collect(),
69            selected: None,
70            on_select: None,
71            font_scale: 1.,
72            state: None,
73        }
74    }
75
76    pub fn selected(mut self, id: impl Into<SharedString>) -> Self {
77        self.selected = Some(id.into());
78        self
79    }
80
81    /// Reports pointer, keyboard activation and accessibility activation.
82    /// Arrow keys and Home/End move focus. The caller commits selection.
83    pub fn on_select(
84        mut self,
85        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
86    ) -> Self {
87        self.on_select = Some(Rc::new(handler));
88        self
89    }
90
91    pub fn font_scale(mut self, scale: f32) -> Self {
92        self.font_scale = if scale.is_finite() && scale > 0. {
93            scale
94        } else {
95            1.
96        };
97        self
98    }
99
100    // Resolve the state before the adaptive scaffold puts it under a different
101    // element path. Otherwise switching from its bar slot to its rail slot
102    // replaces the destination focus handles.
103    pub(super) fn retain(mut self, window: &mut Window, cx: &mut App) -> Self {
104        self.state = Some(self.row_state(window, cx));
105        self
106    }
107
108    fn row_state(&self, window: &mut Window, cx: &mut App) -> Entity<RowState> {
109        window.use_keyed_state((self.id.clone(), "navigation-state"), cx, |_, _| {
110            RowState::default()
111        })
112    }
113}
114
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
116pub enum TabVariant {
117    #[default]
118    Primary,
119    Secondary,
120}
121
122/// A fixed Material tab row by default. Enable scrolling for long tab lists.
123#[derive(IntoElement)]
124pub struct Tabs {
125    items: NavigationItems,
126    variant: TabVariant,
127    scrollable: bool,
128}
129
130impl Tabs {
131    pub fn new(items: NavigationItems) -> Self {
132        Self {
133            items,
134            variant: TabVariant::Primary,
135            scrollable: false,
136        }
137    }
138
139    pub fn variant(mut self, variant: TabVariant) -> Self {
140        self.variant = variant;
141        self
142    }
143
144    pub fn scrollable(mut self, scrollable: bool) -> Self {
145        self.scrollable = scrollable;
146        self
147    }
148}
149
150impl RenderOnce for Tabs {
151    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
152        self.items.render_row(
153            Presentation::Tabs(self.variant, self.scrollable),
154            window,
155            cx,
156        )
157    }
158}
159
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
161pub enum NavigationBarLayout {
162    #[default]
163    Vertical,
164    Horizontal,
165}
166
167/// Material Expressive short navigation bar.
168#[derive(IntoElement)]
169pub struct NavigationBar {
170    items: NavigationItems,
171    layout: NavigationBarLayout,
172}
173
174impl NavigationBar {
175    pub fn new(items: NavigationItems) -> Self {
176        Self {
177            items,
178            layout: NavigationBarLayout::Vertical,
179        }
180    }
181
182    pub fn layout(mut self, layout: NavigationBarLayout) -> Self {
183        self.layout = layout;
184        self
185    }
186}
187
188impl RenderOnce for NavigationBar {
189    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
190        self.items
191            .render_row(Presentation::Bar(self.layout), window, cx)
192    }
193}
194
195#[derive(Clone, Copy, PartialEq, Eq)]
196pub(super) enum Presentation {
197    Tabs(TabVariant, bool),
198    Bar(NavigationBarLayout),
199    Rail(bool),
200}
201
202impl Presentation {
203    fn is_tab(self) -> bool {
204        matches!(self, Self::Tabs(..))
205    }
206
207    fn is_rail(self) -> bool {
208        matches!(self, Self::Rail(_))
209    }
210
211    fn horizontal_label(self) -> bool {
212        matches!(
213            self,
214            Self::Bar(NavigationBarLayout::Horizontal) | Self::Rail(true)
215        )
216    }
217
218    fn is_scrollable(self) -> bool {
219        !matches!(self, Self::Tabs(_, false))
220    }
221
222    fn minimum_height(self, has_icons: bool) -> f32 {
223        match self {
224            Self::Tabs(..) if has_icons => 64.,
225            Self::Tabs(..) => 48.,
226            Self::Bar(_) | Self::Rail(_) => 64.,
227        }
228    }
229}
230
231#[derive(Default)]
232struct RowState {
233    selection: Option<SharedString>,
234    focus: HashMap<SharedString, FocusHandle>,
235    horizontal_scroll: ScrollHandle,
236    vertical_scroll: ScrollHandle,
237    reveal: Option<(Presentation, Direction, SharedString, usize)>,
238}
239
240impl NavigationItems {
241    pub(super) fn render_row(
242        self,
243        presentation: Presentation,
244        window: &mut Window,
245        cx: &mut App,
246    ) -> AnyElement {
247        let theme = window_material_theme(window, cx);
248        let rtl = theme.layout.direction == Direction::Rtl;
249        let direction = theme.layout.direction;
250        let density = theme.layout.density;
251        let tone = |role| color(theme.colors.color(role));
252        let ring = tone(ColorRole::Secondary);
253        let state_layer = tone(ColorRole::OnSurface);
254        let divider = tone(ColorRole::SurfaceVariant);
255        let background = tone(if matches!(presentation, Presentation::Bar(_)) {
256            ColorRole::SurfaceContainer
257        } else {
258            ColorRole::Surface
259        });
260        let rail = presentation.is_rail();
261        let tab = presentation.is_tab();
262        let scrollable = presentation.is_scrollable();
263        let has_icons = self.items.iter().any(|item| item.icon.is_some());
264        let height = px(density.interactive_size(presentation.minimum_height(has_icons)));
265        let state = self
266            .state
267            .clone()
268            .unwrap_or_else(|| self.row_state(window, cx));
269        let (focus, scroll) = state.update(cx, |state, cx| {
270            let mut previous = std::mem::take(&mut state.focus);
271            state.focus = self
272                .items
273                .iter()
274                .map(|item| {
275                    let handle = previous
276                        .remove(&item.id)
277                        .unwrap_or_else(|| cx.focus_handle());
278                    (item.id.clone(), handle)
279                })
280                .collect();
281            let scroll = if rail {
282                &state.vertical_scroll
283            } else {
284                &state.horizontal_scroll
285            };
286            (state.focus.clone(), scroll.clone())
287        });
288        let enabled: Vec<_> = self
289            .items
290            .iter()
291            .filter(|item| !item.disabled)
292            .map(|item| (item.id.clone(), focus[&item.id].clone()))
293            .collect();
294        let focused = enabled.iter().find(|(_, handle)| handle.is_focused(window));
295        let selected = self.selected.as_ref();
296        let first = enabled.first().map(|(id, _)| id);
297        let tab_stop = focused
298            .map(|(id, _)| id)
299            .or_else(|| selected.filter(|id| enabled.iter().any(|(item, _)| item == *id)))
300            .or(first)
301            .cloned();
302        let mut items = self.items;
303        if rtl && !rail {
304            items.reverse();
305        }
306        let reveal_target = if state.read(cx).selection.as_ref() != selected {
307            selected.or_else(|| focused.map(|(id, _)| id))
308        } else {
309            focused.map(|(id, _)| id).or(selected)
310        };
311        let reveal = reveal_target.and_then(|id| {
312            items
313                .iter()
314                .position(|item| &item.id == id)
315                .map(|index| (presentation, direction, id.clone(), index))
316        });
317        state.update(cx, |state, _| {
318            if scrollable
319                && state.reveal != reveal
320                && let Some((_, _, _, index)) = &reveal
321            {
322                scroll.scroll_to_item(*index);
323            }
324            state.reveal = reveal;
325            state.selection = self.selected.clone();
326        });
327        let count = items.len();
328        let row = div()
329            .id(self.id.clone())
330            .test_support()
331            .role(if tab { Role::TabList } else { Role::ListBox })
332            .aria_label(self.label)
333            .flex()
334            .w_full()
335            .min_w_0()
336            .when_else(
337                rail,
338                |row| {
339                    row.flex_col()
340                        .gap(px(4.))
341                        .min_h_0()
342                        .flex_1()
343                        .overflow_y_scroll()
344                        .occlude()
345                },
346                |row| row.flex_row().flex_none().min_h(height).bg(background),
347            )
348            .when(tab, |row| row.border_b_1().border_color(divider))
349            .when(scrollable && !rail, |row| row.overflow_x_scroll())
350            .when(matches!(presentation, Presentation::Tabs(_, true)), |row| {
351                row.px(px(52.))
352            })
353            .when(scrollable, |row| row.track_scroll(&scroll))
354            .on_key_down(move |event, window, cx| {
355                if event.keystroke.modifiers.modified() {
356                    return;
357                }
358                let Some(current) = enabled
359                    .iter()
360                    .position(|(_, handle)| handle.is_focused(window))
361                else {
362                    return;
363                };
364                if let Some(next) =
365                    next_item(&event.keystroke.key, current, enabled.len(), rail, rtl)
366                {
367                    enabled[next].1.focus(window, cx);
368                    window.refresh();
369                    cx.stop_propagation();
370                }
371            });
372        row.children(items.into_iter().enumerate().map(|(index, item)| {
373            let selected = selected == Some(&item.id);
374            let visual = ItemVisual {
375                presentation,
376                selected,
377                height,
378                rtl,
379                font_scale: self.font_scale,
380            };
381            let handle = &focus[&item.id];
382            let is_tab_stop = tab_stop.as_ref() == Some(&item.id);
383            let id = (self.id.clone(), item.id.clone()).into();
384            let content = visual.render(&id, item.icon, item.label.clone(), window, cx);
385            let position = if rtl && !rail {
386                count - index
387            } else {
388                index + 1
389            };
390            Button::new(item.id.clone())
391                .role(if tab { Role::Tab } else { Role::ListBoxOption })
392                .aria_selected(selected)
393                .aria_position_in_set(position)
394                .aria_size_of_set(count)
395                .accessibility_label(item.label)
396                .track_focus(handle)
397                .tab_stop(is_tab_stop)
398                .disabled(item.disabled)
399                .min_h(height)
400                .min_w(px(48.))
401                .when_else(
402                    rail,
403                    |button| button.flex_none().w_full(),
404                    |button| {
405                        button.flex_1().when(
406                            matches!(presentation, Presentation::Tabs(_, true)),
407                            |button| button.flex_none().min_w(px(90.)),
408                        )
409                    },
410                )
411                .border_color(gpui::transparent_black())
412                .border_2()
413                .when(!item.disabled, |button| {
414                    button
415                        .hover(|style| style.bg(state_layer.opacity(0.08)))
416                        .active(|style| style.bg(state_layer.opacity(0.1)))
417                        .focus_visible(|style| style.border_color(ring))
418                        .when_some(self.on_select.clone(), |button, activate| {
419                            let id = item.id.clone();
420                            let on_accessibility_action = activate.clone();
421                            button
422                                .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
423                                    on_accessibility_action(&id, window, cx);
424                                })
425                                .on_click(move |_, window, cx| {
426                                    cx.stop_propagation();
427                                    activate(&item.id, window, cx);
428                                })
429                        })
430                })
431                .opacity(if item.disabled { 0.38 } else { 1. })
432                .child(content)
433        }))
434        .into_any_element()
435    }
436}
437
438fn next_item(key: &str, current: usize, len: usize, vertical: bool, rtl: bool) -> Option<usize> {
439    let forward = match key {
440        "home" => return Some(0),
441        "end" => return Some(len - 1),
442        "down" if vertical => true,
443        "up" if vertical => false,
444        "right" if !vertical => !rtl,
445        "left" if !vertical => rtl,
446        _ => return None,
447    };
448    Some((current + if forward { 1 } else { len - 1 }) % len)
449}
450
451struct ItemVisual {
452    presentation: Presentation,
453    selected: bool,
454    height: gpui::Pixels,
455    rtl: bool,
456    font_scale: f32,
457}
458
459impl ItemVisual {
460    fn render(
461        self,
462        id: &ElementId,
463        icon: Option<Icon>,
464        label: SharedString,
465        window: &mut Window,
466        cx: &mut App,
467    ) -> impl IntoElement + use<> {
468        let theme = window_material_theme(window, cx);
469        let tone = |role| color(theme.colors.color(role));
470        let foreground = if !self.selected {
471            ColorRole::OnSurfaceVariant
472        } else {
473            match self.presentation {
474                Presentation::Tabs(TabVariant::Primary, _) => ColorRole::Primary,
475                Presentation::Tabs(TabVariant::Secondary, _) => ColorRole::OnSurface,
476                _ => ColorRole::Secondary,
477            }
478        };
479        let label_color = tone(foreground);
480        let icon_color = if self.selected && !self.presentation.is_tab() {
481            ColorRole::OnSecondaryContainer
482        } else {
483            foreground
484        };
485        let secondary_container = tone(ColorRole::SecondaryContainer);
486        let indicator = tone(ColorRole::Primary);
487        let motion = theme
488            .motion
489            .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion());
490        let selection = animate(
491            (id.clone(), "indicator"),
492            f32::from(self.selected),
493            motion,
494            window,
495            cx,
496        )
497        .clamp(0., 1.);
498        let horizontal = self.presentation.horizontal_label();
499        let rail = self.presentation.is_rail();
500        let tab = self.presentation.is_tab();
501        let text_role = if tab {
502            TypeRole::TitleSmall
503        } else if rail && horizontal {
504            TypeRole::LabelLarge
505        } else {
506            TypeRole::LabelMedium
507        };
508        let label = text_style(
509            div().min_w_0().truncate().text_color(label_color),
510            text_role.style(TypographyEmphasis::Baseline),
511            self.font_scale,
512            window,
513            cx,
514        )
515        .text_align(if !horizontal {
516            TextAlign::Center
517        } else if self.rtl {
518            TextAlign::Right
519        } else {
520            TextAlign::Left
521        })
522        .child(label);
523        let icon = icon.map(|icon| {
524            div()
525                .flex_none()
526                .flex()
527                .items_center()
528                .justify_center()
529                .when(!tab && !horizontal, |icon| {
530                    icon.w(px(56.))
531                        .h(px(32.))
532                        .rounded_full()
533                        .bg(secondary_container.opacity(selection))
534                })
535                .child(icon.color(icon_color))
536        });
537        let content = div()
538            .relative()
539            .min_w_0()
540            .max_w_full()
541            .flex()
542            .items_center()
543            .when_else(
544                horizontal,
545                |content| {
546                    content
547                        .gap(px(if rail { 8. } else { 4. }))
548                        .when(self.rtl, Styled::flex_row_reverse)
549                        .px(px(16.))
550                        .min_h(px(if rail { 56. } else { 40. }))
551                        .rounded_full()
552                        .bg(secondary_container.opacity(selection))
553                        .when(rail, |content| content.w_full())
554                },
555                |content| content.flex_col().justify_center().gap(px(4.)).px(px(4.)),
556            )
557            .children(icon)
558            .child(label);
559        div()
560            .relative()
561            .flex()
562            .w_full()
563            .min_w_0()
564            .min_h(self.height - px(4.))
565            .items_center()
566            .justify_center()
567            .child(content)
568            .when(tab, |body| {
569                body.child(
570                    div()
571                        .absolute()
572                        .bottom_0()
573                        .w_full()
574                        .flex()
575                        .justify_center()
576                        .child(
577                            match self.presentation {
578                                Presentation::Tabs(TabVariant::Primary, _) => div()
579                                    .w_2_3()
580                                    .h(px(3.))
581                                    .rounded_tl(px(3.))
582                                    .rounded_tr(px(3.)),
583                                _ => div().w_full().h(px(2.)),
584                            }
585                            .bg(indicator.opacity(selection)),
586                        ),
587                )
588            })
589    }
590}