1use crate::{
2 ActiveTheme, Collapsible, Icon, IconName, Side, Sizable, StyledExt,
3 button::{Button, ButtonVariants},
4 h_flex,
5 scroll::ScrollableElement,
6 v_flex,
7};
8use gpui::{
9 AbsoluteLength, AnyElement, App, ClickEvent, DefiniteLength, EdgesRefinement, ElementId,
10 InteractiveElement as _, IntoElement, Length, ListAlignment, ListState, ParentElement, Pixels,
11 RenderOnce, SharedString, StyleRefinement, Styled, Window, div, list, prelude::FluentBuilder,
12 px,
13};
14use gpui_base::LogicalStyledExt as _;
15use std::{rc::Rc, time::Duration};
16
17use crate::animation::{EffectTransition, ease_in_out_cubic};
18
19mod footer;
20mod group;
21mod header;
22mod menu;
23pub use footer::*;
24pub use group::*;
25pub use header::*;
26pub use menu::*;
27
28const DEFAULT_WIDTH: Pixels = px(255.);
29const COLLAPSED_WIDTH: Pixels = px(48.);
30const SIDEBAR_TRANSITION_DURATION: Duration = Duration::from_millis(200);
31
32fn physical_side(side: Side, cx: &App) -> Side {
42 match (side, gpui_base::LayoutDirection::global(cx)) {
43 (Side::Left, gpui_base::LayoutDirection::Rtl) => Side::Right,
44 (Side::Right, gpui_base::LayoutDirection::Rtl) => Side::Left,
45 (side, _) => side,
46 }
47}
48
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub enum SidebarCollapsible {
51 #[default]
53 Icon,
54 Offcanvas,
56 None,
58}
59
60impl From<bool> for SidebarCollapsible {
61 fn from(collapsible: bool) -> Self {
62 if collapsible { Self::Icon } else { Self::None }
63 }
64}
65
66#[derive(Clone, Copy, Debug, PartialEq)]
67enum SidebarWrapperLayout {
68 None,
69 Static { width: Pixels },
70 Animated { target_width: Pixels },
71}
72
73#[derive(Clone, Copy, Debug, PartialEq)]
74struct SidebarLayout {
75 icon_collapsed: bool,
76 offcanvas_collapsed: bool,
77 align_child_to_end: bool,
78 wrapper: SidebarWrapperLayout,
79}
80
81impl SidebarLayout {
82 fn new(
83 collapsible: SidebarCollapsible,
84 collapsed: bool,
85 expanded_width: Option<Pixels>,
86 side: Side,
87 ) -> Self {
88 let collapsed = collapsed && collapsible != SidebarCollapsible::None;
89 let wrapper = match collapsible {
90 SidebarCollapsible::None => SidebarWrapperLayout::None,
91 SidebarCollapsible::Icon => match expanded_width {
92 Some(expanded_width) => SidebarWrapperLayout::Animated {
93 target_width: if collapsed {
94 COLLAPSED_WIDTH
95 } else {
96 expanded_width
97 },
98 },
99 None => SidebarWrapperLayout::None,
100 },
101 SidebarCollapsible::Offcanvas => match (expanded_width, collapsed) {
102 (Some(_), true) => SidebarWrapperLayout::Animated {
103 target_width: px(0.),
104 },
105 (Some(expanded_width), false) => SidebarWrapperLayout::Animated {
106 target_width: expanded_width,
107 },
108 (None, true) => SidebarWrapperLayout::Static { width: px(0.) },
109 (None, false) => SidebarWrapperLayout::None,
110 },
111 };
112 let align_child_to_end = match collapsible {
113 SidebarCollapsible::Offcanvas => side.is_left(),
114 _ => side.is_right(),
115 };
116
117 Self {
118 icon_collapsed: collapsed && collapsible == SidebarCollapsible::Icon,
119 offcanvas_collapsed: collapsed && collapsible == SidebarCollapsible::Offcanvas,
120 align_child_to_end,
121 wrapper,
122 }
123 }
124}
125
126#[derive(Clone, Copy, Debug, PartialEq)]
127struct SidebarAnimationState {
128 from_width: Pixels,
129 target_width: Pixels,
130 render_child: bool,
131 hide_scheduled: bool,
132 hide_request: u64,
133}
134
135impl SidebarAnimationState {
136 fn new(target_width: Pixels, render_child: bool) -> Self {
137 Self {
138 from_width: target_width,
139 target_width,
140 render_child,
141 hide_scheduled: false,
142 hide_request: 0,
143 }
144 }
145
146 fn needs_update(&self, target_width: Pixels, offcanvas_collapsed: bool) -> bool {
147 let child_state_changed = if offcanvas_collapsed {
148 self.render_child && !self.hide_scheduled
149 } else {
150 !self.render_child || self.hide_scheduled
151 };
152
153 self.target_width != target_width || child_state_changed
154 }
155
156 fn update_target(&mut self, target_width: Pixels, offcanvas_collapsed: bool) -> Option<u64> {
157 if self.target_width != target_width {
158 self.from_width = self.target_width;
159 self.target_width = target_width;
160 }
161
162 if offcanvas_collapsed {
163 if self.render_child && !self.hide_scheduled {
164 self.hide_scheduled = true;
165 self.hide_request = self.hide_request.wrapping_add(1);
166 Some(self.hide_request)
167 } else {
168 None
169 }
170 } else {
171 self.render_child = true;
172 if self.hide_scheduled {
173 self.hide_request = self.hide_request.wrapping_add(1);
174 }
175 self.hide_scheduled = false;
176 None
177 }
178 }
179
180 fn finish_hide(&mut self, request: u64) -> bool {
181 if self.render_child
182 && self.hide_scheduled
183 && self.hide_request == request
184 && self.target_width == px(0.)
185 {
186 self.render_child = false;
187 self.hide_scheduled = false;
188 true
189 } else {
190 false
191 }
192 }
193}
194
195fn sidebar_wrapper(
196 id: impl Into<ElementId>,
197 align_child_to_end: bool,
198) -> impl ParentElement + IntoElement + Styled {
199 div()
200 .id(id)
201 .flex()
202 .h_full()
203 .flex_shrink_0()
204 .overflow_hidden()
205 .when(align_child_to_end, |this| this.justify_end())
206}
207
208fn sidebar_expanded_width(style: &StyleRefinement) -> Option<Pixels> {
209 match style.size.width {
210 Some(Length::Definite(DefiniteLength::Absolute(AbsoluteLength::Pixels(px)))) => Some(px),
211 Some(_) => None,
212 None => Some(DEFAULT_WIDTH),
213 }
214}
215
216fn sidebar_animation_id(id: &ElementId, from: Pixels, to: Pixels) -> ElementId {
217 ElementId::NamedInteger(
218 format!("{id}-anim-w").into(),
219 (from.as_f32().to_bits() as u64) << 32 | to.as_f32().to_bits() as u64,
220 )
221}
222
223pub trait SidebarItem: Collapsible + Clone {
224 fn render(
225 self,
226 id: impl Into<ElementId>,
227 window: &mut Window,
228 cx: &mut App,
229 ) -> impl IntoElement;
230}
231
232#[derive(IntoElement)]
234pub struct Sidebar<E: SidebarItem + 'static> {
235 id: ElementId,
236 style: StyleRefinement,
237 content: Vec<E>,
238 header: Option<AnyElement>,
240 footer: Option<AnyElement>,
242 side: Side,
244 collapsible: SidebarCollapsible,
245 collapsed: bool,
246}
247
248impl<E: SidebarItem> Sidebar<E> {
249 pub fn new(id: impl Into<ElementId>) -> Self {
251 Self {
252 id: id.into(),
253 style: StyleRefinement::default(),
254 content: vec![],
255 header: None,
256 footer: None,
257 side: Side::Left,
258 collapsible: SidebarCollapsible::Icon,
259 collapsed: false,
260 }
261 }
262
263 pub fn side(mut self, side: Side) -> Self {
267 self.side = side;
268 self
269 }
270
271 pub fn collapsible(mut self, collapsible: impl Into<SidebarCollapsible>) -> Self {
277 self.collapsible = collapsible.into();
278 self
279 }
280
281 pub fn collapsed(mut self, collapsed: bool) -> Self {
283 self.collapsed = collapsed;
284 self
285 }
286
287 pub fn header(mut self, header: impl IntoElement) -> Self {
289 self.header = Some(header.into_any_element());
290 self
291 }
292
293 pub fn footer(mut self, footer: impl IntoElement) -> Self {
295 self.footer = Some(footer.into_any_element());
296 self
297 }
298
299 pub fn child(mut self, child: E) -> Self {
301 self.content.push(child);
302 self
303 }
304
305 pub fn children(mut self, children: impl IntoIterator<Item = E>) -> Self {
307 self.content.extend(children);
308 self
309 }
310}
311
312#[derive(IntoElement)]
314pub struct SidebarToggleButton {
315 btn: Button,
316 collapsed: bool,
317 side: Side,
318 on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
319}
320
321impl SidebarToggleButton {
322 pub fn new() -> Self {
324 Self {
325 btn: Button::new("collapse").ghost().small(),
326 collapsed: false,
327 side: Side::Left,
328 on_click: None,
329 }
330 }
331
332 pub fn side(mut self, side: Side) -> Self {
336 self.side = side;
337 self
338 }
339
340 pub fn collapsed(mut self, collapsed: bool) -> Self {
342 self.collapsed = collapsed;
343 self
344 }
345
346 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
351 self.btn = self.btn.accessibility_label(label);
352 self
353 }
354
355 pub fn on_click(
357 mut self,
358 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
359 ) -> Self {
360 self.on_click = Some(Rc::new(on_click));
361 self
362 }
363}
364
365impl RenderOnce for SidebarToggleButton {
366 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
367 let collapsed = self.collapsed;
368 let on_click = self.on_click.clone();
369 let side = physical_side(self.side, cx);
370
371 let icon = if collapsed {
372 if side.is_left() {
373 IconName::PanelLeftOpen
374 } else {
375 IconName::PanelRightOpen
376 }
377 } else {
378 if side.is_left() {
379 IconName::PanelLeftClose
380 } else {
381 IconName::PanelRightClose
382 }
383 };
384
385 self.btn
386 .when_some(on_click, |this, on_click| {
387 this.on_click(move |ev, window, cx| {
388 on_click(ev, window, cx);
389 })
390 })
391 .icon(Icon::new(icon).size_4())
392 }
393}
394
395impl<E: SidebarItem> Styled for Sidebar<E> {
396 fn style(&mut self) -> &mut StyleRefinement {
397 &mut self.style
398 }
399}
400
401impl<E: SidebarItem> RenderOnce for Sidebar<E> {
402 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
403 self.style.padding = EdgesRefinement::default();
404
405 let id = self.id;
406 let content_len = self.content.len();
407 let overdraw = px(window.viewport_size().height.as_f32() * 0.3);
408 let list_state = window
409 .use_keyed_state(
410 SharedString::from(format!("{}-list-state", id)),
411 cx,
412 |_, _| ListState::new(content_len, ListAlignment::Top, overdraw),
413 )
414 .read(cx)
415 .clone();
416 if list_state.item_count() != content_len {
417 list_state.reset(content_len);
418 }
419
420 let expanded_width = sidebar_expanded_width(&self.style);
423 let side = physical_side(self.side, cx);
424 let layout = SidebarLayout::new(self.collapsible, self.collapsed, expanded_width, side);
425
426 let sidebar = v_flex()
430 .id(id.clone())
431 .flex_shrink_0()
432 .h_full()
433 .overflow_hidden()
434 .relative()
435 .bg(cx.theme().tokens.sidebar)
436 .text_color(cx.theme().sidebar_foreground)
437 .border_color(cx.theme().sidebar_border)
438 .map(|this| match side {
439 Side::Left => this.border_r_1(),
440 Side::Right => this.border_l_1(),
441 })
442 .when(self.style.size.width.is_none(), |this| {
443 this.w(DEFAULT_WIDTH)
444 })
445 .refine_style(&self.style)
446 .when(layout.icon_collapsed, |this| {
447 this.w(COLLAPSED_WIDTH).gap_2()
448 })
449 .when_some(self.header.take(), |this, header| {
450 this.child(
451 h_flex()
452 .flex_row_dir(cx)
453 .id("header")
454 .pt_3()
455 .px_3()
456 .gap_2()
457 .when(layout.icon_collapsed, |this| this.pt_2().px_2())
458 .child(header),
459 )
460 })
461 .child(
462 v_flex().id("content").flex_1().min_h_0().child(
463 v_flex()
464 .id("inner")
465 .size_full()
466 .px_3()
467 .gap_y_3()
468 .when(layout.icon_collapsed, |this| this.p_2())
469 .child(gpui_base::ScrollBounce::new(
470 "bounce",
471 &list_state,
472 list(list_state.clone(), {
473 move |ix, window, cx| {
474 let group = self.content.get(ix).cloned();
475 let is_first = ix == 0;
476 let is_last =
477 content_len > 0 && ix == content_len.saturating_sub(1);
478 div()
479 .id(ix)
480 .when_some(group, |this, group| {
481 this.child(
482 group
483 .collapsed(layout.icon_collapsed)
484 .render(ix, window, cx)
485 .into_any_element(),
486 )
487 })
488 .when(is_first, |this| this.pt_3())
489 .when(is_last, |this| this.pb_3())
490 .into_any_element()
491 }
492 })
493 .size_full(),
494 ))
495 .vertical_scrollbar(&list_state),
496 ),
497 )
498 .when_some(self.footer.take(), |this, footer| {
499 this.child(
500 h_flex()
501 .flex_row_dir(cx)
502 .id("footer")
503 .pb_3()
504 .px_3()
505 .gap_2()
506 .when(layout.icon_collapsed, |this| this.pt_2().px_2())
507 .child(footer),
508 )
509 });
510
511 let target_width = match layout.wrapper {
512 SidebarWrapperLayout::None => return sidebar.into_any_element(),
513 SidebarWrapperLayout::Static { width } => {
514 return sidebar_wrapper(format!("{}-anim", id), layout.align_child_to_end)
515 .w(width)
516 .when(!layout.offcanvas_collapsed, |this| this.child(sidebar))
517 .into_any_element();
518 }
519 SidebarWrapperLayout::Animated { target_width } => target_width,
520 };
521
522 let animation_state = window.use_keyed_state(format!("{}-anim-w", id), cx, |_, _| {
530 SidebarAnimationState::new(target_width, !layout.offcanvas_collapsed)
531 });
532
533 let hide_request = if animation_state
534 .read(cx)
535 .needs_update(target_width, layout.offcanvas_collapsed)
536 {
537 animation_state.update(cx, |state, _| {
538 state.update_target(target_width, layout.offcanvas_collapsed)
539 })
540 } else {
541 None
542 };
543 if let Some(hide_request) = hide_request {
544 cx.spawn({
545 let animation_state = animation_state.clone();
546 async move |cx| {
547 cx.background_executor()
548 .timer(SIDEBAR_TRANSITION_DURATION)
549 .await;
550 _ = animation_state.update(cx, |state, cx| {
551 if state.finish_hide(hide_request) {
552 cx.notify();
553 }
554 });
555 }
556 })
557 .detach();
558 }
559 let animation_state = *animation_state.read(cx);
560 let from_w = animation_state.from_width;
561 let to_w = animation_state.target_width;
562
563 let wrapper = sidebar_wrapper(format!("{}-anim", id), layout.align_child_to_end)
564 .when(animation_state.render_child, |this| this.child(sidebar));
565
566 EffectTransition::new(SIDEBAR_TRANSITION_DURATION)
567 .ease(ease_in_out_cubic)
568 .width(from_w, to_w)
569 .apply(wrapper, sidebar_animation_id(&id, from_w, to_w))
570 .into_any_element()
571 }
572}
573
574#[cfg(test)]
575mod tests {
576 use super::*;
577
578 fn layout(
579 collapsible: SidebarCollapsible,
580 collapsed: bool,
581 expanded_width: Option<Pixels>,
582 side: Side,
583 ) -> SidebarLayout {
584 SidebarLayout::new(collapsible, collapsed, expanded_width, side)
585 }
586
587 #[test]
588 fn bool_collapsible_should_remain_backward_compatible() {
589 assert_eq!(SidebarCollapsible::from(true), SidebarCollapsible::Icon);
590 assert_eq!(SidebarCollapsible::from(false), SidebarCollapsible::None);
591 }
592
593 #[test]
594 fn icon_collapsed_should_use_icon_width_and_icon_rendering() {
595 let layout = layout(SidebarCollapsible::Icon, true, Some(px(240.)), Side::Left);
596
597 assert!(layout.icon_collapsed);
598 assert!(!layout.offcanvas_collapsed);
599 assert!(!layout.align_child_to_end);
600 assert_eq!(
601 layout.wrapper,
602 SidebarWrapperLayout::Animated {
603 target_width: COLLAPSED_WIDTH,
604 }
605 );
606 }
607
608 #[test]
609 fn icon_expanded_should_use_expanded_width() {
610 let layout = layout(SidebarCollapsible::Icon, false, Some(px(240.)), Side::Left);
611
612 assert!(!layout.icon_collapsed);
613 assert!(!layout.offcanvas_collapsed);
614 assert_eq!(
615 layout.wrapper,
616 SidebarWrapperLayout::Animated {
617 target_width: px(240.),
618 }
619 );
620 }
621
622 #[test]
623 fn icon_expanded_with_non_pixel_width_should_keep_original_layout() {
624 let layout = layout(SidebarCollapsible::Icon, false, None, Side::Left);
625
626 assert!(!layout.icon_collapsed);
627 assert!(!layout.offcanvas_collapsed);
628 assert_eq!(layout.wrapper, SidebarWrapperLayout::None);
629 }
630
631 #[test]
632 fn none_should_ignore_collapsed_state() {
633 let layout = layout(SidebarCollapsible::None, true, Some(px(240.)), Side::Right);
634
635 assert!(!layout.icon_collapsed);
636 assert!(!layout.offcanvas_collapsed);
637 assert!(layout.align_child_to_end);
638 assert_eq!(layout.wrapper, SidebarWrapperLayout::None);
639 }
640
641 #[test]
642 fn offcanvas_collapsed_with_pixel_width_should_animate_to_zero() {
643 let layout = layout(
644 SidebarCollapsible::Offcanvas,
645 true,
646 Some(px(240.)),
647 Side::Left,
648 );
649
650 assert!(!layout.icon_collapsed);
651 assert!(layout.offcanvas_collapsed);
652 assert!(layout.align_child_to_end);
653 assert_eq!(
654 layout.wrapper,
655 SidebarWrapperLayout::Animated {
656 target_width: px(0.),
657 }
658 );
659 }
660
661 #[test]
662 fn offcanvas_expanded_with_pixel_width_should_use_expanded_width() {
663 let layout = layout(
664 SidebarCollapsible::Offcanvas,
665 false,
666 Some(px(240.)),
667 Side::Left,
668 );
669
670 assert!(!layout.icon_collapsed);
671 assert!(!layout.offcanvas_collapsed);
672 assert_eq!(
673 layout.wrapper,
674 SidebarWrapperLayout::Animated {
675 target_width: px(240.),
676 }
677 );
678 }
679
680 #[test]
681 fn offcanvas_collapsed_with_non_pixel_width_should_statically_release_layout() {
682 let layout = layout(SidebarCollapsible::Offcanvas, true, None, Side::Left);
683
684 assert!(!layout.icon_collapsed);
685 assert!(layout.offcanvas_collapsed);
686 assert_eq!(
687 layout.wrapper,
688 SidebarWrapperLayout::Static { width: px(0.) }
689 );
690 }
691
692 #[test]
693 fn offcanvas_expanded_with_non_pixel_width_should_keep_original_layout() {
694 let layout = layout(SidebarCollapsible::Offcanvas, false, None, Side::Left);
695
696 assert!(!layout.icon_collapsed);
697 assert!(!layout.offcanvas_collapsed);
698 assert_eq!(layout.wrapper, SidebarWrapperLayout::None);
699 }
700
701 #[test]
702 fn offcanvas_should_anchor_child_toward_the_content_edge() {
703 let left = layout(
704 SidebarCollapsible::Offcanvas,
705 true,
706 Some(px(240.)),
707 Side::Left,
708 );
709 let right = layout(
710 SidebarCollapsible::Offcanvas,
711 true,
712 Some(px(240.)),
713 Side::Right,
714 );
715
716 assert!(left.align_child_to_end);
717 assert!(!right.align_child_to_end);
718 }
719
720 #[test]
721 fn animation_id_should_be_scoped_to_sidebar_id() {
722 let from = px(240.);
723 let to = COLLAPSED_WIDTH;
724
725 assert_ne!(
726 sidebar_animation_id(&ElementId::Name("sidebar-a".into()), from, to),
727 sidebar_animation_id(&ElementId::Name("sidebar-b".into()), from, to)
728 );
729 }
730
731 #[test]
732 fn animation_state_should_keep_child_until_offcanvas_hide_finishes() {
733 let mut state = SidebarAnimationState::new(px(240.), true);
734
735 let request = state.update_target(px(0.), true);
736
737 assert_eq!(request, Some(1));
738 assert_eq!(state.from_width, px(240.));
739 assert_eq!(state.target_width, px(0.));
740 assert!(state.render_child);
741
742 assert!(state.finish_hide(1));
743
744 assert!(!state.render_child);
745 assert!(!state.hide_scheduled);
746 }
747
748 #[test]
749 fn animation_state_should_not_reschedule_pending_offcanvas_hide() {
750 let mut state = SidebarAnimationState::new(px(240.), true);
751
752 let request = state.update_target(px(0.), true);
753
754 assert_eq!(request, Some(1));
755 assert!(!state.needs_update(px(0.), true));
756 assert_eq!(state.update_target(px(0.), true), None);
757 assert_eq!(state.hide_request, 1);
758 }
759
760 #[test]
761 fn animation_state_should_cancel_pending_hide_when_reexpanded() {
762 let mut state = SidebarAnimationState::new(px(240.), true);
763
764 let request = state.update_target(px(0.), true).unwrap();
765 state.update_target(px(240.), false);
766
767 assert!(!state.finish_hide(request));
768 assert!(state.render_child);
769 assert!(!state.hide_scheduled);
770 assert_eq!(state.from_width, px(0.));
771 assert_eq!(state.target_width, px(240.));
772 }
773
774 #[test]
775 fn animation_state_should_ignore_stale_hide_request() {
776 let mut state = SidebarAnimationState::new(px(240.), true);
777
778 let request = state.update_target(px(0.), true).unwrap();
779 state.update_target(px(240.), false);
780 state.update_target(px(0.), true);
781
782 assert!(!state.finish_hide(request));
783 assert!(state.render_child);
784 assert!(state.hide_scheduled);
785 }
786
787 #[test]
788 fn animation_state_should_start_hidden_when_initially_offcanvas_collapsed() {
789 let state = SidebarAnimationState::new(px(0.), false);
790
791 assert!(!state.render_child);
792 assert_eq!(state.from_width, px(0.));
793 assert_eq!(state.target_width, px(0.));
794 }
795}