Skip to main content

gpui_material_components/navigation/
rail.rs

1use std::{collections::HashMap, rc::Rc};
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, Hsla, InteractiveElement, IntoElement, ParentElement,
5    Pixels, RenderOnce, SharedString, Styled, Window, div, prelude::FluentBuilder, px,
6};
7use gpui_base::TestSupportExt;
8use gpui_material_foundation::{Surface, animate, current_material_theme};
9use gpui_material_theme::{ColorRole, CornerRole, CornerShape, MotionKind, MotionSpeed, TypeRole};
10
11use crate::{
12    DialogCloseReason, DialogProperties, DialogState, Sheet, SheetColors, SheetEdge, SheetMargins,
13    SheetMode, SheetPlacement, Text,
14};
15
16use super::items::{NavigationItems, Presentation};
17
18mod state;
19pub use state::NavigationRailState;
20
21/// Presentation mode of a docked [`NavigationRail`].
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum RailMode {
24    /// Narrow rail showing stacked icons and labels.
25    #[default]
26    Collapsed,
27    /// Wide rail showing inline icons beside labels.
28    Expanded,
29    /// Hidden rail occupying zero width.
30    Hidden,
31}
32
33/// Distribution of standard destinations along the vertical axis.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum NavigationRailArrangement {
36    /// Pack destinations at the top.
37    #[default]
38    Start,
39    /// Center destinations vertically.
40    Center,
41    /// Pack destinations at the bottom.
42    End,
43    /// Distribute destinations with equal space between them.
44    SpaceBetween,
45    /// Distribute destinations with equal space around each item.
46    SpaceAround,
47    /// Distribute destinations with equal space between and around them.
48    SpaceEvenly,
49}
50
51/// Logical insets in pixels, also used inside a destination's indicator.
52#[derive(Clone, Copy, Debug, Default, PartialEq)]
53pub struct NavigationRailPadding {
54    /// Logical start inset in pixels.
55    pub start: Pixels,
56    /// Logical end inset in pixels.
57    pub end: Pixels,
58    /// Top inset in pixels.
59    pub top: Pixels,
60    /// Bottom inset in pixels.
61    pub bottom: Pixels,
62}
63
64impl NavigationRailPadding {
65    fn docked_default() -> Self {
66        Self {
67            start: px(4.),
68            end: px(4.),
69            top: px(4.),
70            bottom: px(8.),
71        }
72    }
73}
74
75/// Per-mode shape overrides. Omitted values use the default docked or sheet shape.
76#[derive(Clone, Copy, Debug, Default, PartialEq)]
77pub struct NavigationRailShapes {
78    /// Corner shape override when the rail is collapsed.
79    pub collapsed: Option<CornerShape>,
80    /// Corner shape override when the rail is expanded.
81    pub expanded: Option<CornerShape>,
82    /// Corner shape override when the rail is presented as a modal sheet.
83    pub modal: Option<CornerShape>,
84}
85
86/// Independent local colors and scrim opacity.
87#[derive(Clone, Copy, Debug, Default, PartialEq)]
88pub struct NavigationRailColors {
89    /// Background color override for the docked rail container.
90    pub container: Option<Hsla>,
91    /// Default foreground color override for docked rail content.
92    pub content: Option<Hsla>,
93    /// Background color override for the modal rail sheet container.
94    pub modal_container: Option<Hsla>,
95    /// Default foreground color override for modal rail sheet content.
96    pub modal_content: Option<Hsla>,
97    /// Color override for the modal backdrop scrim.
98    pub scrim: Option<Hsla>,
99    /// Opacity override for the modal backdrop scrim.
100    pub scrim_opacity: Option<f32>,
101}
102
103/// Window-local side-sheet policy for the optional modal rail.
104#[derive(Clone, Copy, Debug, Default, PartialEq)]
105pub struct RailModalOptions {
106    /// Escape and outside-click dismissal rules for the modal sheet.
107    pub properties: DialogProperties,
108    /// Stacking layer for nested modals.
109    pub layer: usize,
110    /// Whether the modal side sheet is docked or detached.
111    pub placement: SheetPlacement,
112    /// Logical margins applied when [`SheetPlacement::Detached`] is active.
113    pub margins: SheetMargins,
114    /// When `true`, hides the docked rail (zero width) while collapsed if a modal state is bound.
115    pub hide_on_collapse: bool,
116}
117
118#[derive(Clone, Copy, PartialEq)]
119pub(super) struct RailPresentation {
120    pub expanded: bool,
121    pub arrangement: NavigationRailArrangement,
122    pub spacing: Pixels,
123    pub content: Option<Hsla>,
124}
125
126type Destinations = Box<dyn FnOnce(RailMode) -> AnyElement>;
127type DismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
128type Closed = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
129
130/// Material wide navigation rail. The optional modal uses the side-sheet session.
131#[derive(IntoElement)]
132pub struct NavigationRail {
133    id: ElementId,
134    items: NavigationItems,
135    mode: RailMode,
136    state: Option<Entity<NavigationRailState>>,
137    title: Option<SharedString>,
138    header: Option<AnyElement>,
139    fab: Option<AnyElement>,
140    expanded_width: Pixels,
141    modal: Option<Entity<DialogState>>,
142    modal_options: RailModalOptions,
143    destination_content: Option<Destinations>,
144    dividers: HashMap<SharedString, AnyElement>,
145    arrangement: NavigationRailArrangement,
146    destination_spacing: Pixels,
147    content_padding: Option<NavigationRailPadding>,
148    header_spacing: Pixels,
149    expanded_header_top_padding: Pixels,
150    shapes: NavigationRailShapes,
151    colors: NavigationRailColors,
152    dismiss: Option<DismissRequest>,
153    closed: Option<Closed>,
154}
155
156impl NavigationRail {
157    /// Creates a collapsed navigation rail with the given element ID and controlled [`NavigationItems`].
158    pub fn new(id: impl Into<ElementId>, items: NavigationItems) -> Self {
159        Self {
160            id: id.into(),
161            items,
162            mode: RailMode::Collapsed,
163            state: None,
164            title: None,
165            header: None,
166            fab: None,
167            expanded_width: px(240.),
168            modal: None,
169            modal_options: RailModalOptions::default(),
170            destination_content: None,
171            dividers: HashMap::new(),
172            arrangement: NavigationRailArrangement::default(),
173            destination_spacing: px(4.),
174            content_padding: None,
175            header_spacing: px(4.),
176            expanded_header_top_padding: px(0.),
177            shapes: NavigationRailShapes::default(),
178            colors: NavigationRailColors::default(),
179            dismiss: None,
180            closed: None,
181        }
182    }
183
184    /// Sets the docked rail mode (default [`RailMode::Collapsed`]). Ignored when [`Self::state`] is bound.
185    pub fn mode(mut self, mode: RailMode) -> Self {
186        self.mode = mode;
187        self
188    }
189
190    /// Uses retained presentation and transitions in place of the supplied mode.
191    pub fn state(mut self, state: &Entity<NavigationRailState>) -> Self {
192        self.state = Some(state.clone());
193        self
194    }
195
196    /// Sets the accessible title used for the rail and its optional modal sheet (default `"Navigation"`).
197    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
198        self.title = Some(title.into());
199        self
200    }
201
202    /// Places a custom header element at the top of the rail (such as a menu toggle button).
203    pub fn header(mut self, header: impl IntoElement) -> Self {
204        self.header = Some(header.into_any_element());
205        self
206    }
207
208    /// Places a floating action button below the header.
209    pub fn fab(mut self, fab: impl IntoElement) -> Self {
210        self.fab = Some(fab.into_any_element());
211        self
212    }
213
214    /// Sets the expanded rail width in logical pixels, clamped to `220..=360` px (default 240 px).
215    pub fn expanded_width(mut self, width: Pixels) -> Self {
216        if f32::from(width).is_finite() {
217            self.expanded_width = width.clamp(px(220.), px(360.));
218        }
219        self
220    }
221
222    /// Replaces the standard destination list. The caller owns its navigation semantics.
223    pub fn destination_content<E: IntoElement + 'static>(
224        mut self,
225        build: impl FnOnce(RailMode) -> E + 'static,
226    ) -> Self {
227        self.destination_content = Some(Box::new(move |mode| build(mode).into_any_element()));
228        self
229    }
230
231    /// Places a divider or separator after one standard destination.
232    pub fn divider_after(
233        mut self,
234        destination: impl Into<SharedString>,
235        divider: impl IntoElement,
236    ) -> Self {
237        self.dividers
238            .insert(destination.into(), divider.into_any_element());
239        self
240    }
241
242    /// Sets how destinations are vertically distributed within the rail (default [`NavigationRailArrangement::Start`]).
243    pub fn arrangement(mut self, arrangement: NavigationRailArrangement) -> Self {
244        self.arrangement = arrangement;
245        self
246    }
247
248    /// Sets the vertical gap between destinations in logical pixels (default 4 px).
249    pub fn destination_spacing(mut self, spacing: Pixels) -> Self {
250        self.destination_spacing = length(spacing);
251        self
252    }
253
254    /// Overrides the logical inner padding of the rail container.
255    pub fn content_padding(mut self, padding: NavigationRailPadding) -> Self {
256        self.content_padding = Some(padding);
257        self
258    }
259
260    /// Sets the vertical spacing below the header and FAB slots (default 4 px).
261    pub fn header_spacing(mut self, spacing: Pixels) -> Self {
262        self.header_spacing = length(spacing);
263        self
264    }
265
266    /// Sets extra top padding above the header when the rail is expanded.
267    pub fn expanded_header_top_padding(mut self, padding: Pixels) -> Self {
268        self.expanded_header_top_padding = length(padding);
269        self
270    }
271
272    /// Overrides corner shapes for collapsed, expanded, and modal presentations.
273    pub fn shapes(mut self, shapes: NavigationRailShapes) -> Self {
274        self.shapes = shapes;
275        self
276    }
277
278    /// Overrides container, content, and modal scrim colors.
279    pub fn colors(mut self, colors: NavigationRailColors) -> Self {
280        self.colors = colors;
281        self
282    }
283
284    /// Uses DialogState for modal visibility and focus restoration.
285    pub fn modal(mut self, state: &Entity<DialogState>) -> Self {
286        self.modal = Some(state.clone());
287        self
288    }
289
290    /// Configures side-sheet presentation and dismissal policy for the modal rail.
291    pub fn modal_options(mut self, options: RailModalOptions) -> Self {
292        self.modal_options = options;
293        self
294    }
295
296    /// Intercepts user-initiated modal dismissal requests; return `false` to veto closing.
297    pub fn on_dismiss_request(
298        mut self,
299        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
300    ) -> Self {
301        self.dismiss = Some(Rc::new(callback));
302        self
303    }
304
305    /// Invoked once when an accepted modal dismissal closes the rail sheet.
306    pub fn on_modal_close(
307        mut self,
308        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
309    ) -> Self {
310        self.closed = Some(Rc::new(callback));
311        self
312    }
313
314    fn docked(&self, window: &mut Window, cx: &mut App) -> DockedFrame {
315        let viewport = length(window.viewport_size().width);
316        let collapse_width = if self.modal.is_some() && self.modal_options.hide_on_collapse {
317            px(0.)
318        } else {
319            px(96.).min(viewport)
320        };
321        let expand_width = self.expanded_width.min(viewport);
322        if let Some(state) = &self.state {
323            let (weights, target, moving) = state.update(cx, |state, cx| {
324                let weights = state.sample(cx);
325                (weights, state.target_value(), state.is_animating())
326            });
327            if moving && window.is_visible() {
328                window.request_animation_frame();
329            }
330            let width = collapse_width * weights.collapsed + expand_width * weights.expanded;
331            let mode = if target == RailMode::Hidden && moving {
332                if weights.expanded >= weights.collapsed {
333                    RailMode::Expanded
334                } else {
335                    RailMode::Collapsed
336                }
337            } else {
338                target
339            };
340            let size = weights.expanded + weights.collapsed;
341            DockedFrame {
342                width,
343                mode,
344                expansion: if size > 0. {
345                    weights.expanded / size
346                } else {
347                    0.
348                },
349            }
350        } else {
351            let theme = current_material_theme(window, cx);
352            let motion = theme.motion.spec(
353                MotionKind::Spatial,
354                MotionSpeed::Default,
355                cx.reduce_motion(),
356            );
357            let target = match self.mode {
358                RailMode::Collapsed => collapse_width,
359                RailMode::Expanded => expand_width,
360                RailMode::Hidden => px(0.),
361            };
362            let width = px(animate(
363                (self.id.clone(), "rail-width"),
364                target.into(),
365                motion,
366                window,
367                cx,
368            ))
369            .clamp(px(0.), viewport);
370            let span = expand_width - collapse_width;
371            let expansion = if span > px(0.) {
372                ((width - collapse_width) / span).clamp(0., 1.)
373            } else {
374                f32::from(self.mode == RailMode::Expanded)
375            };
376            DockedFrame {
377                width,
378                mode: self.mode,
379                expansion,
380            }
381        }
382    }
383}
384
385struct DockedFrame {
386    width: Pixels,
387    mode: RailMode,
388    expansion: f32,
389}
390
391impl RenderOnce for NavigationRail {
392    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
393        let frame = self.docked(window, cx);
394        let modal = self.modal.as_ref().and_then(|state| {
395            let open = state.read(cx).is_open();
396            let id = (self.id.clone(), "rail-modal").into();
397            let presence = crate::motion::presence(&id, open, 240, window, cx);
398            presence.should_render().then(|| (state.clone(), presence))
399        });
400        // Resolve before either placement so a destination retains its handle.
401        let items = self.items.retain(window, cx);
402        let scope = window
403            .use_keyed_state((self.id.clone(), "rail-docked-focus"), cx, |_, cx| {
404                cx.focus_handle().tab_stop(false)
405            })
406            .read(cx)
407            .clone();
408        let frame_id = (self.id.clone(), "rail-frame");
409        let docked = div()
410            .id(frame_id)
411            .test_support()
412            .w(frame.width)
413            .h_full()
414            .flex_none()
415            .overflow_hidden();
416        let modal_visible = modal.is_some();
417        if !modal_visible && (frame.mode == RailMode::Hidden || frame.width <= px(0.)) {
418            if scope.contains_focused(window, cx) {
419                let focus = window.focused(cx);
420                window.defer(cx, move |window, cx| {
421                    if window
422                        .focused(cx)
423                        .is_none_or(|current| Some(current) == focus)
424                    {
425                        window.focus_next(cx);
426                    }
427                });
428            }
429            return docked.into_any_element();
430        }
431        let mode = if modal_visible {
432            RailMode::Expanded
433        } else {
434            frame.mode
435        };
436        let expanded = mode == RailMode::Expanded;
437        let title = self.title.unwrap_or_else(|| "Navigation".into());
438        let theme = current_material_theme(window, cx);
439        let viewport = window.viewport_size();
440        let layout = theme.layout;
441        let colors = self.colors;
442        let content_color = if modal_visible {
443            colors.modal_content
444        } else {
445            colors.content
446        };
447        let padding = self.content_padding.unwrap_or_else(|| {
448            if modal_visible {
449                NavigationRailPadding::default()
450            } else {
451                NavigationRailPadding::docked_default()
452            }
453        });
454        let (left, right) = layout.horizontal(length(padding.start), length(padding.end));
455        let destinations = match self.destination_content {
456            Some(build) => div()
457                .id("custom-destinations")
458                .flex_1()
459                .min_h_0()
460                .child(build(mode))
461                .into_any_element(),
462            None => items.with_rail_dividers(self.dividers).render_row(
463                Presentation::Rail(RailPresentation {
464                    expanded,
465                    arrangement: self.arrangement,
466                    spacing: self.destination_spacing,
467                    content: content_color,
468                }),
469                window,
470                cx,
471            ),
472        };
473        let panel = div()
474            .id("rail-content")
475            .test_support()
476            .flex()
477            .flex_col()
478            .h_full()
479            .min_h_0()
480            .gap(self.header_spacing)
481            .pt(length(padding.top))
482            .pb(length(padding.bottom))
483            .pl(left)
484            .pr(right)
485            .when_some(content_color, Styled::text_color)
486            .children(self.header.map(|header| {
487                div()
488                    .id("rail-header")
489                    .test_support()
490                    .flex_none()
491                    .pt(if expanded {
492                        self.expanded_header_top_padding
493                    } else {
494                        px(0.)
495                    })
496                    .child(header)
497            }))
498            .children(
499                self.fab
500                    .map(|fab| div().id("rail-fab").flex_none().child(fab)),
501            )
502            .when(expanded && !modal_visible, |panel| {
503                panel.child(
504                    div().px(px(12.)).child(
505                        Text::new(title.clone())
506                            .id("rail-title")
507                            .role(TypeRole::TitleMedium)
508                            .wrap(),
509                    ),
510                )
511            })
512            .child(destinations);
513
514        let shape = docked_shape(self.shapes, frame.expansion, frame.width, viewport.height);
515        let surface = Surface::new(ColorRole::Surface)
516            .shape(shape)
517            .when_some(colors.container, Surface::container_color)
518            .size_full()
519            .overflow_hidden()
520            .when_some(content_color, Surface::content_color);
521        if let Some((state, presence)) = modal {
522            let options = self.modal_options;
523            return docked
524                .child(
525                    Surface::new(ColorRole::Surface)
526                        .shape(shape)
527                        .size_full()
528                        .when_some(colors.container, Surface::container_color),
529                )
530                .child(
531                    Sheet::new(self.id, &state, title, panel)
532                        .mode(SheetMode::Modal)
533                        .edge(SheetEdge::Start)
534                        .extent(self.expanded_width)
535                        .placement(options.placement)
536                        .margins(options.margins)
537                        .layer(options.layer)
538                        .properties(options.properties)
539                        .sampled_presence(presence)
540                        .colors(SheetColors {
541                            container: colors.modal_container,
542                            content: colors.modal_content,
543                            scrim: colors.scrim,
544                            ..Default::default()
545                        })
546                        .when_some(colors.scrim_opacity, Sheet::scrim_opacity)
547                        .when_some(self.shapes.modal.or(self.shapes.expanded), Sheet::shape)
548                        .when_some(self.dismiss, |sheet, callback| {
549                            sheet.on_dismiss_request(move |reason, window, cx| {
550                                callback(reason, window, cx)
551                            })
552                        })
553                        .when_some(self.closed, |sheet, callback| {
554                            sheet.on_close(move |reason, window, cx| callback(reason, window, cx))
555                        }),
556                )
557                .into_any_element();
558        }
559
560        docked
561            .track_focus(&scope)
562            .child(surface.child(panel))
563            .into_any_element()
564    }
565}
566
567fn docked_shape(
568    shapes: NavigationRailShapes,
569    expanded: f32,
570    width: Pixels,
571    height: Pixels,
572) -> CornerShape {
573    let collapsed = shapes.collapsed.unwrap_or_else(|| CornerRole::None.shape());
574    let target = shapes.expanded.unwrap_or_else(|| CornerRole::None.shape());
575    if expanded <= 0. || collapsed == target {
576        return collapsed;
577    }
578    if expanded >= 1. {
579        return target;
580    }
581    let resolve = |shape| match shape {
582        CornerShape::Radii(radii) => radii,
583        CornerShape::Full => [f32::from(width.min(height)) * 0.5; 4],
584    };
585    let a = resolve(collapsed);
586    let b = resolve(target);
587    CornerShape::Radii(std::array::from_fn(|i| a[i] + (b[i] - a[i]) * expanded))
588}
589
590pub(super) fn length(value: Pixels) -> Pixels {
591    if f32::from(value).is_finite() {
592        value.max(px(0.))
593    } else {
594        px(0.)
595    }
596}