Skip to main content

gpui_material_components/navigation/
items.rs

1use std::{collections::HashMap, rc::Rc};
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, Hsla, IntoElement, RenderOnce, SharedString, Window,
5};
6use gpui_material_foundation::InteractionSource;
7
8use super::rail::{NavigationRailPadding, RailPresentation};
9use super::tabs::TabVariant;
10use crate::{Badge, Icon};
11
12mod render;
13
14use render::RowState;
15
16/// Placement of a navigation item's icon relative to its label.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum NavigationItemIconPosition {
19    /// Place the icon above the label.
20    Top,
21    /// Place the icon at the logical start of the label.
22    Start,
23}
24
25/// Optional pigments for an Expressive navigation destination.
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub struct NavigationItemColors {
28    /// Icon color when the destination is selected.
29    pub selected_icon: Option<Hsla>,
30    /// Label color when selected and the icon is positioned above the label.
31    pub selected_label_top: Option<Hsla>,
32    /// Label color when selected and the icon is positioned at the logical start.
33    pub selected_label_start: Option<Hsla>,
34    /// Fill color for the selected destination pill indicator.
35    pub selected_indicator: Option<Hsla>,
36    /// Icon color when the destination is unselected.
37    pub unselected_icon: Option<Hsla>,
38    /// Label color when the destination is unselected.
39    pub unselected_label: Option<Hsla>,
40    /// Icon color when the destination is disabled.
41    pub disabled_icon: Option<Hsla>,
42    /// Label color when the destination is disabled.
43    pub disabled_label: Option<Hsla>,
44}
45
46/// One destination or tab with an ID unique within its collection.
47pub struct NavigationItem {
48    pub(super) id: SharedString,
49    pub(super) label: SharedString,
50    pub(super) icon: Option<Icon>,
51    pub(super) icon_position: Option<NavigationItemIconPosition>,
52    pub(super) label_content: Option<AnyElement>,
53    pub(super) badge: Option<Badge>,
54    pub(super) indicator_padding: Option<(NavigationRailPadding, NavigationRailPadding)>,
55    pub(super) colors: NavigationItemColors,
56    pub(super) interaction_source: Option<Entity<InteractionSource>>,
57    pub(super) disabled: bool,
58}
59
60impl NavigationItem {
61    /// Creates a navigation destination or tab with a unique ID and visible label.
62    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
63        Self {
64            id: id.into(),
65            label: label.into(),
66            icon: None,
67            icon_position: None,
68            label_content: None,
69            badge: None,
70            indicator_padding: None,
71            colors: NavigationItemColors::default(),
72            interaction_source: None,
73            disabled: false,
74        }
75    }
76
77    /// Sets the destination's icon.
78    pub fn icon(mut self, icon: Icon) -> Self {
79        self.icon = Some(icon);
80        self
81    }
82
83    /// Disables pointer and keyboard activation for this destination.
84    pub fn disabled(mut self, disabled: bool) -> Self {
85        self.disabled = disabled;
86        self
87    }
88
89    /// Overrides icon placement inherited from the tab, bar, or rail.
90    pub fn icon_position(mut self, position: NavigationItemIconPosition) -> Self {
91        self.icon_position = Some(position);
92        self
93    }
94
95    /// Replaces the visible label while retaining the accessible name.
96    pub fn label_content(mut self, content: impl IntoElement) -> Self {
97        self.label_content = Some(content.into_any_element());
98        self
99    }
100
101    /// Anchors a standalone badge to the icon, or to the label if there is no icon.
102    /// An accessible badge label becomes the destination's description.
103    pub fn badge(mut self, badge: Badge) -> Self {
104        self.badge = Some(badge);
105        self
106    }
107
108    /// Sets the rail indicator's logical content padding without shrinking its target.
109    pub fn indicator_padding(
110        mut self,
111        collapsed: NavigationRailPadding,
112        expanded: NavigationRailPadding,
113    ) -> Self {
114        self.indicator_padding = Some((collapsed, expanded));
115        self
116    }
117
118    /// Sets per-state pigments for a navigation or tab destination.
119    pub fn colors(mut self, colors: NavigationItemColors) -> Self {
120        self.colors = colors;
121        self
122    }
123
124    /// Observes the destination using its collection ID and item ID.
125    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
126        self.interaction_source = Some(source.clone());
127        self
128    }
129}
130
131pub(super) type Select = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
132
133/// Controlled destinations. Use the same collection ID across adaptive
134/// presentations to preserve focus on the destination that currently owns it.
135pub struct NavigationItems {
136    id: ElementId,
137    label: SharedString,
138    items: Vec<NavigationItem>,
139    selected: Option<SharedString>,
140    on_select: Option<Select>,
141    font_scale: f32,
142    state: Option<Entity<RowState>>,
143    rail_dividers: HashMap<SharedString, AnyElement>,
144    retain_roving_stop: bool,
145}
146
147impl NavigationItems {
148    /// Creates a controlled navigation collection with an element ID, accessible landmark label, and items.
149    pub fn new(
150        id: impl Into<ElementId>,
151        label: impl Into<SharedString>,
152        items: impl IntoIterator<Item = NavigationItem>,
153    ) -> Self {
154        Self {
155            id: id.into(),
156            label: label.into(),
157            items: items.into_iter().collect(),
158            selected: None,
159            on_select: None,
160            font_scale: 1.,
161            state: None,
162            rail_dividers: HashMap::new(),
163            retain_roving_stop: false,
164        }
165    }
166
167    /// Sets the ID of the currently selected destination.
168    pub fn selected(mut self, id: impl Into<SharedString>) -> Self {
169        self.selected = Some(id.into());
170        self
171    }
172
173    /// Reports pointer, keyboard activation and accessibility activation.
174    /// Arrow keys and Home/End move focus. The caller commits selection.
175    pub fn on_select(
176        mut self,
177        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
178    ) -> Self {
179        self.on_select = Some(Rc::new(handler));
180        self
181    }
182
183    /// Multiplies item label typography scale by a positive finite factor (default `1.0`).
184    pub fn font_scale(mut self, scale: f32) -> Self {
185        self.font_scale = if scale.is_finite() && scale > 0. {
186            scale
187        } else {
188            1.
189        };
190        self
191    }
192
193    pub(super) fn with_rail_dividers(
194        mut self,
195        dividers: HashMap<SharedString, AnyElement>,
196    ) -> Self {
197        self.rail_dividers = dividers;
198        self
199    }
200
201    // Resolve the state before the adaptive scaffold puts it under a different
202    // element path. Otherwise switching from its bar slot to its rail slot
203    // replaces the destination focus handles.
204    pub(super) fn retain(mut self, window: &mut Window, cx: &mut App) -> Self {
205        if self.state.is_none() {
206            self.state = Some(self.row_state(window, cx));
207        }
208        self
209    }
210
211    pub(super) fn id(&self) -> &ElementId {
212        &self.id
213    }
214
215    #[allow(clippy::type_complexity)]
216    pub(super) fn into_drawer_parts(
217        self,
218    ) -> (
219        ElementId,
220        SharedString,
221        Vec<NavigationItem>,
222        Option<SharedString>,
223        Option<Select>,
224        f32,
225    ) {
226        (
227            self.id,
228            self.label,
229            self.items,
230            self.selected,
231            self.on_select,
232            self.font_scale,
233        )
234    }
235
236    pub(super) fn retain_roving_stop(mut self) -> Self {
237        self.retain_roving_stop = true;
238        self
239    }
240
241    fn row_state(&self, window: &mut Window, cx: &mut App) -> Entity<RowState> {
242        window.use_keyed_state((self.id.clone(), "navigation-state"), cx, |_, _| {
243            RowState::default()
244        })
245    }
246}
247
248/// Icon-and-label orientation for items inside a [`NavigationBar`].
249#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
250pub enum NavigationBarLayout {
251    /// Stack the icon above the label.
252    #[default]
253    Vertical,
254    /// Place the icon beside the label at the logical start.
255    Horizontal,
256}
257
258/// Distribution of the navigation items along the width of the bar.
259#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
260pub enum NavigationBarArrangement {
261    /// Distribute items evenly across the full width of the bar.
262    #[default]
263    EqualWeight,
264    /// Group items together centered along the bar.
265    Centered,
266}
267
268/// Short navigation bar pigments. Item overrides take precedence over `content`.
269#[derive(Clone, Copy, Debug, Default, PartialEq)]
270pub struct NavigationBarColors {
271    /// Background color override for the navigation bar container.
272    pub container: Option<Hsla>,
273    /// Default foreground color override for bar item content.
274    pub content: Option<Hsla>,
275}
276
277/// Material Expressive short navigation bar.
278#[derive(IntoElement)]
279pub struct NavigationBar {
280    items: NavigationItems,
281    layout: NavigationBarLayout,
282    arrangement: NavigationBarArrangement,
283    colors: NavigationBarColors,
284}
285
286impl NavigationBar {
287    /// Creates a short navigation bar displaying the given [`NavigationItems`].
288    pub fn new(items: NavigationItems) -> Self {
289        Self {
290            items,
291            layout: NavigationBarLayout::Vertical,
292            arrangement: NavigationBarArrangement::default(),
293            colors: NavigationBarColors::default(),
294        }
295    }
296
297    /// Sets the item icon-and-label layout (default [`NavigationBarLayout::Vertical`]).
298    pub fn layout(mut self, layout: NavigationBarLayout) -> Self {
299        self.layout = layout;
300        self
301    }
302
303    /// Sets how items are distributed across the bar width (default [`NavigationBarArrangement::EqualWeight`]).
304    pub fn arrangement(mut self, arrangement: NavigationBarArrangement) -> Self {
305        self.arrangement = arrangement;
306        self
307    }
308
309    /// Overrides container and default content colors for the bar.
310    pub fn colors(mut self, colors: NavigationBarColors) -> Self {
311        self.colors = colors;
312        self
313    }
314}
315
316impl RenderOnce for NavigationBar {
317    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
318        self.items.render_row(
319            Presentation::Bar {
320                layout: self.layout,
321                arrangement: self.arrangement,
322                colors: self.colors,
323            },
324            window,
325            cx,
326        )
327    }
328}
329
330#[derive(Clone, Copy, PartialEq)]
331pub(super) enum Presentation {
332    Tabs(TabVariant, bool),
333    Bar {
334        layout: NavigationBarLayout,
335        arrangement: NavigationBarArrangement,
336        colors: NavigationBarColors,
337    },
338    Rail(RailPresentation),
339}
340
341impl Presentation {
342    fn is_tab(self) -> bool {
343        matches!(self, Self::Tabs(..))
344    }
345
346    fn is_rail(self) -> bool {
347        matches!(self, Self::Rail(_))
348    }
349
350    fn horizontal_label(self) -> bool {
351        matches!(
352            self,
353            Self::Bar {
354                layout: NavigationBarLayout::Horizontal,
355                ..
356            } | Self::Rail(RailPresentation { expanded: true, .. })
357        )
358    }
359
360    fn bar_colors(self) -> Option<NavigationBarColors> {
361        match self {
362            Self::Bar { colors, .. } => Some(colors),
363            _ => None,
364        }
365    }
366
367    fn rail_options(self) -> Option<RailPresentation> {
368        match self {
369            Self::Rail(options) => Some(options),
370            _ => None,
371        }
372    }
373
374    fn item_colors(self) -> Option<NavigationBarColors> {
375        match self {
376            Self::Rail(options) => Some(NavigationBarColors {
377                content: options.content,
378                container: None,
379            }),
380            _ => self.bar_colors(),
381        }
382    }
383
384    fn centered(self) -> bool {
385        matches!(
386            self,
387            Self::Bar {
388                arrangement: NavigationBarArrangement::Centered,
389                ..
390            }
391        )
392    }
393
394    fn is_scrollable(self) -> bool {
395        !matches!(self, Self::Tabs(_, false))
396    }
397
398    fn minimum_height(self, has_icons: bool) -> f32 {
399        match self {
400            Self::Tabs(..) if has_icons => 64.,
401            Self::Tabs(..) => 48.,
402            Self::Bar { .. } | Self::Rail(_) => 64.,
403        }
404    }
405}