Skip to main content

gpui_material_components/navigation/
adaptive_navigation.rs

1use std::time::Duration;
2
3use gpui::{
4    AnyElement, App, AvailableSpace, Bounds, ContentMask, Context, Element, ElementId, Entity,
5    GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId, ParentElement,
6    Pixels, Point, RenderOnce, Size, Style, Styled, Window, div, point, prelude::FluentBuilder,
7    relative, size,
8};
9use gpui_base::{TestSupportExt, motion::Easing};
10use gpui_material_foundation::{RetargetTransition, current_material_theme};
11use gpui_material_theme::{Direction, WidthClass};
12
13use super::{
14    NavigationBar, NavigationBarLayout, NavigationItems, NavigationRail, RailMode, Scaffold,
15    rail::length,
16};
17
18/// Current Material 3 Expressive navigation presentations.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum AdaptiveNavigationType {
21    /// Compact bottom navigation bar with vertical icon-over-label items.
22    ShortBarCompact,
23    /// Medium bottom navigation bar with horizontal icon-beside-label items.
24    ShortBarMedium,
25    /// Collapsed side navigation rail.
26    RailCollapsed,
27    /// Expanded side navigation rail with inline labels.
28    RailExpanded,
29    /// Leaves the scaffold's existing slots in place.
30    None,
31}
32
33impl AdaptiveNavigationType {
34    /// Selects the default Material navigation presentation for the given available width.
35    pub fn for_width(width: Pixels) -> Self {
36        match WidthClass::from_width(width.into()) {
37            WidthClass::Compact => Self::ShortBarCompact,
38            WidthClass::Medium => Self::ShortBarMedium,
39            _ => Self::RailCollapsed,
40        }
41    }
42
43    fn is_rail(self) -> bool {
44        matches!(self, Self::RailCollapsed | Self::RailExpanded)
45    }
46}
47
48/// Available scaffold space for an application-supplied navigation policy.
49#[derive(Clone, Copy, Debug, PartialEq)]
50pub struct AdaptiveNavigationInfo {
51    /// Bounded width and height available to the scaffold.
52    pub available_size: Size<Pixels>,
53    /// Material width class derived from `available_size.width`.
54    pub width_class: WidthClass,
55    /// Active layout direction from the window theme.
56    pub direction: Direction,
57}
58
59/// Settled visibility of the adaptive navigation slot.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub enum AdaptiveNavigationVisibility {
62    /// The navigation bar or rail is visible.
63    #[default]
64    Shown,
65    /// The navigation bar or rail is hidden.
66    Hidden,
67}
68
69impl AdaptiveNavigationVisibility {
70    fn fraction(self) -> f32 {
71        f32::from(self == Self::Shown)
72    }
73}
74
75/// Retained navigation visibility, independent of the current presentation.
76pub struct AdaptiveNavigationState {
77    current: AdaptiveNavigationVisibility,
78    target: AdaptiveNavigationVisibility,
79    fraction: f32,
80    duration: Duration,
81    transition: RetargetTransition,
82}
83
84impl Default for AdaptiveNavigationState {
85    fn default() -> Self {
86        Self::new(AdaptiveNavigationVisibility::Shown)
87    }
88}
89
90impl AdaptiveNavigationState {
91    /// Creates retained navigation visibility state starting at `initial` with a 240 ms default transition.
92    pub fn new(initial: AdaptiveNavigationVisibility) -> Self {
93        Self {
94            current: initial,
95            target: initial,
96            fraction: initial.fraction(),
97            duration: Duration::from_millis(240),
98            transition: RetargetTransition::settled(initial.fraction()),
99        }
100    }
101
102    /// Sets the duration used when animating between shown and hidden states.
103    pub fn transition_duration(mut self, duration: Duration) -> Self {
104        self.duration = duration;
105        self
106    }
107
108    /// Last settled visibility.
109    pub fn current_value(&self) -> AdaptiveNavigationVisibility {
110        self.current
111    }
112
113    /// Visibility state currently settled at or transitioning toward.
114    pub fn target_value(&self) -> AdaptiveNavigationVisibility {
115        self.target
116    }
117
118    /// Returns whether a show/hide transition is currently running.
119    pub fn is_animating(&self) -> bool {
120        self.transition.is_animating()
121    }
122
123    /// The currently visible fraction of the slot, in 0..=1.
124    pub fn progress(&self) -> f32 {
125        self.fraction
126    }
127
128    /// Animates the navigation slot to [`AdaptiveNavigationVisibility::Shown`].
129    pub fn show(&mut self, cx: &mut Context<Self>) {
130        self.animate_to(AdaptiveNavigationVisibility::Shown, cx);
131    }
132
133    /// Animates the navigation slot to [`AdaptiveNavigationVisibility::Hidden`].
134    pub fn hide(&mut self, cx: &mut Context<Self>) {
135        self.animate_to(AdaptiveNavigationVisibility::Hidden, cx);
136    }
137
138    /// Toggles the target visibility between shown and hidden.
139    pub fn toggle(&mut self, cx: &mut Context<Self>) {
140        match self.target {
141            AdaptiveNavigationVisibility::Shown => self.hide(cx),
142            AdaptiveNavigationVisibility::Hidden => self.show(cx),
143        }
144    }
145
146    /// Moves immediately to `value` without animation.
147    pub fn snap_to(&mut self, value: AdaptiveNavigationVisibility, cx: &mut Context<Self>) {
148        if self.current != value || self.target != value || self.is_animating() {
149            self.target = value;
150            self.settle();
151            cx.notify();
152        }
153    }
154
155    fn animate_to(&mut self, target: AdaptiveNavigationVisibility, cx: &mut Context<Self>) {
156        if self.duration.is_zero() || cx.reduce_motion() {
157            self.snap_to(target, cx);
158            return;
159        }
160        self.sample(cx);
161        if self.target != target {
162            self.target = target;
163            let now = cx.background_executor().now();
164            self.transition.animate_to(
165                target.fraction(),
166                self.duration,
167                Easing::EaseInOut,
168                now,
169                false,
170            );
171            self.fraction = self.transition.value();
172            if !self.transition.is_animating() {
173                self.settle();
174            }
175            cx.notify();
176        }
177    }
178
179    fn settle(&mut self) {
180        self.current = self.target;
181        self.fraction = self.target.fraction();
182        self.transition.snap_to(self.fraction);
183    }
184
185    fn sample(&mut self, cx: &mut Context<Self>) {
186        if !self.transition.is_animating() {
187            return;
188        }
189        let now = cx.background_executor().now();
190        let (next, running) = self.transition.sample(now, cx.reduce_motion());
191        let notify = if !running {
192            self.settle();
193            true
194        } else if next != self.fraction {
195            self.fraction = next;
196            true
197        } else {
198            false
199        };
200        if notify {
201            let state = cx.weak_entity();
202            cx.defer(move |cx| {
203                let _ = state.update(cx, |_, cx| cx.notify());
204            });
205        }
206    }
207}
208
209type Policy = Box<dyn FnOnce(AdaptiveNavigationInfo) -> AdaptiveNavigationType>;
210type NavigationContent = Box<dyn FnOnce(AdaptiveNavigationType, AnyElement) -> AnyElement>;
211type Configure<T> = Box<dyn FnOnce(AdaptiveNavigationType, T) -> T>;
212
213/// Material 3 navigation suite for the existing Scaffold bar and rail slots.
214#[derive(IntoElement)]
215pub struct AdaptiveNavigation {
216    scaffold: Scaffold,
217    items: NavigationItems,
218    width: Pixels,
219    height: Option<Pixels>,
220    policy: Option<Policy>,
221    state: Option<Entity<AdaptiveNavigationState>>,
222    content: Option<NavigationContent>,
223    bar: Option<Configure<NavigationBar>>,
224    rail: Option<Configure<NavigationRail>>,
225}
226
227impl AdaptiveNavigation {
228    /// Uses the available width of the scaffold in logical units.
229    pub fn new(scaffold: Scaffold, items: NavigationItems, available_width: Pixels) -> Self {
230        Self {
231            scaffold,
232            items,
233            width: available_width,
234            height: None,
235            policy: None,
236            state: None,
237            content: None,
238            bar: None,
239            rail: None,
240        }
241    }
242
243    /// Supplies the bounded scaffold size when it differs from the viewport.
244    pub fn available_size(mut self, size: Size<Pixels>) -> Self {
245        self.width = size.width;
246        self.height = Some(size.height);
247        self
248    }
249
250    /// Forces a fixed navigation presentation regardless of available width.
251    pub fn navigation_type(self, kind: AdaptiveNavigationType) -> Self {
252        self.navigation_policy(move |_| kind)
253    }
254
255    /// Supplies a custom policy that maps [`AdaptiveNavigationInfo`] to a presentation type.
256    pub fn navigation_policy(
257        mut self,
258        policy: impl FnOnce(AdaptiveNavigationInfo) -> AdaptiveNavigationType + 'static,
259    ) -> Self {
260        self.policy = Some(Box::new(policy));
261        self
262    }
263
264    /// Binds retained visibility state for animated showing and hiding of the navigation slot.
265    pub fn state(mut self, state: &Entity<AdaptiveNavigationState>) -> Self {
266        self.state = Some(state.clone());
267        self
268    }
269
270    /// Composes or replaces the standard navigation in its scaffold slot.
271    pub fn navigation_content<E: IntoElement>(
272        mut self,
273        build: impl FnOnce(AdaptiveNavigationType, AnyElement) -> E + 'static,
274    ) -> Self {
275        self.content = Some(Box::new(move |kind, default| {
276            build(kind, default).into_any_element()
277        }));
278        self
279    }
280
281    /// Customizes the generated [`NavigationBar`] when a bottom-bar presentation is active.
282    pub fn navigation_bar(
283        mut self,
284        build: impl FnOnce(AdaptiveNavigationType, NavigationBar) -> NavigationBar + 'static,
285    ) -> Self {
286        self.bar = Some(Box::new(build));
287        self
288    }
289
290    /// Customizes the generated [`NavigationRail`] when a side-rail presentation is active.
291    pub fn navigation_rail(
292        mut self,
293        build: impl FnOnce(AdaptiveNavigationType, NavigationRail) -> NavigationRail + 'static,
294    ) -> Self {
295        self.rail = Some(Box::new(build));
296        self
297    }
298}
299
300impl RenderOnce for AdaptiveNavigation {
301    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
302        let viewport = window.viewport_size();
303        let available = size(
304            length(self.width),
305            length(self.height.unwrap_or(viewport.height)),
306        );
307        let direction = current_material_theme(window, cx).layout.direction;
308        let info = AdaptiveNavigationInfo {
309            available_size: available,
310            width_class: WidthClass::from_width(available.width.into()),
311            direction,
312        };
313        let kind = match self.policy {
314            Some(policy) => policy(info),
315            None => AdaptiveNavigationType::for_width(available.width),
316        };
317        let (fraction, moving) = self.state.as_ref().map_or((1., false), |state| {
318            state.update(cx, |state, cx| {
319                state.sample(cx);
320                (state.progress(), state.is_animating())
321            })
322        });
323        if moving && window.is_visible() {
324            window.request_animation_frame();
325        }
326        let scope = window
327            .use_keyed_state(
328                (self.items.id().clone(), "adaptive-navigation-focus"),
329                cx,
330                |_, cx| cx.focus_handle().tab_stop(false),
331            )
332            .read(cx)
333            .clone();
334        let items = self.items.retain(window, cx).retain_roving_stop();
335        if kind == AdaptiveNavigationType::None || fraction <= 0. {
336            if scope.contains_focused(window, cx) {
337                let previous = window.focused(cx);
338                window.defer(cx, move |window, cx| {
339                    if window.focused(cx) == previous {
340                        window.focus_next(cx);
341                        if window.focused(cx) == previous {
342                            window.blur(cx);
343                        }
344                    }
345                });
346            }
347            return self.scaffold;
348        }
349        let is_rail = kind.is_rail();
350        let default = if is_rail {
351            let mode = if kind == AdaptiveNavigationType::RailExpanded {
352                RailMode::Expanded
353            } else {
354                RailMode::Collapsed
355            };
356            let rail = NavigationRail::new("adaptive-rail", items).mode(mode);
357            match self.rail {
358                Some(build) => build(kind, rail),
359                None => rail,
360            }
361            .into_any_element()
362        } else {
363            let layout = if kind == AdaptiveNavigationType::ShortBarMedium {
364                NavigationBarLayout::Horizontal
365            } else {
366                NavigationBarLayout::Vertical
367            };
368            let bar = NavigationBar::new(items).layout(layout);
369            match self.bar {
370                Some(build) => build(kind, bar),
371                None => bar,
372            }
373            .into_any_element()
374        };
375        let content = match self.content {
376            Some(build) => build(kind, default),
377            None => default,
378        };
379        let content = div()
380            .flex()
381            .flex_col()
382            .when(is_rail, |content| content.h_full().max_w(available.width))
383            .when(!is_rail, |content| content.w_full().max_h(available.height))
384            .child(content);
385        let slot = div()
386            .id("adaptive-navigation-slot")
387            .test_support()
388            .track_focus(&scope)
389            .flex_none()
390            .when(is_rail, Styled::h_full)
391            .when(!is_rail, Styled::w_full);
392        let slot = if fraction < 1. {
393            slot.child(SlidingSlot {
394                content: content.into_any_element(),
395                available,
396                fraction,
397                is_rail,
398                direction,
399            })
400        } else {
401            slot.child(content)
402        };
403        if is_rail {
404            self.scaffold.rail(slot)
405        } else {
406            self.scaffold.bottom_bar(slot)
407        }
408    }
409}
410
411/// Measures the natural slot once and reserves its animated fraction. The
412/// same content is clipped and translated, preserving its layout and IDs.
413struct SlidingSlot {
414    content: AnyElement,
415    available: Size<Pixels>,
416    fraction: f32,
417    is_rail: bool,
418    direction: Direction,
419}
420
421impl IntoElement for SlidingSlot {
422    type Element = Self;
423
424    fn into_element(self) -> Self {
425        self
426    }
427}
428
429impl Element for SlidingSlot {
430    type RequestLayoutState = Size<Pixels>;
431    type PrepaintState = ();
432
433    fn id(&self) -> Option<ElementId> {
434        None
435    }
436
437    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
438        None
439    }
440
441    fn request_layout(
442        &mut self,
443        _: Option<&GlobalElementId>,
444        _: Option<&InspectorElementId>,
445        window: &mut Window,
446        cx: &mut App,
447    ) -> (LayoutId, Self::RequestLayoutState) {
448        let natural =
449            self.content
450                .layout_as_root(self.available.map(AvailableSpace::Definite), window, cx);
451        let size = if self.is_rail {
452            size((natural.width * self.fraction).into(), relative(1.).into())
453        } else {
454            size(relative(1.).into(), (natural.height * self.fraction).into())
455        };
456        (
457            window.request_layout(
458                Style {
459                    size,
460                    ..Style::default()
461                },
462                None,
463                cx,
464            ),
465            natural,
466        )
467    }
468
469    fn prepaint(
470        &mut self,
471        _: Option<&GlobalElementId>,
472        _: Option<&InspectorElementId>,
473        bounds: Bounds<Pixels>,
474        natural: &mut Self::RequestLayoutState,
475        window: &mut Window,
476        cx: &mut App,
477    ) {
478        let cross_fit = if self.is_rail {
479            size(self.available.width, bounds.size.height)
480        } else {
481            size(bounds.size.width, self.available.height)
482        };
483        let natural = if cross_fit != self.available {
484            self.content
485                .layout_as_root(cross_fit.map(AvailableSpace::Definite), window, cx)
486        } else {
487            *natural
488        };
489        let origin: Point<Pixels> = if self.is_rail && self.direction == Direction::Ltr {
490            point(bounds.right() - natural.width, bounds.top())
491        } else {
492            bounds.origin
493        };
494        window.with_content_mask(Some(ContentMask { bounds }), |window| {
495            self.content.prepaint_at(origin, window, cx);
496        });
497    }
498
499    fn paint(
500        &mut self,
501        _: Option<&GlobalElementId>,
502        _: Option<&InspectorElementId>,
503        bounds: Bounds<Pixels>,
504        _: &mut Self::RequestLayoutState,
505        _: &mut (),
506        window: &mut Window,
507        cx: &mut App,
508    ) {
509        window.with_content_mask(Some(ContentMask { bounds }), |window| {
510            self.content.paint(window, cx)
511        });
512    }
513}