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, Hsla, InteractiveElement,
5    IntoElement, ParentElement, RenderOnce, Role, ScrollHandle, SharedString,
6    StatefulInteractiveElement, Styled, TextAlign, Window, canvas, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button, TestSupportExt};
9use gpui_material_foundation::{
10    InteractionSource, animate, color,
11    control_feedback::{activate_feedback, feedback_target, ripple_state},
12    text_style, window_material_theme,
13};
14use gpui_material_theme::{
15    ColorRole, Direction, MotionKind, MotionSpeed, TypeRole, TypographyEmphasis,
16};
17
18use super::tabs::{
19    TabDecoration, TabIndicatorTarget, TabOptions, TabReveal, TabVariant, decorative_slot,
20};
21use crate::{Badge, Icon};
22
23use super::rail::{NavigationRailArrangement, NavigationRailPadding, RailPresentation, length};
24
25/// Placement of a navigation item's icon relative to its label.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum NavigationItemIconPosition {
28    Top,
29    Start,
30}
31
32/// Optional pigments for an Expressive navigation destination.
33#[derive(Clone, Copy, Debug, Default, PartialEq)]
34pub struct NavigationItemColors {
35    pub selected_icon: Option<Hsla>,
36    pub selected_label_top: Option<Hsla>,
37    pub selected_label_start: Option<Hsla>,
38    pub selected_indicator: Option<Hsla>,
39    pub unselected_icon: Option<Hsla>,
40    pub unselected_label: Option<Hsla>,
41    pub disabled_icon: Option<Hsla>,
42    pub disabled_label: Option<Hsla>,
43}
44
45/// One destination or tab with an ID unique within its collection.
46pub struct NavigationItem {
47    id: SharedString,
48    label: SharedString,
49    icon: Option<Icon>,
50    icon_position: Option<NavigationItemIconPosition>,
51    label_content: Option<AnyElement>,
52    badge: Option<Badge>,
53    indicator_padding: Option<(NavigationRailPadding, NavigationRailPadding)>,
54    colors: NavigationItemColors,
55    interaction_source: Option<Entity<InteractionSource>>,
56    disabled: bool,
57}
58
59impl NavigationItem {
60    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
61        Self {
62            id: id.into(),
63            label: label.into(),
64            icon: None,
65            icon_position: None,
66            label_content: None,
67            badge: None,
68            indicator_padding: None,
69            colors: NavigationItemColors::default(),
70            interaction_source: None,
71            disabled: false,
72        }
73    }
74
75    pub fn icon(mut self, icon: Icon) -> Self {
76        self.icon = Some(icon);
77        self
78    }
79
80    pub fn disabled(mut self, disabled: bool) -> Self {
81        self.disabled = disabled;
82        self
83    }
84
85    /// Overrides icon placement inherited from the tab, bar, or rail.
86    pub fn icon_position(mut self, position: NavigationItemIconPosition) -> Self {
87        self.icon_position = Some(position);
88        self
89    }
90
91    /// Replaces the visible label while retaining the accessible name.
92    pub fn label_content(mut self, content: impl IntoElement) -> Self {
93        self.label_content = Some(content.into_any_element());
94        self
95    }
96
97    /// Anchors a standalone badge to the icon, or to the label if there is no icon.
98    /// An accessible badge label becomes the destination's description.
99    pub fn badge(mut self, badge: Badge) -> Self {
100        self.badge = Some(badge);
101        self
102    }
103
104    /// Sets the rail indicator's logical content padding without shrinking its target.
105    pub fn indicator_padding(
106        mut self,
107        collapsed: NavigationRailPadding,
108        expanded: NavigationRailPadding,
109    ) -> Self {
110        self.indicator_padding = Some((collapsed, expanded));
111        self
112    }
113
114    /// Sets per-state pigments for a navigation or tab destination.
115    pub fn colors(mut self, colors: NavigationItemColors) -> Self {
116        self.colors = colors;
117        self
118    }
119
120    /// Observes the destination using its collection ID and item ID.
121    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
122        self.interaction_source = Some(source.clone());
123        self
124    }
125}
126
127type Select = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
128
129/// Controlled destinations. Use the same collection ID across adaptive
130/// presentations to preserve focus on the destination that currently owns it.
131pub struct NavigationItems {
132    id: ElementId,
133    label: SharedString,
134    items: Vec<NavigationItem>,
135    selected: Option<SharedString>,
136    on_select: Option<Select>,
137    font_scale: f32,
138    state: Option<Entity<RowState>>,
139    rail_dividers: HashMap<SharedString, AnyElement>,
140    retain_roving_stop: bool,
141}
142
143impl NavigationItems {
144    pub fn new(
145        id: impl Into<ElementId>,
146        label: impl Into<SharedString>,
147        items: impl IntoIterator<Item = NavigationItem>,
148    ) -> Self {
149        Self {
150            id: id.into(),
151            label: label.into(),
152            items: items.into_iter().collect(),
153            selected: None,
154            on_select: None,
155            font_scale: 1.,
156            state: None,
157            rail_dividers: HashMap::new(),
158            retain_roving_stop: false,
159        }
160    }
161
162    pub fn selected(mut self, id: impl Into<SharedString>) -> Self {
163        self.selected = Some(id.into());
164        self
165    }
166
167    /// Reports pointer, keyboard activation and accessibility activation.
168    /// Arrow keys and Home/End move focus. The caller commits selection.
169    pub fn on_select(
170        mut self,
171        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
172    ) -> Self {
173        self.on_select = Some(Rc::new(handler));
174        self
175    }
176
177    pub fn font_scale(mut self, scale: f32) -> Self {
178        self.font_scale = if scale.is_finite() && scale > 0. {
179            scale
180        } else {
181            1.
182        };
183        self
184    }
185
186    pub(super) fn with_rail_dividers(
187        mut self,
188        dividers: HashMap<SharedString, AnyElement>,
189    ) -> Self {
190        self.rail_dividers = dividers;
191        self
192    }
193
194    // Resolve the state before the adaptive scaffold puts it under a different
195    // element path. Otherwise switching from its bar slot to its rail slot
196    // replaces the destination focus handles.
197    pub(super) fn retain(mut self, window: &mut Window, cx: &mut App) -> Self {
198        if self.state.is_none() {
199            self.state = Some(self.row_state(window, cx));
200        }
201        self
202    }
203
204    pub(super) fn id(&self) -> &ElementId {
205        &self.id
206    }
207
208    pub(super) fn retain_roving_stop(mut self) -> Self {
209        self.retain_roving_stop = true;
210        self
211    }
212
213    fn row_state(&self, window: &mut Window, cx: &mut App) -> Entity<RowState> {
214        window.use_keyed_state((self.id.clone(), "navigation-state"), cx, |_, _| {
215            RowState::default()
216        })
217    }
218}
219
220#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
221pub enum NavigationBarLayout {
222    #[default]
223    Vertical,
224    Horizontal,
225}
226
227/// Distribution of the navigation items along the width of the bar.
228#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
229pub enum NavigationBarArrangement {
230    #[default]
231    EqualWeight,
232    Centered,
233}
234
235/// Short navigation bar pigments. Item overrides take precedence over `content`.
236#[derive(Clone, Copy, Debug, Default, PartialEq)]
237pub struct NavigationBarColors {
238    pub container: Option<Hsla>,
239    pub content: Option<Hsla>,
240}
241
242/// Material Expressive short navigation bar.
243#[derive(IntoElement)]
244pub struct NavigationBar {
245    items: NavigationItems,
246    layout: NavigationBarLayout,
247    arrangement: NavigationBarArrangement,
248    colors: NavigationBarColors,
249}
250
251impl NavigationBar {
252    pub fn new(items: NavigationItems) -> Self {
253        Self {
254            items,
255            layout: NavigationBarLayout::Vertical,
256            arrangement: NavigationBarArrangement::default(),
257            colors: NavigationBarColors::default(),
258        }
259    }
260
261    pub fn layout(mut self, layout: NavigationBarLayout) -> Self {
262        self.layout = layout;
263        self
264    }
265
266    pub fn arrangement(mut self, arrangement: NavigationBarArrangement) -> Self {
267        self.arrangement = arrangement;
268        self
269    }
270
271    pub fn colors(mut self, colors: NavigationBarColors) -> Self {
272        self.colors = colors;
273        self
274    }
275}
276
277impl RenderOnce for NavigationBar {
278    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
279        self.items.render_row(
280            Presentation::Bar {
281                layout: self.layout,
282                arrangement: self.arrangement,
283                colors: self.colors,
284            },
285            window,
286            cx,
287        )
288    }
289}
290
291#[derive(Clone, Copy, PartialEq)]
292pub(super) enum Presentation {
293    Tabs(TabVariant, bool),
294    Bar {
295        layout: NavigationBarLayout,
296        arrangement: NavigationBarArrangement,
297        colors: NavigationBarColors,
298    },
299    Rail(RailPresentation),
300}
301
302impl Presentation {
303    fn is_tab(self) -> bool {
304        matches!(self, Self::Tabs(..))
305    }
306
307    fn is_rail(self) -> bool {
308        matches!(self, Self::Rail(_))
309    }
310
311    fn horizontal_label(self) -> bool {
312        matches!(
313            self,
314            Self::Bar {
315                layout: NavigationBarLayout::Horizontal,
316                ..
317            } | Self::Rail(RailPresentation { expanded: true, .. })
318        )
319    }
320
321    fn bar_colors(self) -> Option<NavigationBarColors> {
322        match self {
323            Self::Bar { colors, .. } => Some(colors),
324            _ => None,
325        }
326    }
327
328    fn rail_options(self) -> Option<RailPresentation> {
329        match self {
330            Self::Rail(options) => Some(options),
331            _ => None,
332        }
333    }
334
335    fn item_colors(self) -> Option<NavigationBarColors> {
336        match self {
337            Self::Rail(options) => Some(NavigationBarColors {
338                content: options.content,
339                container: None,
340            }),
341            _ => self.bar_colors(),
342        }
343    }
344
345    fn centered(self) -> bool {
346        matches!(
347            self,
348            Self::Bar {
349                arrangement: NavigationBarArrangement::Centered,
350                ..
351            }
352        )
353    }
354
355    fn is_scrollable(self) -> bool {
356        !matches!(self, Self::Tabs(_, false))
357    }
358
359    fn minimum_height(self, has_icons: bool) -> f32 {
360        match self {
361            Self::Tabs(..) if has_icons => 64.,
362            Self::Tabs(..) => 48.,
363            Self::Bar { .. } | Self::Rail(_) => 64.,
364        }
365    }
366}
367
368#[derive(Default)]
369struct RowState {
370    selection: Option<SharedString>,
371    focus: HashMap<SharedString, FocusHandle>,
372    horizontal_scroll: ScrollHandle,
373    vertical_scroll: ScrollHandle,
374    reveal: Option<(Presentation, Direction, SharedString, usize)>,
375    tab_reveal: TabReveal,
376    roving_stop: Option<SharedString>,
377}
378
379impl NavigationItems {
380    pub(super) fn render_row(
381        self,
382        presentation: Presentation,
383        window: &mut Window,
384        cx: &mut App,
385    ) -> AnyElement {
386        self.render_row_with_tabs(presentation, None, window, cx)
387    }
388
389    pub(super) fn render_row_with_tabs(
390        self,
391        presentation: Presentation,
392        mut tabs: Option<TabOptions>,
393        window: &mut Window,
394        cx: &mut App,
395    ) -> AnyElement {
396        let theme = window_material_theme(window, cx);
397        let rtl = theme.layout.direction == Direction::Rtl;
398        let direction = theme.layout.direction;
399        let density = theme.layout.density;
400        let tone = |role| color(theme.colors.color(role));
401        let ring = tone(ColorRole::Secondary);
402        let indicator_color = tone(ColorRole::Primary);
403        let state_layer = tone(ColorRole::OnSurface);
404        let tab_colors = tabs.as_ref().map(|tabs| tabs.colors).unwrap_or_default();
405        let divider = tab_colors
406            .divider
407            .unwrap_or_else(|| tone(ColorRole::SurfaceVariant));
408        let bar_colors = presentation.bar_colors();
409        let background = bar_colors
410            .and_then(|colors| colors.container)
411            .or(tab_colors.container)
412            .unwrap_or_else(|| {
413                tone(if bar_colors.is_some() {
414                    ColorRole::SurfaceContainer
415                } else {
416                    ColorRole::Surface
417                })
418            });
419        let options = presentation.rail_options();
420        let item_colors = presentation.item_colors();
421        let rail = presentation.is_rail();
422        let tab = presentation.is_tab();
423        let scrollable = presentation.is_scrollable();
424        let has_icons = self.items.iter().any(|item| {
425            item.icon.is_some()
426                && (!tab || item.icon_position != Some(NavigationItemIconPosition::Start))
427        });
428        let height = px(density.interactive_size(presentation.minimum_height(has_icons)));
429        let state = self
430            .state
431            .clone()
432            .unwrap_or_else(|| self.row_state(window, cx));
433        let mut rail_dividers = self.rail_dividers;
434        let (focus, scroll) = state.update(cx, |state, cx| {
435            let mut previous = std::mem::take(&mut state.focus);
436            state.focus = self
437                .items
438                .iter()
439                .map(|item| {
440                    let handle = previous
441                        .remove(&item.id)
442                        .unwrap_or_else(|| cx.focus_handle());
443                    (item.id.clone(), handle)
444                })
445                .collect();
446            let scroll = if rail {
447                &state.vertical_scroll
448            } else {
449                &state.horizontal_scroll
450            };
451            (state.focus.clone(), scroll.clone())
452        });
453        let scroll = tabs
454            .as_ref()
455            .filter(|_| scrollable)
456            .and_then(|tabs| tabs.scroll.clone())
457            .unwrap_or(scroll);
458        let enabled: Vec<_> = self
459            .items
460            .iter()
461            .filter(|item| !item.disabled)
462            .map(|item| (item.id.clone(), focus[&item.id].clone()))
463            .collect();
464        let focused = enabled.iter().find(|(_, handle)| handle.is_focused(window));
465        let selected = self.selected.as_ref();
466        let first = enabled.first().map(|(id, _)| id);
467        let remembered = self
468            .retain_roving_stop
469            .then(|| {
470                state.update(cx, |state, _| {
471                    if let Some((id, _)) = focused {
472                        state.roving_stop = Some(id.clone());
473                    } else if state.selection.as_ref() != selected {
474                        state.roving_stop = None;
475                    }
476                    state.roving_stop.clone()
477                })
478            })
479            .flatten();
480        let enabled_id = |id: &&SharedString| enabled.iter().any(|(item, _)| item == *id);
481        let tab_stop = focused
482            .map(|(id, _)| id)
483            .or_else(|| remembered.as_ref().filter(enabled_id))
484            .or_else(|| selected.filter(enabled_id))
485            .or(first)
486            .cloned();
487        let mut items = self.items;
488        if rtl && !rail {
489            items.reverse();
490        }
491        let focused_id = focused.map(|(id, _)| id);
492        let reveal_index = if tab && scrollable {
493            state.update(cx, |state, _| {
494                state.tab_reveal.choose(
495                    selected,
496                    focused_id,
497                    items.iter().map(|item| item.id.clone()).collect(),
498                    &scroll,
499                )
500            })
501        } else {
502            state.update(cx, |state, _| {
503                let reveal_target = if state.selection.as_ref() != selected {
504                    selected.or(focused_id)
505                } else {
506                    focused_id.or(selected)
507                };
508                let reveal = reveal_target.and_then(|id| {
509                    items
510                        .iter()
511                        .position(|item| &item.id == id)
512                        .map(|index| (presentation, direction, id.clone(), index))
513                });
514                if scrollable
515                    && state.reveal != reveal
516                    && let Some((_, _, _, index)) = &reveal
517                {
518                    scroll.scroll_to_item(*index);
519                }
520                state.reveal = reveal;
521                state.selection = self.selected.clone();
522                state.tab_reveal = TabReveal::default();
523            });
524            None
525        };
526        let custom_indicator = tabs
527            .as_ref()
528            .is_some_and(|tabs| tabs.indicator_style.is_some() || tabs.indicator_content.is_some());
529        let custom_divider = tabs.as_mut().and_then(|tabs| tabs.divider.take());
530        let decoration = tabs.as_mut().and_then(|tabs| {
531            let Presentation::Tabs(variant, _) = presentation else {
532                return None;
533            };
534            let (index, item) = items
535                .iter()
536                .enumerate()
537                .find(|(_, item)| selected == Some(&item.id))?;
538            if !custom_indicator {
539                return None;
540            }
541            let style = tabs.indicator_style.unwrap_or_default();
542            let tint = item
543                .colors
544                .selected_indicator
545                .or(style.color)
546                .unwrap_or(indicator_color);
547            Some((
548                index,
549                TabDecoration {
550                    row: self.id.clone(),
551                    selected: item.id.clone(),
552                    variant,
553                    direction,
554                    target: Rc::new(TabIndicatorTarget::default()),
555                    scroll: scrollable.then(|| scroll.clone()),
556                    style,
557                    content: tabs.indicator_content.take(),
558                    color: tint.opacity(if item.disabled { 0.38 } else { 1. }),
559                    has_default_divider: custom_divider.is_none(),
560                },
561            ))
562        });
563        let indicator_target = decoration
564            .as_ref()
565            .map(|(index, decoration)| (*index, decoration.target.clone()));
566        let width = window.viewport_size().width;
567        let edge_padding = tabs
568            .as_ref()
569            .map_or(px(52.), |tabs| tabs.edge_padding.min(width / 2.));
570        let min_tab_width = tabs
571            .as_ref()
572            .map_or(px(90.), |tabs| tabs.min_tab_width.min(width.max(px(90.))));
573        let count = items.len();
574        let centered_widths = (presentation.centered() && count > 0).then(|| {
575            // Compose reserves side space for short labels, while capping wider
576            // destinations to their share of an equal-weight bar.
577            let share = 1. / count as f32;
578            let group = ((count.min(7) + 3) as f32 * 0.1).min(1.);
579            (gpui::relative(share * group), gpui::relative(share))
580        });
581        let row = div()
582            .when(tab && (scrollable || indicator_target.is_some()), |row| {
583                let scroll = scroll.clone();
584                let indicator_target = indicator_target.clone();
585                row.on_children_prepainted(move |bounds, window, cx| {
586                    if let Some((index, target)) = &indicator_target {
587                        target.tab_bounds.set(if scrollable {
588                            scroll.bounds_for_item(*index)
589                        } else {
590                            bounds.get(*index).copied()
591                        });
592                    }
593                    if let Some(index) = reveal_index {
594                        state.update(cx, |state, _| {
595                            state.tab_reveal.observe_geometry(index, &scroll, window)
596                        });
597                    }
598                })
599            })
600            .id(self.id.clone())
601            .test_support()
602            .role(if tab { Role::TabList } else { Role::ListBox })
603            .aria_label(self.label)
604            .flex()
605            .w_full()
606            .min_w_0()
607            .when_else(
608                rail,
609                |row| {
610                    row.flex_col()
611                        .gap(options.map_or(px(4.), |options| options.spacing))
612                        .min_h_0()
613                        .flex_1()
614                        .overflow_y_scroll()
615                        .occlude()
616                },
617                |row| {
618                    row.flex_row()
619                        .flex_none()
620                        .min_h(height)
621                        .when(custom_divider.is_none(), |row| row.bg(background))
622                },
623            )
624            .when(tab && custom_divider.is_none(), |row| {
625                row.border_b_1().border_color(divider)
626            })
627            .when_some(options, |row, options| match options.arrangement {
628                NavigationRailArrangement::SpaceBetween => row.justify_between(),
629                NavigationRailArrangement::SpaceAround => row.justify_around(),
630                NavigationRailArrangement::SpaceEvenly => row.justify_evenly(),
631                _ => row,
632            })
633            .when(centered_widths.is_some(), Styled::justify_center)
634            .when(scrollable && !rail, |row| row.overflow_x_scroll())
635            .when(matches!(presentation, Presentation::Tabs(_, true)), |row| {
636                row.px(edge_padding)
637            })
638            .when(scrollable, |row| row.track_scroll(&scroll))
639            .on_key_down(move |event, window, cx| {
640                if event.keystroke.modifiers.modified() {
641                    return;
642                }
643                let Some(current) = enabled
644                    .iter()
645                    .position(|(_, handle)| handle.is_focused(window))
646                else {
647                    return;
648                };
649                if let Some(next) =
650                    next_item(&event.keystroke.key, current, enabled.len(), rail, rtl)
651                {
652                    enabled[next].1.focus(window, cx);
653                    window.refresh();
654                    cx.stop_propagation();
655                }
656            });
657        let row = row.children(items.into_iter().enumerate().map(|(index, mut item)| {
658            let selected = selected == Some(&item.id);
659            let styled_item = bar_colors.is_some()
660                || tab
661                    && (tab_colors.content.is_some()
662                        || item.colors != NavigationItemColors::default())
663                || rail
664                    && (options.is_some_and(|options| options.content.is_some())
665                        || item.colors != NavigationItemColors::default());
666            let visual = ItemVisual {
667                presentation,
668                selected,
669                height,
670                rtl,
671                font_scale: self.font_scale,
672                tab_content: tab_colors.content,
673                styled_item,
674                custom_indicator,
675                indicator_target: indicator_target
676                    .as_ref()
677                    .and_then(|(selected_index, target)| {
678                        (*selected_index == index).then(|| target.clone())
679                    }),
680            };
681            let handle = &focus[&item.id];
682            let is_tab_stop = tab_stop.as_ref() == Some(&item.id);
683            let id = (self.id.clone(), item.id.clone()).into();
684            let customize_item = tab || item_colors.is_some();
685            let description = item
686                .badge
687                .as_mut()
688                .filter(|_| customize_item)
689                .and_then(Badge::take_accessible_label);
690            let content = visual.render(&id, &mut item, window, cx);
691            let feedback = item
692                .interaction_source
693                .as_ref()
694                .filter(|_| customize_item)
695                .map(|source| {
696                    let feedback = ripple_state(&id, !item.disabled, window, cx);
697                    let tracker = InteractionSource::track(source, &id, window, cx);
698                    feedback
699                        .borrow_mut()
700                        .track(!item.disabled, handle, Some(tracker), window, cx);
701                    feedback
702                });
703            let position = if rtl && !rail {
704                count - index
705            } else {
706                index + 1
707            };
708            let divider = rail_dividers.remove(&item.id);
709            let slot_id = (id, "rail-destination");
710            let button = Button::new(item.id.clone())
711                .role(if tab { Role::Tab } else { Role::ListBoxOption })
712                .aria_selected(selected)
713                .aria_position_in_set(position)
714                .aria_size_of_set(count)
715                .accessibility_label(item.label)
716                .when_some(description, |button, description| {
717                    button.aria_description(description)
718                })
719                .track_focus(handle)
720                .tab_stop(is_tab_stop)
721                .disabled(item.disabled)
722                .min_h(height)
723                .min_w(px(48.))
724                .when_else(
725                    rail,
726                    |button| button.flex_none().w_full(),
727                    |button| {
728                        button.flex_1().when(
729                            matches!(presentation, Presentation::Tabs(_, true)),
730                            |button| button.flex_none().min_w(min_tab_width),
731                        )
732                    },
733                )
734                .when_some(centered_widths, |button, (minimum, maximum)| {
735                    button.flex_none().min_w(minimum).max_w(maximum)
736                })
737                .border_color(gpui::transparent_black())
738                .border_2()
739                .when(!item.disabled, |button| {
740                    button
741                        .hover(|style| style.bg(state_layer.opacity(0.08)))
742                        .active(|style| style.bg(state_layer.opacity(0.1)))
743                        .focus_visible(|style| style.border_color(ring))
744                        .when_some(feedback.as_ref().cloned(), |button, feedback| {
745                            feedback_target(button, feedback, true, Some(handle.clone()))
746                        })
747                        .when_some(self.on_select.clone(), |button, activate| {
748                            let id = item.id.clone();
749                            let on_accessibility_action = activate.clone();
750                            button
751                                .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
752                                    on_accessibility_action(&id, window, cx);
753                                })
754                                .on_click(move |event, window, cx| {
755                                    cx.stop_propagation();
756                                    if let Some(feedback) = &feedback {
757                                        activate_feedback(event, feedback, window, cx);
758                                    }
759                                    activate(&item.id, window, cx);
760                                })
761                        })
762                })
763                .opacity(if item.disabled && !styled_item {
764                    0.38
765                } else {
766                    1.
767                })
768                .child(content);
769            if let Some(options) = options {
770                div()
771                    .id(slot_id)
772                    .flex_none()
773                    .when(
774                        index == 0
775                            && matches!(
776                                options.arrangement,
777                                NavigationRailArrangement::Center | NavigationRailArrangement::End
778                            ),
779                        |slot| slot.mt_auto(),
780                    )
781                    .when(
782                        index + 1 == count
783                            && options.arrangement == NavigationRailArrangement::Center,
784                        |slot| slot.mb_auto(),
785                    )
786                    .child(button)
787                    .children(divider.map(|divider| div().id("rail-divider").child(divider)))
788                    .into_any_element()
789            } else {
790                button.into_any_element()
791            }
792        }));
793        if custom_divider.is_some() || decoration.is_some() {
794            div()
795                .relative()
796                .w_full()
797                .min_w_0()
798                .when(custom_divider.is_some(), |host| host.bg(background))
799                .children(custom_divider.map(|divider| {
800                    decorative_slot((self.id.clone(), "custom-divider").into(), divider)
801                        .absolute()
802                        .left_0()
803                        .right_0()
804                        .bottom_0()
805                }))
806                .child(row)
807                .children(decoration.map(|(_, decoration)| decoration.element()))
808                .into_any_element()
809        } else {
810            row.into_any_element()
811        }
812    }
813}
814
815fn next_item(key: &str, current: usize, len: usize, vertical: bool, rtl: bool) -> Option<usize> {
816    let forward = match key {
817        "home" => return Some(0),
818        "end" => return Some(len - 1),
819        "down" if vertical => true,
820        "up" if vertical => false,
821        "right" if !vertical => !rtl,
822        "left" if !vertical => rtl,
823        _ => return None,
824    };
825    Some((current + if forward { 1 } else { len - 1 }) % len)
826}
827
828struct ItemVisual {
829    presentation: Presentation,
830    selected: bool,
831    height: gpui::Pixels,
832    rtl: bool,
833    font_scale: f32,
834    tab_content: Option<Hsla>,
835    styled_item: bool,
836    custom_indicator: bool,
837    indicator_target: Option<Rc<TabIndicatorTarget>>,
838}
839
840impl ItemVisual {
841    fn render(
842        self,
843        id: &ElementId,
844        item: &mut NavigationItem,
845        window: &mut Window,
846        cx: &mut App,
847    ) -> impl IntoElement + use<> {
848        let theme = window_material_theme(window, cx);
849        let tone = |role| color(theme.colors.color(role));
850        let foreground = if !self.selected {
851            ColorRole::OnSurfaceVariant
852        } else {
853            match self.presentation {
854                Presentation::Tabs(TabVariant::Primary, _) => ColorRole::Primary,
855                Presentation::Tabs(TabVariant::Secondary, _) => ColorRole::OnSurface,
856                _ => ColorRole::Secondary,
857            }
858        };
859        let icon_role = if self.selected && !self.presentation.is_tab() {
860            ColorRole::OnSecondaryContainer
861        } else {
862            foreground
863        };
864        let bar = self.presentation.item_colors();
865        let tab = self.presentation.is_tab();
866        let customize_item = bar.is_some() || tab;
867        let fallback = bar.and_then(|colors| colors.content).or(self.tab_content);
868        let rail_padding = self.presentation.rail_options().and_then(|options| {
869            item.indicator_padding.map(|(collapsed, expanded)| {
870                if options.expanded {
871                    expanded
872                } else {
873                    collapsed
874                }
875            })
876        });
877        let indicator_padding = rail_padding.map(|padding| {
878            let (left, right) = theme
879                .layout
880                .horizontal(length(padding.start), length(padding.end));
881            (left, right, length(padding.top), length(padding.bottom))
882        });
883        let horizontal = item.icon_position.filter(|_| customize_item).map_or_else(
884            || self.presentation.horizontal_label(),
885            |position| position == NavigationItemIconPosition::Start,
886        );
887        let (icon_color, label_color, selected_indicator) = if self.styled_item {
888            let colors = item.colors;
889            let resolve = |selected: Option<Hsla>,
890                           unselected: Option<Hsla>,
891                           disabled: Option<Hsla>,
892                           active_role| {
893                let unselected = unselected
894                    .or(fallback)
895                    .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant));
896                if item.disabled {
897                    disabled.unwrap_or_else(|| unselected.opacity(0.38))
898                } else if self.selected {
899                    selected.or(fallback).unwrap_or_else(|| tone(active_role))
900                } else {
901                    unselected
902                }
903            };
904            let icon = resolve(
905                colors.selected_icon,
906                colors.unselected_icon,
907                colors.disabled_icon,
908                icon_role,
909            );
910            let label = resolve(
911                if horizontal {
912                    colors.selected_label_start
913                } else {
914                    colors.selected_label_top
915                },
916                colors.unselected_label,
917                colors.disabled_label,
918                foreground,
919            );
920            let selected_indicator = colors
921                .selected_indicator
922                .unwrap_or_else(|| tone(ColorRole::SecondaryContainer));
923            (
924                icon,
925                label,
926                selected_indicator.opacity(if item.disabled { 0.38 } else { 1. }),
927            )
928        } else {
929            (
930                tone(icon_role),
931                tone(foreground),
932                tone(ColorRole::SecondaryContainer),
933            )
934        };
935        let indicator = item
936            .colors
937            .selected_indicator
938            .unwrap_or_else(|| tone(ColorRole::Primary))
939            .opacity(if item.disabled && self.styled_item {
940                0.38
941            } else {
942                1.
943            });
944        let motion = theme
945            .motion
946            .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion());
947        let selection = if self.custom_indicator {
948            0.
949        } else {
950            animate(
951                (id.clone(), "indicator"),
952                f32::from(self.selected),
953                motion,
954                window,
955                cx,
956            )
957            .clamp(0., 1.)
958        };
959        let rail = self.presentation.is_rail();
960        let text_role = if tab {
961            TypeRole::TitleSmall
962        } else if rail && horizontal {
963            TypeRole::LabelLarge
964        } else {
965            TypeRole::LabelMedium
966        };
967        let mut label = text_style(
968            div().min_w_0().truncate().text_color(label_color),
969            text_role.style(TypographyEmphasis::Baseline),
970            self.font_scale,
971            window,
972            cx,
973        )
974        .text_align(if !horizontal {
975            TextAlign::Center
976        } else if self.rtl {
977            TextAlign::Right
978        } else {
979            TextAlign::Left
980        });
981        label = if let Some(content) = item.label_content.take().filter(|_| customize_item) {
982            if tab {
983                label.child(decorative_slot(
984                    (id.clone(), "visual-label").into(),
985                    content,
986                ))
987            } else {
988                label.child(
989                    div()
990                        .id((id.clone(), "visual-label"))
991                        .role(Role::Group)
992                        .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
993                        .child(content),
994                )
995            }
996        } else {
997            label.child(item.label.clone())
998        };
999        let mut badge = item.badge.take().filter(|_| customize_item);
1000        let icon = item.icon.take().map(|icon| {
1001            let icon = if self.styled_item {
1002                icon.inherit_color()
1003            } else {
1004                icon.color(icon_role)
1005            };
1006            let icon = if let Some(badge) = badge.take() {
1007                badge.attach_to(icon).into_any_element()
1008            } else {
1009                icon.into_any_element()
1010            };
1011            div()
1012                .flex_none()
1013                .flex()
1014                .items_center()
1015                .justify_center()
1016                .text_color(icon_color)
1017                .when(!tab && !horizontal, |icon| {
1018                    icon.w(px(56.))
1019                        .h(px(32.))
1020                        .rounded_full()
1021                        .bg(selected_indicator.opacity(selection))
1022                })
1023                .when_some(
1024                    indicator_padding.filter(|_| !horizontal),
1025                    |icon, (left, right, top, bottom)| {
1026                        icon.w(px(24.) + left + right)
1027                            .h(px(24.) + top + bottom)
1028                            .pl(left)
1029                            .pr(right)
1030                            .pt(top)
1031                            .pb(bottom)
1032                    },
1033                )
1034                .child(icon)
1035        });
1036        let label = if let Some(badge) = badge {
1037            div()
1038                .min_w_0()
1039                .max_w_full()
1040                .child(badge.attach_to(label))
1041                .into_any_element()
1042        } else {
1043            label.into_any_element()
1044        };
1045        let padding = px(if horizontal { 16. } else { 4. });
1046        let content = div()
1047            .relative()
1048            .min_w_0()
1049            .max_w_full()
1050            .flex()
1051            .items_center()
1052            .when_else(
1053                horizontal,
1054                |content| {
1055                    content
1056                        .gap(px(if rail || tab { 8. } else { 4. }))
1057                        .when(self.rtl, Styled::flex_row_reverse)
1058                        .when(!tab, |content| {
1059                            content
1060                                .min_h(px(if rail { 56. } else { 40. }))
1061                                .rounded_full()
1062                                .bg(selected_indicator.opacity(selection))
1063                        })
1064                        .when(rail, |content| content.w_full())
1065                },
1066                |content| content.flex_col().justify_center().gap(px(4.)),
1067            )
1068            .px(padding)
1069            .when_some(
1070                indicator_padding.filter(|_| horizontal),
1071                |content, (left, right, top, bottom)| content.pl(left).pr(right).pt(top).pb(bottom),
1072            )
1073            .children(icon)
1074            .child(label)
1075            .children(self.indicator_target.map(|target| {
1076                canvas(
1077                    move |bounds, _, _| {
1078                        target
1079                            .content_width
1080                            .set((bounds.size.width - padding * 2.).max(px(0.)))
1081                    },
1082                    |_, _, _, _| {},
1083                )
1084                .absolute()
1085                .inset_0()
1086            }));
1087        div()
1088            .relative()
1089            .flex()
1090            .w_full()
1091            .min_w_0()
1092            .min_h(self.height - px(4.))
1093            .items_center()
1094            .justify_center()
1095            .child(content)
1096            .when(tab && !self.custom_indicator, |body| {
1097                body.child(
1098                    div()
1099                        .absolute()
1100                        .bottom_0()
1101                        .w_full()
1102                        .flex()
1103                        .justify_center()
1104                        .child(
1105                            match self.presentation {
1106                                Presentation::Tabs(TabVariant::Primary, _) => div()
1107                                    .w_2_3()
1108                                    .h(px(3.))
1109                                    .rounded_tl(px(3.))
1110                                    .rounded_tr(px(3.)),
1111                                _ => div().w_full().h(px(2.)),
1112                            }
1113                            .bg(indicator.opacity(selection)),
1114                        ),
1115                )
1116            })
1117    }
1118}