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