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