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 if !running {
173 self.settle();
174 cx.notify();
175 } else if next != self.fraction {
176 self.fraction = next;
177 cx.notify();
178 }
179 }
180}
181
182type Policy = Box<dyn FnOnce(AdaptiveNavigationInfo) -> AdaptiveNavigationType>;
183type NavigationContent = Box<dyn FnOnce(AdaptiveNavigationType, AnyElement) -> AnyElement>;
184type Configure<T> = Box<dyn FnOnce(AdaptiveNavigationType, T) -> T>;
185
186#[derive(IntoElement)]
188pub struct AdaptiveNavigation {
189 scaffold: Scaffold,
190 items: NavigationItems,
191 width: Pixels,
192 height: Option<Pixels>,
193 policy: Option<Policy>,
194 state: Option<Entity<AdaptiveNavigationState>>,
195 content: Option<NavigationContent>,
196 bar: Option<Configure<NavigationBar>>,
197 rail: Option<Configure<NavigationRail>>,
198}
199
200impl AdaptiveNavigation {
201 pub fn new(scaffold: Scaffold, items: NavigationItems, available_width: Pixels) -> Self {
203 Self {
204 scaffold,
205 items,
206 width: available_width,
207 height: None,
208 policy: None,
209 state: None,
210 content: None,
211 bar: None,
212 rail: None,
213 }
214 }
215
216 pub fn available_size(mut self, size: Size<Pixels>) -> Self {
218 self.width = size.width;
219 self.height = Some(size.height);
220 self
221 }
222
223 pub fn navigation_type(self, kind: AdaptiveNavigationType) -> Self {
224 self.navigation_policy(move |_| kind)
225 }
226
227 pub fn navigation_policy(
228 mut self,
229 policy: impl FnOnce(AdaptiveNavigationInfo) -> AdaptiveNavigationType + 'static,
230 ) -> Self {
231 self.policy = Some(Box::new(policy));
232 self
233 }
234
235 pub fn state(mut self, state: &Entity<AdaptiveNavigationState>) -> Self {
236 self.state = Some(state.clone());
237 self
238 }
239
240 pub fn navigation_content<E: IntoElement>(
242 mut self,
243 build: impl FnOnce(AdaptiveNavigationType, AnyElement) -> E + 'static,
244 ) -> Self {
245 self.content = Some(Box::new(move |kind, default| {
246 build(kind, default).into_any_element()
247 }));
248 self
249 }
250
251 pub fn navigation_bar(
252 mut self,
253 build: impl FnOnce(AdaptiveNavigationType, NavigationBar) -> NavigationBar + 'static,
254 ) -> Self {
255 self.bar = Some(Box::new(build));
256 self
257 }
258
259 pub fn navigation_rail(
260 mut self,
261 build: impl FnOnce(AdaptiveNavigationType, NavigationRail) -> NavigationRail + 'static,
262 ) -> Self {
263 self.rail = Some(Box::new(build));
264 self
265 }
266}
267
268impl RenderOnce for AdaptiveNavigation {
269 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
270 let viewport = window.viewport_size();
271 let available = size(
272 length(self.width),
273 length(self.height.unwrap_or(viewport.height)),
274 );
275 let direction = current_material_theme(window, cx).layout.direction;
276 let info = AdaptiveNavigationInfo {
277 available_size: available,
278 width_class: WidthClass::from_width(available.width.into()),
279 direction,
280 };
281 let kind = match self.policy {
282 Some(policy) => policy(info),
283 None => AdaptiveNavigationType::for_width(available.width),
284 };
285 let (fraction, moving) = self.state.as_ref().map_or((1., false), |state| {
286 state.update(cx, |state, cx| {
287 state.sample(cx);
288 (state.progress(), state.is_animating())
289 })
290 });
291 if moving && window.is_visible() {
292 window.request_animation_frame();
293 }
294 let scope = window
295 .use_keyed_state(
296 (self.items.id().clone(), "adaptive-navigation-focus"),
297 cx,
298 |_, cx| cx.focus_handle().tab_stop(false),
299 )
300 .read(cx)
301 .clone();
302 let items = self.items.retain(window, cx).retain_roving_stop();
303 if kind == AdaptiveNavigationType::None || fraction <= 0. {
304 if scope.contains_focused(window, cx) {
305 let previous = window.focused(cx);
306 window.defer(cx, move |window, cx| {
307 if window.focused(cx) == previous {
308 window.focus_next(cx);
309 if window.focused(cx) == previous {
310 window.blur(cx);
311 }
312 }
313 });
314 }
315 return self.scaffold;
316 }
317 let is_rail = kind.is_rail();
318 let default = if is_rail {
319 let mode = if kind == AdaptiveNavigationType::RailExpanded {
320 RailMode::Expanded
321 } else {
322 RailMode::Collapsed
323 };
324 let rail = NavigationRail::new("adaptive-rail", items).mode(mode);
325 match self.rail {
326 Some(build) => build(kind, rail),
327 None => rail,
328 }
329 .into_any_element()
330 } else {
331 let layout = if kind == AdaptiveNavigationType::ShortBarMedium {
332 NavigationBarLayout::Horizontal
333 } else {
334 NavigationBarLayout::Vertical
335 };
336 let bar = NavigationBar::new(items).layout(layout);
337 match self.bar {
338 Some(build) => build(kind, bar),
339 None => bar,
340 }
341 .into_any_element()
342 };
343 let content = match self.content {
344 Some(build) => build(kind, default),
345 None => default,
346 };
347 let content = div()
348 .flex()
349 .flex_col()
350 .when(is_rail, |content| content.h_full().max_w(available.width))
351 .when(!is_rail, |content| content.w_full().max_h(available.height))
352 .child(content);
353 let slot = div()
354 .id("adaptive-navigation-slot")
355 .test_support()
356 .track_focus(&scope)
357 .flex_none()
358 .when(is_rail, Styled::h_full)
359 .when(!is_rail, Styled::w_full);
360 let slot = if fraction < 1. {
361 slot.child(SlidingSlot {
362 content: content.into_any_element(),
363 available,
364 fraction,
365 is_rail,
366 direction,
367 })
368 } else {
369 slot.child(content)
370 };
371 if is_rail {
372 self.scaffold.rail(slot)
373 } else {
374 self.scaffold.bottom_bar(slot)
375 }
376 }
377}
378
379struct SlidingSlot {
382 content: AnyElement,
383 available: Size<Pixels>,
384 fraction: f32,
385 is_rail: bool,
386 direction: Direction,
387}
388
389impl IntoElement for SlidingSlot {
390 type Element = Self;
391
392 fn into_element(self) -> Self {
393 self
394 }
395}
396
397impl Element for SlidingSlot {
398 type RequestLayoutState = ();
399 type PrepaintState = ();
400
401 fn id(&self) -> Option<ElementId> {
402 None
403 }
404
405 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
406 None
407 }
408
409 fn request_layout(
410 &mut self,
411 _: Option<&GlobalElementId>,
412 _: Option<&InspectorElementId>,
413 window: &mut Window,
414 cx: &mut App,
415 ) -> (LayoutId, ()) {
416 let natural =
417 self.content
418 .layout_as_root(self.available.map(AvailableSpace::Definite), window, cx);
419 let size = if self.is_rail {
420 size((natural.width * self.fraction).into(), relative(1.).into())
421 } else {
422 size(relative(1.).into(), (natural.height * self.fraction).into())
423 };
424 (
425 window.request_layout(
426 Style {
427 size,
428 ..Style::default()
429 },
430 None,
431 cx,
432 ),
433 (),
434 )
435 }
436
437 fn prepaint(
438 &mut self,
439 _: Option<&GlobalElementId>,
440 _: Option<&InspectorElementId>,
441 bounds: Bounds<Pixels>,
442 _: &mut (),
443 window: &mut Window,
444 cx: &mut App,
445 ) {
446 let cross_fit = if self.is_rail {
447 size(self.available.width, bounds.size.height)
448 } else {
449 size(bounds.size.width, self.available.height)
450 };
451 let natural =
452 self.content
453 .layout_as_root(cross_fit.map(AvailableSpace::Definite), window, cx);
454 let origin: Point<Pixels> = if self.is_rail && self.direction == Direction::Ltr {
455 point(bounds.right() - natural.width, bounds.top())
456 } else {
457 bounds.origin
458 };
459 window.with_content_mask(Some(ContentMask { bounds }), |window| {
460 self.content.prepaint_at(origin, window, cx);
461 });
462 }
463
464 fn paint(
465 &mut self,
466 _: Option<&GlobalElementId>,
467 _: Option<&InspectorElementId>,
468 bounds: Bounds<Pixels>,
469 _: &mut (),
470 _: &mut (),
471 window: &mut Window,
472 cx: &mut App,
473 ) {
474 window.with_content_mask(Some(ContentMask { bounds }), |window| {
475 self.content.paint(window, cx)
476 });
477 }
478}