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