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) width: Pixels,
107    pub(super) headline: Option<SharedString>,
108    pub(super) header: Option<AnyElement>,
109    pub(super) footer: Option<AnyElement>,
110    pub(super) shape: Option<CornerShape>,
111    pub(super) colors: NavigationDrawerColors,
112    pub(super) modal_state: Option<Entity<DialogState>>,
113    pub(super) modal_properties: DialogProperties,
114    pub(super) on_dismiss_request: Option<DismissRequest>,
115    pub(super) on_closed: Option<Closed>,
116}
117
118impl NavigationDrawer {
119    /// Default Material 3 navigation drawer width (360 dp).
120    pub const DEFAULT_WIDTH: Pixels = px(360.);
121
122    /// Creates a standard navigation drawer with the given element ID and controlled [`NavigationItems`].
123    pub fn new(id: impl Into<ElementId>, items: NavigationItems) -> Self {
124        Self {
125            id: id.into(),
126            items,
127            entries: Vec::new(),
128            dividers_before: HashSet::new(),
129            mode: NavigationDrawerMode::default(),
130            width: Self::DEFAULT_WIDTH,
131            headline: None,
132            header: None,
133            footer: None,
134            shape: None,
135            colors: NavigationDrawerColors::default(),
136            modal_state: None,
137            modal_properties: DialogProperties::default(),
138            on_dismiss_request: None,
139            on_closed: None,
140        }
141    }
142
143    /// Appends ordered destination, header, or divider entries to the drawer list.
144    pub fn entries(mut self, entries: impl IntoIterator<Item = NavigationDrawerEntry>) -> Self {
145        self.entries.extend(entries);
146        self
147    }
148
149    /// Appends a section heading followed by its navigation items.
150    pub fn section(
151        mut self,
152        header: impl Into<SharedString>,
153        items: impl IntoIterator<Item = NavigationItem>,
154    ) -> Self {
155        self.entries
156            .push(NavigationDrawerEntry::Header(header.into()));
157        self.entries
158            .extend(items.into_iter().map(NavigationDrawerEntry::item));
159        self
160    }
161
162    /// Appends a [`NavigationDrawerSection`] with an optional header and its items.
163    pub fn push_section(mut self, section: NavigationDrawerSection) -> Self {
164        if let Some(header) = section.header {
165            self.entries.push(NavigationDrawerEntry::Header(header));
166        }
167        self.entries
168            .extend(section.items.into_iter().map(NavigationDrawerEntry::item));
169        self
170    }
171
172    /// Appends a horizontal divider entry to the ordered entries list.
173    pub fn divider(mut self) -> Self {
174        self.entries.push(NavigationDrawerEntry::Divider);
175        self
176    }
177
178    /// Inserts a horizontal divider immediately before the destination with matching `item_id`.
179    pub fn divider_before(mut self, item_id: impl Into<SharedString>) -> Self {
180        self.dividers_before.insert(item_id.into());
181        self
182    }
183
184    /// Chooses Standard (docked, default) or Modal (side-sheet overlay) mode.
185    pub fn mode(mut self, mode: NavigationDrawerMode) -> Self {
186        self.mode = mode;
187        self
188    }
189
190    /// Sets the drawer width in logical pixels (defaults to 360 dp, clamped to viewport).
191    pub fn width(mut self, width: Pixels) -> Self {
192        let value = f32::from(width);
193        if value.is_finite() && value > 0. {
194            self.width = width.max(px(200.));
195        }
196        self
197    }
198
199    /// Sets the drawer title displayed in Standard mode and used as the modal sheet's accessible name.
200    pub fn headline(mut self, headline: impl Into<SharedString>) -> Self {
201        self.headline = Some(headline.into());
202        self
203    }
204
205    /// Supplies custom header content above the destination list.
206    pub fn header(mut self, header: impl IntoElement) -> Self {
207        self.header = Some(header.into_any_element());
208        self
209    }
210
211    /// Supplies custom footer content anchored beneath the scrolling destination list.
212    pub fn footer(mut self, footer: impl IntoElement) -> Self {
213        self.footer = Some(footer.into_any_element());
214        self
215    }
216
217    /// Overrides the container corner shape.
218    pub fn shape(mut self, shape: CornerShape) -> Self {
219        self.shape = Some(shape);
220        self
221    }
222
223    /// Overrides container, content, header, divider, indicator, and modal scrim colors independently.
224    pub fn colors(mut self, colors: NavigationDrawerColors) -> Self {
225        self.colors = colors;
226        self
227    }
228
229    /// Attaches a caller-owned `DialogState` for `NavigationDrawerMode::Modal`.
230    pub fn modal_state(mut self, state: &Entity<DialogState>) -> Self {
231        self.modal_state = Some(state.clone());
232        self
233    }
234
235    /// Configures Escape and outside-click dismissal rules in Modal mode.
236    pub fn modal_properties(mut self, properties: DialogProperties) -> Self {
237        self.modal_properties = properties;
238        self
239    }
240
241    /// Intercepts user-initiated modal dismissal requests; return `false` to veto closing.
242    pub fn on_dismiss_request(
243        mut self,
244        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
245    ) -> Self {
246        self.on_dismiss_request = Some(Rc::new(callback));
247        self
248    }
249
250    /// Invoked once when an accepted modal dismissal closes the drawer.
251    pub fn on_closed(
252        mut self,
253        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
254    ) -> Self {
255        self.on_closed = Some(Rc::new(callback));
256        self
257    }
258}