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