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;
7use gpui_material_theme::LogicalEdges;
8
9use super::rail::RailPresentation;
10use super::tabs::TabVariant;
11use crate::{Badge, Icon};
12
13mod palette;
14mod row;
15mod state;
16mod visual;
17
18pub(in crate::navigation) use state::{RowState, row_state_for};
19
20/// Placement of a navigation item's icon relative to its label.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum NavigationItemIconPosition {
23    /// Place the icon above the label.
24    Top,
25    /// Place the icon at the logical start of the label.
26    Start,
27}
28
29/// Optional pigments for an Expressive navigation destination.
30#[derive(Clone, Copy, Debug, Default, PartialEq)]
31pub struct NavigationItemColors {
32    /// Icon color when the destination is selected.
33    pub selected_icon: Option<Hsla>,
34    /// Label color when selected and the icon is positioned above the label.
35    pub selected_label_top: Option<Hsla>,
36    /// Label color when selected and the icon is positioned at the logical start.
37    pub selected_label_start: Option<Hsla>,
38    /// Fill color for the selected destination pill indicator.
39    pub selected_indicator: Option<Hsla>,
40    /// Icon color when the destination is unselected.
41    pub unselected_icon: Option<Hsla>,
42    /// Label color when the destination is unselected.
43    pub unselected_label: Option<Hsla>,
44    /// Icon color when the destination is disabled.
45    pub disabled_icon: Option<Hsla>,
46    /// Label color when the destination is disabled.
47    pub disabled_label: Option<Hsla>,
48}
49
50/// One destination or tab with an ID unique within its collection.
51pub struct NavigationItem {
52    pub(super) id: SharedString,
53    pub(super) label: SharedString,
54    pub(super) icon: Option<Icon>,
55    pub(super) icon_position: Option<NavigationItemIconPosition>,
56    pub(super) label_content: Option<AnyElement>,
57    pub(super) badge: Option<Badge>,
58    pub(super) indicator_padding: Option<(LogicalEdges, LogicalEdges)>,
59    pub(super) colors: NavigationItemColors,
60    pub(super) interaction_source: Option<Entity<InteractionSource>>,
61    pub(super) disabled: bool,
62}
63
64impl NavigationItem {
65    /// Creates a navigation destination or tab with a unique ID and visible label.
66    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
67        Self {
68            id: id.into(),
69            label: label.into(),
70            icon: None,
71            icon_position: None,
72            label_content: None,
73            badge: None,
74            indicator_padding: None,
75            colors: NavigationItemColors::default(),
76            interaction_source: None,
77            disabled: false,
78        }
79    }
80
81    /// Sets the destination's icon.
82    pub fn icon(mut self, icon: Icon) -> Self {
83        self.icon = Some(icon);
84        self
85    }
86
87    /// Disables pointer and keyboard activation for this destination.
88    pub fn disabled(mut self, disabled: bool) -> Self {
89        self.disabled = disabled;
90        self
91    }
92
93    /// Overrides icon placement inherited from the tab, bar, or rail.
94    pub fn icon_position(mut self, position: NavigationItemIconPosition) -> Self {
95        self.icon_position = Some(position);
96        self
97    }
98
99    /// Replaces the visible label while retaining the accessible name.
100    pub fn label_content(mut self, content: impl IntoElement) -> Self {
101        self.label_content = Some(content.into_any_element());
102        self
103    }
104
105    /// Anchors a standalone badge to the icon, or to the label if there is no icon.
106    /// An accessible badge label becomes the destination's description.
107    pub fn badge(mut self, badge: Badge) -> Self {
108        self.badge = Some(badge);
109        self
110    }
111
112    /// Sets the rail indicator's logical content padding without shrinking its target.
113    pub fn indicator_padding(mut self, collapsed: LogicalEdges, expanded: LogicalEdges) -> 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        Option<Entity<RowState>>,
226    ) {
227        (
228            self.id,
229            self.label,
230            self.items,
231            self.selected,
232            self.on_select,
233            self.font_scale,
234            self.state,
235        )
236    }
237
238    pub(super) fn retain_roving_stop(mut self) -> Self {
239        self.retain_roving_stop = true;
240        self
241    }
242
243    fn row_state(&self, window: &mut Window, cx: &mut App) -> Entity<RowState> {
244        row_state_for(&self.id, window, cx)
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}