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