Skip to main content

gpui_material_components/navigation/
drawer.rs

1use std::{collections::HashSet, rc::Rc};
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, Hsla, IntoElement, Pixels, SharedString, Window, px,
5};
6use gpui_material_theme::CornerShape;
7
8use crate::{DialogCloseReason, DialogProperties, DialogState};
9
10use super::items::{NavigationItem, NavigationItems};
11
12mod render;
13
14/// Presentation mode for a standalone [`NavigationDrawer`].
15#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
16pub enum NavigationDrawerMode {
17    /// Docked side drawer that participates in parent layout.
18    #[default]
19    Standard,
20    /// Modal overlay drawer presented above a scrim with focus trapping.
21    Modal,
22}
23
24/// Ordered entry inside a [`NavigationDrawer`] destination list.
25pub enum NavigationDrawerEntry {
26    /// A selectable navigation destination.
27    Item(Box<NavigationItem>),
28    /// A non-interactive section heading label.
29    Header(SharedString),
30    /// A horizontal divider separating destination groups.
31    Divider,
32}
33
34impl NavigationDrawerEntry {
35    /// Creates a destination item entry.
36    pub fn item(item: NavigationItem) -> Self {
37        Self::Item(Box::new(item))
38    }
39}
40
41impl From<NavigationItem> for NavigationDrawerEntry {
42    fn from(item: NavigationItem) -> Self {
43        Self::Item(Box::new(item))
44    }
45}
46
47/// Convenience section grouping an optional heading with a list of [`NavigationItem`]s.
48pub struct NavigationDrawerSection {
49    /// Optional section heading displayed above the items.
50    pub header: Option<SharedString>,
51    /// Ordered navigation items belonging to this section.
52    pub items: Vec<NavigationItem>,
53}
54
55impl NavigationDrawerSection {
56    /// Creates a drawer section containing the given navigation items and no heading.
57    pub fn new(items: impl IntoIterator<Item = NavigationItem>) -> Self {
58        Self {
59            header: None,
60            items: items.into_iter().collect(),
61        }
62    }
63
64    /// Sets the section heading label.
65    pub fn header(mut self, title: impl Into<SharedString>) -> Self {
66        self.header = Some(title.into());
67        self
68    }
69}
70
71/// Per-instance pigment overrides for [`NavigationDrawer`]. Omitted fields use the window theme.
72#[derive(Clone, Copy, Debug, Default, PartialEq)]
73pub struct NavigationDrawerColors {
74    /// Background color override for the drawer surface.
75    pub container: Option<Hsla>,
76    /// Default foreground color override for drawer content.
77    pub content: Option<Hsla>,
78    /// Foreground color override for section headings and the drawer headline.
79    pub header: Option<Hsla>,
80    /// Color override for horizontal dividers.
81    pub divider: Option<Hsla>,
82    /// Fill color override for the selected destination pill indicator.
83    pub active_indicator: Option<Hsla>,
84    /// Foreground color override for the selected destination icon and label.
85    pub active_content: Option<Hsla>,
86    /// Foreground color override for unselected destination icons and labels.
87    pub inactive_content: Option<Hsla>,
88    /// Color override for the modal backdrop scrim.
89    pub scrim: Option<Hsla>,
90    /// Opacity override for the modal backdrop scrim.
91    pub scrim_opacity: Option<f32>,
92}
93
94pub(super) type DismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
95pub(super) type Closed = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
96
97/// Full-width Material 3 Navigation Drawer (360 dp default width) with Standard (docked) and
98/// Modal (side-sheet) presentations, sections, dividers, and 56 dp pill destination indicators.
99#[derive(IntoElement)]
100pub struct NavigationDrawer {
101    pub(super) id: ElementId,
102    pub(super) items: NavigationItems,
103    pub(super) entries: Vec<NavigationDrawerEntry>,
104    pub(super) dividers_before: HashSet<SharedString>,
105    pub(super) mode: NavigationDrawerMode,
106    pub(super) open: bool,
107    pub(super) width: Pixels,
108    pub(super) headline: Option<SharedString>,
109    pub(super) header: Option<AnyElement>,
110    pub(super) footer: Option<AnyElement>,
111    pub(super) shape: Option<CornerShape>,
112    pub(super) colors: NavigationDrawerColors,
113    pub(super) modal_state: Option<Entity<DialogState>>,
114    pub(super) modal_properties: DialogProperties,
115    pub(super) on_dismiss_request: Option<DismissRequest>,
116    pub(super) on_closed: Option<Closed>,
117}
118
119impl NavigationDrawer {
120    /// Default Material 3 navigation drawer width (360 dp).
121    pub const DEFAULT_WIDTH: Pixels = px(360.);
122
123    /// Creates a standard navigation drawer with the given element ID and controlled [`NavigationItems`].
124    pub fn new(id: impl Into<ElementId>, items: NavigationItems) -> Self {
125        Self {
126            id: id.into(),
127            items,
128            entries: Vec::new(),
129            dividers_before: HashSet::new(),
130            mode: NavigationDrawerMode::default(),
131            open: true,
132            width: Self::DEFAULT_WIDTH,
133            headline: None,
134            header: None,
135            footer: None,
136            shape: None,
137            colors: NavigationDrawerColors::default(),
138            modal_state: None,
139            modal_properties: DialogProperties::default(),
140            on_dismiss_request: None,
141            on_closed: None,
142        }
143    }
144
145    /// Appends ordered destination, header, or divider entries to the drawer list.
146    pub fn entries(mut self, entries: impl IntoIterator<Item = NavigationDrawerEntry>) -> Self {
147        self.entries.extend(entries);
148        self
149    }
150
151    /// Appends a section heading followed by its navigation items.
152    pub fn section(
153        mut self,
154        header: impl Into<SharedString>,
155        items: impl IntoIterator<Item = NavigationItem>,
156    ) -> Self {
157        self.entries
158            .push(NavigationDrawerEntry::Header(header.into()));
159        self.entries
160            .extend(items.into_iter().map(NavigationDrawerEntry::item));
161        self
162    }
163
164    /// Appends a [`NavigationDrawerSection`] with an optional header and its items.
165    pub fn push_section(mut self, section: NavigationDrawerSection) -> Self {
166        if let Some(header) = section.header {
167            self.entries.push(NavigationDrawerEntry::Header(header));
168        }
169        self.entries
170            .extend(section.items.into_iter().map(NavigationDrawerEntry::item));
171        self
172    }
173
174    /// Appends a horizontal divider entry to the ordered entries list.
175    pub fn divider(mut self) -> Self {
176        self.entries.push(NavigationDrawerEntry::Divider);
177        self
178    }
179
180    /// Inserts a horizontal divider immediately before the destination with matching `item_id`.
181    pub fn divider_before(mut self, item_id: impl Into<SharedString>) -> Self {
182        self.dividers_before.insert(item_id.into());
183        self
184    }
185
186    /// Chooses Standard (docked, default) or Modal (side-sheet overlay) mode.
187    pub fn mode(mut self, mode: NavigationDrawerMode) -> Self {
188        self.mode = mode;
189        self
190    }
191
192    /// Controls whether a [`NavigationDrawerMode::Standard`] drawer is open (expanded, default `true`)
193    /// or collapsed to zero width with a smooth spatial width transition.
194    ///
195    /// Ignored in [`NavigationDrawerMode::Modal`], which uses [`Self::modal_state`].
196    pub fn open(mut self, open: bool) -> Self {
197        self.open = open;
198        self
199    }
200
201    /// Sets the drawer width in logical pixels (defaults to 360 dp, clamped to viewport).
202    pub fn width(mut self, width: Pixels) -> Self {
203        let value = f32::from(width);
204        if value.is_finite() && value > 0. {
205            self.width = width.max(px(200.));
206        }
207        self
208    }
209
210    /// Sets the drawer title displayed in Standard mode and used as the modal sheet's accessible name.
211    pub fn headline(mut self, headline: impl Into<SharedString>) -> Self {
212        self.headline = Some(headline.into());
213        self
214    }
215
216    /// Supplies custom header content above the destination list.
217    pub fn header(mut self, header: impl IntoElement) -> Self {
218        self.header = Some(header.into_any_element());
219        self
220    }
221
222    /// Supplies custom footer content anchored beneath the scrolling destination list.
223    pub fn footer(mut self, footer: impl IntoElement) -> Self {
224        self.footer = Some(footer.into_any_element());
225        self
226    }
227
228    /// Overrides the container corner shape.
229    pub fn shape(mut self, shape: CornerShape) -> Self {
230        self.shape = Some(shape);
231        self
232    }
233
234    /// Overrides container, content, header, divider, indicator, and modal scrim colors independently.
235    pub fn colors(mut self, colors: NavigationDrawerColors) -> Self {
236        self.colors = colors;
237        self
238    }
239
240    /// Attaches a caller-owned `DialogState` for `NavigationDrawerMode::Modal`.
241    pub fn modal_state(mut self, state: &Entity<DialogState>) -> Self {
242        self.modal_state = Some(state.clone());
243        self
244    }
245
246    /// Configures Escape and outside-click dismissal rules in Modal mode.
247    pub fn modal_properties(mut self, properties: DialogProperties) -> Self {
248        self.modal_properties = properties;
249        self
250    }
251
252    /// Intercepts user-initiated modal dismissal requests; return `false` to veto closing.
253    pub fn on_dismiss_request(
254        mut self,
255        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
256    ) -> Self {
257        self.on_dismiss_request = Some(Rc::new(callback));
258        self
259    }
260
261    /// Invoked once when an accepted modal dismissal closes the drawer.
262    pub fn on_closed(
263        mut self,
264        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
265    ) -> Self {
266        self.on_closed = Some(Rc::new(callback));
267        self
268    }
269}