1use std::{collections::HashMap, rc::Rc};
2
3use gpui::{
4 AnyElement, App, ElementId, Entity, Hsla, InteractiveElement, IntoElement, ParentElement,
5 Pixels, RenderOnce, SharedString, Styled, Window, div, prelude::FluentBuilder, px,
6};
7use gpui_base::TestSupportExt;
8use gpui_material_foundation::{Surface, animate, current_material_theme};
9use gpui_material_theme::{ColorRole, CornerRole, CornerShape, MotionKind, MotionSpeed, TypeRole};
10
11use crate::{
12 DialogCloseReason, DialogProperties, DialogState, Sheet, SheetColors, SheetEdge, SheetMargins,
13 SheetMode, SheetPlacement, Text,
14};
15
16use super::items::{NavigationItems, Presentation};
17
18mod state;
19pub use state::NavigationRailState;
20
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum RailMode {
24 #[default]
26 Collapsed,
27 Expanded,
29 Hidden,
31}
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum NavigationRailArrangement {
36 #[default]
38 Start,
39 Center,
41 End,
43 SpaceBetween,
45 SpaceAround,
47 SpaceEvenly,
49}
50
51#[derive(Clone, Copy, Debug, Default, PartialEq)]
53pub struct NavigationRailPadding {
54 pub start: Pixels,
56 pub end: Pixels,
58 pub top: Pixels,
60 pub bottom: Pixels,
62}
63
64impl NavigationRailPadding {
65 fn docked_default() -> Self {
66 Self {
67 start: px(4.),
68 end: px(4.),
69 top: px(4.),
70 bottom: px(8.),
71 }
72 }
73}
74
75#[derive(Clone, Copy, Debug, Default, PartialEq)]
77pub struct NavigationRailShapes {
78 pub collapsed: Option<CornerShape>,
80 pub expanded: Option<CornerShape>,
82 pub modal: Option<CornerShape>,
84}
85
86#[derive(Clone, Copy, Debug, Default, PartialEq)]
88pub struct NavigationRailColors {
89 pub container: Option<Hsla>,
91 pub content: Option<Hsla>,
93 pub modal_container: Option<Hsla>,
95 pub modal_content: Option<Hsla>,
97 pub scrim: Option<Hsla>,
99 pub scrim_opacity: Option<f32>,
101}
102
103#[derive(Clone, Copy, Debug, Default, PartialEq)]
105pub struct RailModalOptions {
106 pub properties: DialogProperties,
108 pub layer: usize,
110 pub placement: SheetPlacement,
112 pub margins: SheetMargins,
114 pub hide_on_collapse: bool,
116}
117
118#[derive(Clone, Copy, PartialEq)]
119pub(super) struct RailPresentation {
120 pub expanded: bool,
121 pub arrangement: NavigationRailArrangement,
122 pub spacing: Pixels,
123 pub content: Option<Hsla>,
124}
125
126type Destinations = Box<dyn FnOnce(RailMode) -> AnyElement>;
127type DismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
128type Closed = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
129
130#[derive(IntoElement)]
132pub struct NavigationRail {
133 id: ElementId,
134 items: NavigationItems,
135 mode: RailMode,
136 state: Option<Entity<NavigationRailState>>,
137 title: Option<SharedString>,
138 header: Option<AnyElement>,
139 fab: Option<AnyElement>,
140 expanded_width: Pixels,
141 modal: Option<Entity<DialogState>>,
142 modal_options: RailModalOptions,
143 destination_content: Option<Destinations>,
144 dividers: HashMap<SharedString, AnyElement>,
145 arrangement: NavigationRailArrangement,
146 destination_spacing: Pixels,
147 content_padding: Option<NavigationRailPadding>,
148 header_spacing: Pixels,
149 expanded_header_top_padding: Pixels,
150 shapes: NavigationRailShapes,
151 colors: NavigationRailColors,
152 dismiss: Option<DismissRequest>,
153 closed: Option<Closed>,
154}
155
156impl NavigationRail {
157 pub fn new(id: impl Into<ElementId>, items: NavigationItems) -> Self {
159 Self {
160 id: id.into(),
161 items,
162 mode: RailMode::Collapsed,
163 state: None,
164 title: None,
165 header: None,
166 fab: None,
167 expanded_width: px(240.),
168 modal: None,
169 modal_options: RailModalOptions::default(),
170 destination_content: None,
171 dividers: HashMap::new(),
172 arrangement: NavigationRailArrangement::default(),
173 destination_spacing: px(4.),
174 content_padding: None,
175 header_spacing: px(4.),
176 expanded_header_top_padding: px(0.),
177 shapes: NavigationRailShapes::default(),
178 colors: NavigationRailColors::default(),
179 dismiss: None,
180 closed: None,
181 }
182 }
183
184 pub fn mode(mut self, mode: RailMode) -> Self {
186 self.mode = mode;
187 self
188 }
189
190 pub fn state(mut self, state: &Entity<NavigationRailState>) -> Self {
192 self.state = Some(state.clone());
193 self
194 }
195
196 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
198 self.title = Some(title.into());
199 self
200 }
201
202 pub fn header(mut self, header: impl IntoElement) -> Self {
204 self.header = Some(header.into_any_element());
205 self
206 }
207
208 pub fn fab(mut self, fab: impl IntoElement) -> Self {
210 self.fab = Some(fab.into_any_element());
211 self
212 }
213
214 pub fn expanded_width(mut self, width: Pixels) -> Self {
216 if f32::from(width).is_finite() {
217 self.expanded_width = width.clamp(px(220.), px(360.));
218 }
219 self
220 }
221
222 pub fn destination_content<E: IntoElement + 'static>(
224 mut self,
225 build: impl FnOnce(RailMode) -> E + 'static,
226 ) -> Self {
227 self.destination_content = Some(Box::new(move |mode| build(mode).into_any_element()));
228 self
229 }
230
231 pub fn divider_after(
233 mut self,
234 destination: impl Into<SharedString>,
235 divider: impl IntoElement,
236 ) -> Self {
237 self.dividers
238 .insert(destination.into(), divider.into_any_element());
239 self
240 }
241
242 pub fn arrangement(mut self, arrangement: NavigationRailArrangement) -> Self {
244 self.arrangement = arrangement;
245 self
246 }
247
248 pub fn destination_spacing(mut self, spacing: Pixels) -> Self {
250 self.destination_spacing = length(spacing);
251 self
252 }
253
254 pub fn content_padding(mut self, padding: NavigationRailPadding) -> Self {
256 self.content_padding = Some(padding);
257 self
258 }
259
260 pub fn header_spacing(mut self, spacing: Pixels) -> Self {
262 self.header_spacing = length(spacing);
263 self
264 }
265
266 pub fn expanded_header_top_padding(mut self, padding: Pixels) -> Self {
268 self.expanded_header_top_padding = length(padding);
269 self
270 }
271
272 pub fn shapes(mut self, shapes: NavigationRailShapes) -> Self {
274 self.shapes = shapes;
275 self
276 }
277
278 pub fn colors(mut self, colors: NavigationRailColors) -> Self {
280 self.colors = colors;
281 self
282 }
283
284 pub fn modal(mut self, state: &Entity<DialogState>) -> Self {
286 self.modal = Some(state.clone());
287 self
288 }
289
290 pub fn modal_options(mut self, options: RailModalOptions) -> Self {
292 self.modal_options = options;
293 self
294 }
295
296 pub fn on_dismiss_request(
298 mut self,
299 callback: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
300 ) -> Self {
301 self.dismiss = Some(Rc::new(callback));
302 self
303 }
304
305 pub fn on_modal_close(
307 mut self,
308 callback: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
309 ) -> Self {
310 self.closed = Some(Rc::new(callback));
311 self
312 }
313
314 fn docked(&self, window: &mut Window, cx: &mut App) -> DockedFrame {
315 let viewport = length(window.viewport_size().width);
316 let collapse_width = if self.modal.is_some() && self.modal_options.hide_on_collapse {
317 px(0.)
318 } else {
319 px(96.).min(viewport)
320 };
321 let expand_width = self.expanded_width.min(viewport);
322 if let Some(state) = &self.state {
323 let (weights, target, moving) = state.update(cx, |state, cx| {
324 let weights = state.sample(cx);
325 (weights, state.target_value(), state.is_animating())
326 });
327 if moving && window.is_visible() {
328 window.request_animation_frame();
329 }
330 let width = collapse_width * weights.collapsed + expand_width * weights.expanded;
331 let mode = if target == RailMode::Hidden && moving {
332 if weights.expanded >= weights.collapsed {
333 RailMode::Expanded
334 } else {
335 RailMode::Collapsed
336 }
337 } else {
338 target
339 };
340 let size = weights.expanded + weights.collapsed;
341 DockedFrame {
342 width,
343 mode,
344 expansion: if size > 0. {
345 weights.expanded / size
346 } else {
347 0.
348 },
349 }
350 } else {
351 let theme = current_material_theme(window, cx);
352 let motion = theme.motion.spec(
353 MotionKind::Spatial,
354 MotionSpeed::Default,
355 cx.reduce_motion(),
356 );
357 let target = match self.mode {
358 RailMode::Collapsed => collapse_width,
359 RailMode::Expanded => expand_width,
360 RailMode::Hidden => px(0.),
361 };
362 let width = px(animate(
363 (self.id.clone(), "rail-width"),
364 target.into(),
365 motion,
366 window,
367 cx,
368 ))
369 .clamp(px(0.), viewport);
370 let span = expand_width - collapse_width;
371 let expansion = if span > px(0.) {
372 ((width - collapse_width) / span).clamp(0., 1.)
373 } else {
374 f32::from(self.mode == RailMode::Expanded)
375 };
376 DockedFrame {
377 width,
378 mode: self.mode,
379 expansion,
380 }
381 }
382 }
383}
384
385struct DockedFrame {
386 width: Pixels,
387 mode: RailMode,
388 expansion: f32,
389}
390
391impl RenderOnce for NavigationRail {
392 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
393 let frame = self.docked(window, cx);
394 let modal = self.modal.as_ref().and_then(|state| {
395 let open = state.read(cx).is_open();
396 let id = (self.id.clone(), "rail-modal").into();
397 let presence = crate::motion::presence(&id, open, 240, window, cx);
398 presence.should_render().then(|| (state.clone(), presence))
399 });
400 let items = self.items.retain(window, cx);
402 let scope = window
403 .use_keyed_state((self.id.clone(), "rail-docked-focus"), cx, |_, cx| {
404 cx.focus_handle().tab_stop(false)
405 })
406 .read(cx)
407 .clone();
408 let frame_id = (self.id.clone(), "rail-frame");
409 let docked = div()
410 .id(frame_id)
411 .test_support()
412 .w(frame.width)
413 .h_full()
414 .flex_none()
415 .overflow_hidden();
416 let modal_visible = modal.is_some();
417 if !modal_visible && (frame.mode == RailMode::Hidden || frame.width <= px(0.)) {
418 if scope.contains_focused(window, cx) {
419 let focus = window.focused(cx);
420 window.defer(cx, move |window, cx| {
421 if window
422 .focused(cx)
423 .is_none_or(|current| Some(current) == focus)
424 {
425 window.focus_next(cx);
426 }
427 });
428 }
429 return docked.into_any_element();
430 }
431 let mode = if modal_visible {
432 RailMode::Expanded
433 } else {
434 frame.mode
435 };
436 let expanded = mode == RailMode::Expanded;
437 let title = self.title.unwrap_or_else(|| "Navigation".into());
438 let theme = current_material_theme(window, cx);
439 let viewport = window.viewport_size();
440 let layout = theme.layout;
441 let colors = self.colors;
442 let content_color = if modal_visible {
443 colors.modal_content
444 } else {
445 colors.content
446 };
447 let padding = self.content_padding.unwrap_or_else(|| {
448 if modal_visible {
449 NavigationRailPadding::default()
450 } else {
451 NavigationRailPadding::docked_default()
452 }
453 });
454 let (left, right) = layout.horizontal(length(padding.start), length(padding.end));
455 let destinations = match self.destination_content {
456 Some(build) => div()
457 .id("custom-destinations")
458 .flex_1()
459 .min_h_0()
460 .child(build(mode))
461 .into_any_element(),
462 None => items.with_rail_dividers(self.dividers).render_row(
463 Presentation::Rail(RailPresentation {
464 expanded,
465 arrangement: self.arrangement,
466 spacing: self.destination_spacing,
467 content: content_color,
468 }),
469 window,
470 cx,
471 ),
472 };
473 let panel = div()
474 .id("rail-content")
475 .test_support()
476 .flex()
477 .flex_col()
478 .h_full()
479 .min_h_0()
480 .gap(self.header_spacing)
481 .pt(length(padding.top))
482 .pb(length(padding.bottom))
483 .pl(left)
484 .pr(right)
485 .when_some(content_color, Styled::text_color)
486 .children(self.header.map(|header| {
487 div()
488 .id("rail-header")
489 .test_support()
490 .flex_none()
491 .pt(if expanded {
492 self.expanded_header_top_padding
493 } else {
494 px(0.)
495 })
496 .child(header)
497 }))
498 .children(
499 self.fab
500 .map(|fab| div().id("rail-fab").flex_none().child(fab)),
501 )
502 .when(expanded && !modal_visible, |panel| {
503 panel.child(
504 div().px(px(12.)).child(
505 Text::new(title.clone())
506 .id("rail-title")
507 .role(TypeRole::TitleMedium)
508 .wrap(),
509 ),
510 )
511 })
512 .child(destinations);
513
514 let shape = docked_shape(self.shapes, frame.expansion, frame.width, viewport.height);
515 let surface = Surface::new(ColorRole::Surface)
516 .shape(shape)
517 .when_some(colors.container, Surface::container_color)
518 .size_full()
519 .overflow_hidden()
520 .when_some(content_color, Surface::content_color);
521 if let Some((state, presence)) = modal {
522 let options = self.modal_options;
523 return docked
524 .child(
525 Surface::new(ColorRole::Surface)
526 .shape(shape)
527 .size_full()
528 .when_some(colors.container, Surface::container_color),
529 )
530 .child(
531 Sheet::new(self.id, &state, title, panel)
532 .mode(SheetMode::Modal)
533 .edge(SheetEdge::Start)
534 .extent(self.expanded_width)
535 .placement(options.placement)
536 .margins(options.margins)
537 .layer(options.layer)
538 .properties(options.properties)
539 .sampled_presence(presence)
540 .colors(SheetColors {
541 container: colors.modal_container,
542 content: colors.modal_content,
543 scrim: colors.scrim,
544 ..Default::default()
545 })
546 .when_some(colors.scrim_opacity, Sheet::scrim_opacity)
547 .when_some(self.shapes.modal.or(self.shapes.expanded), Sheet::shape)
548 .when_some(self.dismiss, |sheet, callback| {
549 sheet.on_dismiss_request(move |reason, window, cx| {
550 callback(reason, window, cx)
551 })
552 })
553 .when_some(self.closed, |sheet, callback| {
554 sheet.on_close(move |reason, window, cx| callback(reason, window, cx))
555 }),
556 )
557 .into_any_element();
558 }
559
560 docked
561 .track_focus(&scope)
562 .child(surface.child(panel))
563 .into_any_element()
564 }
565}
566
567fn docked_shape(
568 shapes: NavigationRailShapes,
569 expanded: f32,
570 width: Pixels,
571 height: Pixels,
572) -> CornerShape {
573 let collapsed = shapes.collapsed.unwrap_or_else(|| CornerRole::None.shape());
574 let target = shapes.expanded.unwrap_or_else(|| CornerRole::None.shape());
575 if expanded <= 0. || collapsed == target {
576 return collapsed;
577 }
578 if expanded >= 1. {
579 return target;
580 }
581 let resolve = |shape| match shape {
582 CornerShape::Radii(radii) => radii,
583 CornerShape::Full => [f32::from(width.min(height)) * 0.5; 4],
584 };
585 let a = resolve(collapsed);
586 let b = resolve(target);
587 CornerShape::Radii(std::array::from_fn(|i| a[i] + (b[i] - a[i]) * expanded))
588}
589
590pub(super) fn length(value: Pixels) -> Pixels {
591 if f32::from(value).is_finite() {
592 value.max(px(0.))
593 } else {
594 px(0.)
595 }
596}