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,
23 ShortBarMedium,
25 RailCollapsed,
27 RailExpanded,
29 None,
31}
32
33impl AdaptiveNavigationType {
34 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#[derive(Clone, Copy, Debug, PartialEq)]
50pub struct AdaptiveNavigationInfo {
51 pub available_size: Size<Pixels>,
53 pub width_class: WidthClass,
55 pub direction: Direction,
57}
58
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub enum AdaptiveNavigationVisibility {
62 #[default]
64 Shown,
65 Hidden,
67}
68
69impl AdaptiveNavigationVisibility {
70 fn fraction(self) -> f32 {
71 f32::from(self == Self::Shown)
72 }
73}
74
75pub 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 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 pub fn transition_duration(mut self, duration: Duration) -> Self {
104 self.duration = duration;
105 self
106 }
107
108 pub fn current_value(&self) -> AdaptiveNavigationVisibility {
110 self.current
111 }
112
113 pub fn target_value(&self) -> AdaptiveNavigationVisibility {
115 self.target
116 }
117
118 pub fn is_animating(&self) -> bool {
120 self.transition.is_animating()
121 }
122
123 pub fn progress(&self) -> f32 {
125 self.fraction
126 }
127
128 pub fn show(&mut self, cx: &mut Context<Self>) {
130 self.animate_to(AdaptiveNavigationVisibility::Shown, cx);
131 }
132
133 pub fn hide(&mut self, cx: &mut Context<Self>) {
135 self.animate_to(AdaptiveNavigationVisibility::Hidden, cx);
136 }
137
138 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 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#[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 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 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 pub fn navigation_type(self, kind: AdaptiveNavigationType) -> Self {
252 self.navigation_policy(move |_| kind)
253 }
254
255 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 pub fn state(mut self, state: &Entity<AdaptiveNavigationState>) -> Self {
266 self.state = Some(state.clone());
267 self
268 }
269
270 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 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 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 items_id = items.id().clone();
350 let is_rail = kind.is_rail();
351 let default = if is_rail {
352 let mode = if kind == AdaptiveNavigationType::RailExpanded {
353 RailMode::Expanded
354 } else {
355 RailMode::Collapsed
356 };
357 let rail = NavigationRail::new((items_id.clone(), "adaptive-rail"), items).mode(mode);
358 match self.rail {
359 Some(build) => build(kind, rail),
360 None => rail,
361 }
362 .into_any_element()
363 } else {
364 let layout = if kind == AdaptiveNavigationType::ShortBarMedium {
365 NavigationBarLayout::Horizontal
366 } else {
367 NavigationBarLayout::Vertical
368 };
369 let bar = NavigationBar::new(items).layout(layout);
370 match self.bar {
371 Some(build) => build(kind, bar),
372 None => bar,
373 }
374 .into_any_element()
375 };
376 let content = match self.content {
377 Some(build) => build(kind, default),
378 None => default,
379 };
380 let content = div()
381 .flex()
382 .flex_col()
383 .when(is_rail, |content| content.h_full().max_w(available.width))
384 .when(!is_rail, |content| content.w_full().max_h(available.height))
385 .child(content);
386 let slot = div()
387 .id((items_id, "adaptive-navigation-slot"))
388 .test_support()
389 .track_focus(&scope)
390 .flex_none()
391 .when(is_rail, Styled::h_full)
392 .when(!is_rail, Styled::w_full);
393 let slot = if fraction < 1. {
394 slot.child(SlidingSlot {
395 content: content.into_any_element(),
396 available,
397 fraction,
398 is_rail,
399 direction,
400 })
401 } else {
402 slot.child(content)
403 };
404 if is_rail {
405 self.scaffold.rail(slot)
406 } else {
407 self.scaffold.bottom_bar(slot)
408 }
409 }
410}
411
412struct SlidingSlot {
415 content: AnyElement,
416 available: Size<Pixels>,
417 fraction: f32,
418 is_rail: bool,
419 direction: Direction,
420}
421
422impl Element for SlidingSlot {
423 type RequestLayoutState = Size<Pixels>;
424 type PrepaintState = ();
425
426 fn id(&self) -> Option<ElementId> {
427 None
428 }
429
430 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
431 None
432 }
433
434 fn request_layout(
435 &mut self,
436 _: Option<&GlobalElementId>,
437 _: Option<&InspectorElementId>,
438 window: &mut Window,
439 cx: &mut App,
440 ) -> (LayoutId, Self::RequestLayoutState) {
441 let natural =
442 self.content
443 .layout_as_root(self.available.map(AvailableSpace::Definite), window, cx);
444 let size = if self.is_rail {
445 size((natural.width * self.fraction).into(), relative(1.).into())
446 } else {
447 size(relative(1.).into(), (natural.height * self.fraction).into())
448 };
449 (
450 window.request_layout(
451 Style {
452 size,
453 ..Style::default()
454 },
455 None,
456 cx,
457 ),
458 natural,
459 )
460 }
461
462 fn prepaint(
463 &mut self,
464 _: Option<&GlobalElementId>,
465 _: Option<&InspectorElementId>,
466 bounds: Bounds<Pixels>,
467 natural: &mut Self::RequestLayoutState,
468 window: &mut Window,
469 cx: &mut App,
470 ) {
471 let cross_fit = if self.is_rail {
472 size(self.available.width, bounds.size.height)
473 } else {
474 size(bounds.size.width, self.available.height)
475 };
476 let natural = if cross_fit != self.available {
477 self.content
478 .layout_as_root(cross_fit.map(AvailableSpace::Definite), window, cx)
479 } else {
480 *natural
481 };
482 let origin: Point<Pixels> = if self.is_rail && self.direction == Direction::Ltr {
483 point(bounds.right() - natural.width, bounds.top())
484 } else {
485 bounds.origin
486 };
487 window.with_content_mask(Some(ContentMask { bounds }), |window| {
488 self.content.prepaint_at(origin, window, cx);
489 });
490 }
491
492 fn paint(
493 &mut self,
494 _: Option<&GlobalElementId>,
495 _: Option<&InspectorElementId>,
496 bounds: Bounds<Pixels>,
497 _: &mut Self::RequestLayoutState,
498 _: &mut (),
499 window: &mut Window,
500 cx: &mut App,
501 ) {
502 window.with_content_mask(Some(ContentMask { bounds }), |window| {
503 self.content.paint(window, cx)
504 });
505 }
506}