Skip to main content

gpui_component/sidebar/
menu.rs

1use crate::{
2    ActiveTheme as _, Collapsible, Icon, IconName, Placement, Sizable as _, StyledExt,
3    button::{Button, ButtonVariants as _},
4    h_flex,
5    menu::{ContextMenuExt, PopupMenu},
6    sidebar::SidebarItem,
7    tooltip::{ManagedTooltipExt as _, Tooltip},
8    v_flex,
9};
10use gpui::ColorExt as _;
11use gpui::{
12    AnyElement, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement,
13    ParentElement as _, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled,
14    Window, div, percentage, prelude::FluentBuilder,
15};
16use std::rc::Rc;
17
18/// Menu for the [`super::Sidebar`]
19#[derive(Clone)]
20pub struct SidebarMenu {
21    style: StyleRefinement,
22    collapsed: bool,
23    items: Vec<SidebarMenuItem>,
24}
25
26impl SidebarMenu {
27    /// Create a new SidebarMenu
28    pub fn new() -> Self {
29        Self {
30            style: StyleRefinement::default(),
31            items: Vec::new(),
32            collapsed: false,
33        }
34    }
35
36    /// Add a [`SidebarMenuItem`] child menu item to the sidebar menu.
37    ///
38    /// See also [`SidebarMenu::children`].
39    pub fn child(mut self, child: impl Into<SidebarMenuItem>) -> Self {
40        self.items.push(child.into());
41        self
42    }
43
44    /// Add multiple [`SidebarMenuItem`] child menu items to the sidebar menu.
45    pub fn children(
46        mut self,
47        children: impl IntoIterator<Item = impl Into<SidebarMenuItem>>,
48    ) -> Self {
49        self.items = children.into_iter().map(Into::into).collect();
50        self
51    }
52}
53
54impl Collapsible for SidebarMenu {
55    fn is_collapsed(&self) -> bool {
56        self.collapsed
57    }
58
59    fn collapsed(mut self, collapsed: bool) -> Self {
60        self.collapsed = collapsed;
61        self
62    }
63}
64
65impl SidebarItem for SidebarMenu {
66    fn render(
67        self,
68        id: impl Into<ElementId>,
69        window: &mut Window,
70        cx: &mut App,
71    ) -> impl IntoElement {
72        let id = id.into();
73
74        v_flex()
75            .gap_2()
76            .refine_style(&self.style)
77            .children(self.items.into_iter().enumerate().map(|(ix, item)| {
78                let id = SharedString::from(format!("{}-{}", id, ix));
79                item.collapsed(self.collapsed)
80                    .render(id, window, cx)
81                    .into_any_element()
82            }))
83    }
84}
85
86impl Styled for SidebarMenu {
87    fn style(&mut self) -> &mut StyleRefinement {
88        &mut self.style
89    }
90}
91
92/// Menu item for the [`SidebarMenu`]
93#[derive(Clone)]
94pub struct SidebarMenuItem {
95    icon: Option<Icon>,
96    label: SharedString,
97    handler: Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
98    active: bool,
99    default_open: bool,
100    click_to_open: bool,
101    collapsed: bool,
102    click_to_toggle: bool,
103    children: Vec<Self>,
104    suffix: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>>,
105    disabled: bool,
106    context_menu: Option<Rc<dyn Fn(PopupMenu, &mut Window, &mut App) -> PopupMenu + 'static>>,
107}
108
109impl SidebarMenuItem {
110    /// Create a new [`SidebarMenuItem`] with a label.
111    pub fn new(label: impl Into<SharedString>) -> Self {
112        Self {
113            icon: None,
114            label: label.into(),
115            handler: Rc::new(|_, _, _| {}),
116            active: false,
117            collapsed: false,
118            default_open: false,
119            click_to_open: false,
120            click_to_toggle: false,
121            children: Vec::new(),
122            suffix: None,
123            disabled: false,
124            context_menu: None,
125        }
126    }
127
128    /// Set the icon for the menu item
129    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
130        self.icon = Some(icon.into());
131        self
132    }
133
134    /// Set the active state of the menu item
135    pub fn active(mut self, active: bool) -> Self {
136        self.active = active;
137        self
138    }
139
140    /// Add a click handler to the menu item
141    pub fn on_click(
142        mut self,
143        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
144    ) -> Self {
145        self.handler = Rc::new(handler);
146        self
147    }
148
149    /// Set the collapsed state of the menu item
150    pub fn collapsed(mut self, collapsed: bool) -> Self {
151        self.collapsed = collapsed;
152        self
153    }
154
155    /// Set the default open state of the Submenu, default is `false`.
156    ///
157    /// This only used on initial render, the internal state will be used afterwards.
158    pub fn default_open(mut self, open: bool) -> Self {
159        self.default_open = open;
160        self
161    }
162
163    /// Set whether clicking the menu item open the submenu.
164    ///
165    /// Default is `false`.
166    ///
167    /// If `false` we only handle open/close via the caret button.
168    pub fn click_to_open(mut self, click_to_open: bool) -> Self {
169        self.click_to_open = click_to_open;
170        self
171    }
172
173    /// Set whether clicking the menu item toggles the submenu.
174    ///
175    /// If click_to_open is `true`, this has no effect.
176    ///
177    /// Default is `false`.
178    pub fn click_to_toggle(mut self, click_to_toggle: bool) -> Self {
179        self.click_to_toggle = click_to_toggle;
180        self
181    }
182
183    pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Self>>) -> Self {
184        self.children = children.into_iter().map(Into::into).collect();
185        self
186    }
187
188    /// Set the suffix for the menu item.
189    pub fn suffix<F, E>(mut self, builder: F) -> Self
190    where
191        F: Fn(&mut Window, &mut App) -> E + 'static,
192        E: IntoElement,
193    {
194        self.suffix = Some(Rc::new(move |window, cx| {
195            builder(window, cx).into_any_element()
196        }));
197        self
198    }
199
200    /// Set disabled flat for menu item.
201    pub fn disable(mut self, disable: bool) -> Self {
202        self.disabled = disable;
203        self
204    }
205
206    fn is_submenu(&self) -> bool {
207        self.children.len() > 0
208    }
209
210    fn collapsed_tooltip(&self) -> Option<SharedString> {
211        (self.collapsed && self.icon.is_some()).then(|| self.label.clone())
212    }
213
214    /// Set the context menu for the menu item.
215    pub fn context_menu(
216        mut self,
217        f: impl Fn(PopupMenu, &mut Window, &mut App) -> PopupMenu + 'static,
218    ) -> Self {
219        self.context_menu = Some(Rc::new(f));
220        self
221    }
222}
223
224impl FluentBuilder for SidebarMenuItem {}
225
226impl Collapsible for SidebarMenuItem {
227    fn is_collapsed(&self) -> bool {
228        self.collapsed
229    }
230
231    fn collapsed(mut self, collapsed: bool) -> Self {
232        self.collapsed = collapsed;
233        self
234    }
235}
236
237impl SidebarItem for SidebarMenuItem {
238    fn render(
239        self,
240        id: impl Into<ElementId>,
241        window: &mut Window,
242        cx: &mut App,
243    ) -> impl IntoElement {
244        let click_to_open = self.click_to_open;
245        let click_to_toggle = self.click_to_toggle;
246        let default_open = self.default_open;
247        let collapsed_tooltip = self.collapsed_tooltip();
248        let id = id.into();
249        let is_submenu = self.is_submenu();
250        let open_state = if is_submenu {
251            Some(window.use_keyed_state(id.clone(), cx, |_, _| default_open))
252        } else {
253            None
254        };
255        let handler = self.handler.clone();
256        let is_collapsed = self.collapsed;
257        let is_active = self.active;
258        let is_hoverable = !is_active && !self.disabled;
259        let is_disabled = self.disabled;
260        let is_open = open_state
261            .as_ref()
262            .map_or(false, |s| !is_collapsed && *s.read(cx));
263
264        div()
265            .id(id.clone())
266            .w_full()
267            .child(
268                h_flex()
269                    .size_full()
270                    .id("item")
271                    .overflow_x_hidden()
272                    .flex_shrink_0()
273                    .p_2()
274                    .gap_x_2()
275                    .rounded(cx.theme().radius)
276                    .text_sm()
277                    .when(is_hoverable, |this| {
278                        this.hover(|this| {
279                            this.bg(cx.theme().sidebar_accent.opacity(0.8))
280                                .text_color(cx.theme().sidebar_accent_foreground)
281                        })
282                    })
283                    .when(is_active, |this| {
284                        this.font_medium()
285                            .bg(cx.theme().tokens.sidebar_accent)
286                            .text_color(cx.theme().sidebar_accent_foreground)
287                    })
288                    .when_some(self.icon.clone(), |this, icon| this.child(icon))
289                    .when(is_collapsed, |this| {
290                        this.justify_center().when(is_active, |this| {
291                            this.bg(cx.theme().tokens.sidebar_accent)
292                                .text_color(cx.theme().sidebar_accent_foreground)
293                        })
294                    })
295                    .when(!is_collapsed, |this| {
296                        this.h_7()
297                            .child(
298                                h_flex()
299                                    .flex_1()
300                                    .gap_x_2()
301                                    .justify_between()
302                                    .overflow_x_hidden()
303                                    .child(
304                                        h_flex()
305                                            .flex_1()
306                                            .overflow_x_hidden()
307                                            .child(self.label.clone()),
308                                    )
309                                    .when_some(self.suffix.clone(), |this, suffix| {
310                                        this.child(suffix(window, cx).into_any_element())
311                                    }),
312                            )
313                            .when_some(open_state.clone(), |this, open_state| {
314                                this.child(
315                                    Button::new("caret")
316                                        .xsmall()
317                                        .ghost()
318                                        .icon(
319                                            Icon::new(IconName::ChevronRight)
320                                                .size_4()
321                                                .when(is_open, |this| {
322                                                    this.rotate(percentage(90. / 360.))
323                                                }),
324                                        )
325                                        .on_click({
326                                            move |_, _, cx| {
327                                                // Avoid trigger item click, just expand/collapse submenu
328                                                cx.stop_propagation();
329                                                open_state.update(cx, |is_open, cx| {
330                                                    *is_open = !*is_open;
331                                                    cx.notify();
332                                                })
333                                            }
334                                        }),
335                                )
336                            })
337                    })
338                    .when(is_disabled, |this| {
339                        this.text_color(cx.theme().muted_foreground)
340                    })
341                    .when(!is_disabled, |this| {
342                        this.on_click({
343                            let open_state = open_state.clone();
344                            move |ev, window, cx| {
345                                if click_to_open {
346                                    if let Some(ref s) = open_state {
347                                        s.update(cx, |is_open: &mut bool, cx| {
348                                            *is_open = true;
349                                            cx.notify();
350                                        });
351                                    }
352                                } else if click_to_toggle {
353                                    if let Some(ref s) = open_state {
354                                        s.update(cx, |is_open: &mut bool, cx| {
355                                            *is_open = !*is_open;
356                                            cx.notify();
357                                        });
358                                    }
359                                }
360                                handler(ev, window, cx)
361                            }
362                        })
363                    })
364                    .map(|this| {
365                        if let Some(tooltip) = collapsed_tooltip {
366                            this.managed_tooltip_at(Placement::Right, move |window, cx| {
367                                Tooltip::new(tooltip.clone()).build(window, cx)
368                            })
369                        } else {
370                            this
371                        }
372                    })
373                    .map(|this| {
374                        if let Some(context_menu) = self.context_menu {
375                            this.context_menu(move |menu, window, cx| {
376                                context_menu(menu, window, cx)
377                            })
378                            .into_any_element()
379                        } else {
380                            this.into_any_element()
381                        }
382                    }),
383            )
384            .when(is_open, |this| {
385                this.child(
386                    v_flex()
387                        .id("submenu")
388                        .border_l_1()
389                        .border_color(cx.theme().sidebar_border)
390                        .gap_1()
391                        .ml_3p5()
392                        .pl_2p5()
393                        .py_0p5()
394                        .children(self.children.into_iter().enumerate().map(|(ix, item)| {
395                            let id = format!("{}-{}", id, ix);
396                            item.render(id, window, cx).into_any_element()
397                        })),
398                )
399            })
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    #[test]
408    fn collapsed_icon_item_uses_label_as_tooltip() {
409        let item = SidebarMenuItem::new("Projects")
410            .icon(Icon::default())
411            .collapsed(true);
412
413        assert_eq!(item.collapsed_tooltip().as_deref(), Some("Projects"));
414    }
415
416    #[test]
417    fn expanded_or_iconless_item_has_no_collapsed_tooltip() {
418        let expanded = SidebarMenuItem::new("Projects").icon(Icon::default());
419        let iconless = SidebarMenuItem::new("Projects").collapsed(true);
420
421        assert!(expanded.collapsed_tooltip().is_none());
422        assert!(iconless.collapsed_tooltip().is_none());
423    }
424}