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