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::{
11    AnyElement, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement,
12    ParentElement as _, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement,
13    Styled, Window, div, percentage, prelude::FluentBuilder,
14};
15use gpui_base::LogicalStyledExt as _;
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    /// Accessible name for the submenu caret: the toggle is icon-only,
236    /// so assistive tech needs the item it acts on.
237    fn caret_accessibility_label(&self) -> SharedString {
238        format!("Toggle {} submenu", self.label).into()
239    }
240
241    /// Set the context menu for the menu item.
242    pub fn context_menu(
243        mut self,
244        f: impl Fn(PopupMenu, &mut Window, &mut App) -> PopupMenu + 'static,
245    ) -> Self {
246        self.context_menu = Some(Rc::new(f));
247        self
248    }
249}
250
251impl FluentBuilder for SidebarMenuItem {}
252
253impl Collapsible for SidebarMenuItem {
254    fn is_collapsed(&self) -> bool {
255        self.collapsed
256    }
257
258    fn collapsed(mut self, collapsed: bool) -> Self {
259        self.collapsed = collapsed;
260        self
261    }
262}
263
264impl SidebarItem for SidebarMenuItem {
265    fn render(
266        self,
267        id: impl Into<ElementId>,
268        window: &mut Window,
269        cx: &mut App,
270    ) -> impl IntoElement {
271        let click_to_open = self.click_to_open;
272        let click_to_toggle = self.click_to_toggle;
273        let default_open = self.default_open;
274        let collapsed_tooltip = self.collapsed_tooltip();
275        let id = id.into();
276        let label_text = self.label.clone();
277        let accessibility_label = self.accessibility_label.clone();
278        let is_submenu = self.is_submenu();
279        let open_state = if is_submenu {
280            Some(window.use_keyed_state(id.clone(), cx, |_, _| default_open))
281        } else {
282            None
283        };
284        let handler = self.handler.clone();
285        let is_collapsed = self.collapsed;
286        let is_active = self.active;
287        let is_hoverable = !is_active && !self.disabled;
288        let is_disabled = self.disabled;
289        let is_open = open_state
290            .as_ref()
291            .map_or(false, |s| !is_collapsed && *s.read(cx));
292        let rtl = gpui_base::LayoutDirection::global(cx).is_rtl();
293
294        div()
295            .id(id.clone())
296            .test_support()
297            .w_full()
298            .child(
299                h_flex()
300                    .flex_row_dir(cx)
301                    .size_full()
302                    .id("item")
303                    .role(Role::TreeItem)
304                    .aria_label(accessibility_label.unwrap_or_else(|| label_text.clone()))
305                    .aria_selected(is_active)
306                    .overflow_x_hidden()
307                    .flex_shrink_0()
308                    .p_2()
309                    .gap_x_2()
310                    .rounded(cx.theme().radius)
311                    .text_sm()
312                    .refine_style(&self.style)
313                    .when(is_hoverable, |this| {
314                        this.hover(|this| {
315                            this.bg(cx.theme().sidebar_accent.opacity(0.8))
316                                .text_color(cx.theme().sidebar_accent_foreground)
317                        })
318                    })
319                    .when(is_active, |this| {
320                        this.font_medium()
321                            .bg(cx.theme().tokens.sidebar_accent)
322                            .text_color(cx.theme().sidebar_accent_foreground)
323                    })
324                    .when_some(self.icon.clone(), |this, icon| this.child(icon))
325                    .when(is_collapsed, |this| {
326                        this.justify_center().when(is_active, |this| {
327                            this.bg(cx.theme().tokens.sidebar_accent)
328                                .text_color(cx.theme().sidebar_accent_foreground)
329                        })
330                    })
331                    .when(!is_collapsed, |this| {
332                        this.h_7()
333                            .child(
334                                h_flex()
335                                    .flex_row_dir(cx)
336                                    .flex_1()
337                                    .gap_x_2()
338                                    .justify_between()
339                                    .overflow_x_hidden()
340                                    .child(
341                                        h_flex()
342                                            .flex_row_dir(cx)
343                                            .flex_1()
344                                            .overflow_x_hidden()
345                                            .refine_style(&self.label_style)
346                                            .child(self.label.clone()),
347                                    )
348                                    .when_some(self.suffix.clone(), |this, suffix| {
349                                        this.child(suffix(window, cx).into_any_element())
350                                    }),
351                            )
352                            .when_some(open_state.clone(), |this, open_state| {
353                                this.child(
354                                    Button::new("caret")
355                                        .xsmall()
356                                        .ghost()
357                                        .accessibility_label(self.caret_accessibility_label())
358                                        .icon(
359                                            // Points toward the end edge while
360                                            // closed and turns down when open.
361                                            Icon::new(if rtl {
362                                                IconName::ChevronLeft
363                                            } else {
364                                                IconName::ChevronRight
365                                            })
366                                            .size_4()
367                                            .when(
368                                                is_open,
369                                                |this| {
370                                                    // A quarter turn toward down: clockwise
371                                                    // from right, counter-clockwise from left.
372                                                    this.rotate(percentage(
373                                                        if rtl { 270. } else { 90. } / 360.,
374                                                    ))
375                                                },
376                                            ),
377                                        )
378                                        .on_click({
379                                            move |_, _, cx| {
380                                                // Avoid trigger item click, just expand/collapse submenu
381                                                cx.stop_propagation();
382                                                open_state.update(cx, |is_open, cx| {
383                                                    *is_open = !*is_open;
384                                                    cx.notify();
385                                                })
386                                            }
387                                        }),
388                                )
389                            })
390                    })
391                    .when(is_disabled, |this| {
392                        this.text_color(cx.theme().muted_foreground)
393                    })
394                    .when(!is_disabled, |this| {
395                        this.on_click({
396                            let open_state = open_state.clone();
397                            move |ev, window, cx| {
398                                if click_to_open {
399                                    if let Some(ref s) = open_state {
400                                        s.update(cx, |is_open: &mut bool, cx| {
401                                            *is_open = true;
402                                            cx.notify();
403                                        });
404                                    }
405                                } else if click_to_toggle {
406                                    if let Some(ref s) = open_state {
407                                        s.update(cx, |is_open: &mut bool, cx| {
408                                            *is_open = !*is_open;
409                                            cx.notify();
410                                        });
411                                    }
412                                }
413                                handler(ev, window, cx)
414                            }
415                        })
416                    })
417                    .map(|this| {
418                        if let Some(tooltip) = collapsed_tooltip {
419                            this.managed_tooltip_at(Placement::Right, move |window, cx| {
420                                Tooltip::new(tooltip.clone()).build(window, cx)
421                            })
422                        } else {
423                            this
424                        }
425                    })
426                    .map(|this| {
427                        if let Some(context_menu) = self.context_menu {
428                            this.context_menu(move |menu, window, cx| {
429                                context_menu(menu, window, cx)
430                            })
431                            .into_any_element()
432                        } else {
433                            this.into_any_element()
434                        }
435                    }),
436            )
437            .when(is_open, |this| {
438                this.child(
439                    v_flex()
440                        .id("submenu")
441                        .border_s(gpui::px(1.), cx)
442                        .border_color(cx.theme().sidebar_border)
443                        .gap_1()
444                        .ms(gpui::rems(0.875), cx)
445                        .ps(gpui::rems(0.625), cx)
446                        .py_0p5()
447                        .children(self.children.into_iter().enumerate().map(|(ix, item)| {
448                            let id = format!("{}-{}", id, ix);
449                            item.render(id, window, cx).into_any_element()
450                        })),
451                )
452            })
453    }
454}
455
456impl Styled for SidebarMenuItem {
457    fn style(&mut self) -> &mut StyleRefinement {
458        &mut self.style
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465
466    #[test]
467    fn collapsed_icon_item_uses_label_as_tooltip() {
468        let item = SidebarMenuItem::new("Projects")
469            .icon(Icon::default())
470            .collapsed(true);
471
472        assert_eq!(item.collapsed_tooltip().as_deref(), Some("Projects"));
473    }
474
475    #[test]
476    fn expanded_or_iconless_item_has_no_collapsed_tooltip() {
477        let expanded = SidebarMenuItem::new("Projects").icon(Icon::default());
478        let iconless = SidebarMenuItem::new("Projects").collapsed(true);
479
480        assert!(expanded.collapsed_tooltip().is_none());
481        assert!(iconless.collapsed_tooltip().is_none());
482    }
483
484    #[test]
485    fn submenu_caret_is_named_after_the_item() {
486        let item =
487            SidebarMenuItem::new("Projects").children(vec![SidebarMenuItem::new("Overview")]);
488
489        assert_eq!(item.caret_accessibility_label(), "Toggle Projects submenu");
490    }
491}