Skip to main content

gpui_material_components/overlay/
menu.rs

1use std::cell::{Cell, RefCell};
2use std::rc::Rc;
3
4use crate::motion::{OverlayMotion, ScaledOverlay, menu_pivot};
5use crate::{Icon, IconName};
6use gpui::{
7    Anchor, AnyElement, App, Axis, Bounds, ElementId, FocusHandle, Focusable, InteractiveElement,
8    IntoElement, MouseButton, ParentElement, RenderOnce, Role, ScrollHandle, SharedString,
9    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
10};
11use gpui_base::{Popover, PopoverState, TestSupportExt};
12use gpui_material_foundation::{
13    Surface, color, logical_anchor, move_roving_focus, window_material_theme,
14};
15use gpui_material_theme::{ColorRole, Direction, Elevation};
16
17type Action = Rc<dyn Fn(&mut Window, &mut App)>;
18type ComposedTrigger = Box<dyn FnOnce(bool, Action) -> AnyElement>;
19
20/// An item in a Material menu. Callers retain command and selection state.
21pub struct MenuItem {
22    id: ElementId,
23    label: SharedString,
24    disabled: bool,
25    kind: Kind,
26}
27
28enum Kind {
29    Action(Option<Action>),
30    Check(bool, Option<Action>),
31    Select(bool, Option<Action>),
32    Group,
33    Submenu(Vec<MenuItem>),
34}
35
36struct MenuExitRow {
37    label: SharedString,
38    disabled: bool,
39    group: bool,
40    selected: bool,
41    submenu: bool,
42}
43
44impl From<&MenuItem> for MenuExitRow {
45    fn from(item: &MenuItem) -> Self {
46        Self {
47            label: item.label.clone(),
48            disabled: item.disabled,
49            group: matches!(item.kind, Kind::Group),
50            selected: matches!(item.kind, Kind::Check(true, _) | Kind::Select(true, _)),
51            submenu: matches!(item.kind, Kind::Submenu(_)),
52        }
53    }
54}
55
56impl MenuItem {
57    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
58        Self {
59            id: id.into(),
60            label: label.into(),
61            disabled: false,
62            kind: Kind::Action(None),
63        }
64    }
65
66    pub fn group(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
67        Self {
68            kind: Kind::Group,
69            ..Self::new(id, title)
70        }
71    }
72
73    pub fn submenu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
74        self.kind = Kind::Submenu(items.into_iter().collect());
75        self
76    }
77
78    pub fn disabled(mut self, disabled: bool) -> Self {
79        self.disabled = disabled;
80        self
81    }
82
83    pub fn checked(mut self, checked: bool) -> Self {
84        self.kind = Kind::Check(checked, self.action());
85        self
86    }
87
88    pub fn selected(mut self, selected: bool) -> Self {
89        self.kind = Kind::Select(selected, self.action());
90        self
91    }
92
93    fn action(&self) -> Option<Action> {
94        match &self.kind {
95            Kind::Action(action) | Kind::Check(_, action) | Kind::Select(_, action) => {
96                action.clone()
97            }
98            _ => None,
99        }
100    }
101
102    pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
103        match &mut self.kind {
104            Kind::Action(handler) | Kind::Check(_, handler) | Kind::Select(_, handler) => {
105                *handler = Some(Rc::new(action));
106            }
107            _ => {}
108        }
109        self
110    }
111}
112
113/// Positions a Material menu against a caller-owned, keyboard-focusable trigger.
114/// Pointer and keyboard activation use the same Base popover focus lifecycle.
115#[derive(IntoElement)]
116pub struct Menu {
117    id: ElementId,
118    trigger: AnyElement,
119    items: Vec<MenuItem>,
120    mouse_button: MouseButton,
121    anchor: Anchor,
122    close_parent: Option<Action>,
123    enabled: bool,
124    ancestor: Option<Rc<PopupBounds>>,
125    composed_trigger: Option<ComposedTrigger>,
126}
127
128#[derive(Default)]
129struct PopupBounds {
130    trigger: Cell<Bounds<gpui::Pixels>>,
131    popup: Cell<Bounds<gpui::Pixels>>,
132    child: RefCell<Option<Rc<PopupBounds>>>,
133    items: RefCell<Vec<MenuExitRow>>,
134    scroll: ScrollHandle,
135    motion: Cell<Option<OverlayMotion>>,
136    open: Rc<Cell<bool>>,
137}
138
139impl PopupBounds {
140    fn contains(&self, point: &gpui::Point<gpui::Pixels>) -> bool {
141        self.trigger.get().contains(point)
142            || self.popup.get().contains(point)
143            || self
144                .child
145                .borrow()
146                .as_ref()
147                .is_some_and(|child| child.open.get() && child.contains(point))
148    }
149}
150
151impl Menu {
152    pub fn new(
153        id: impl Into<ElementId>,
154        trigger: impl IntoElement,
155        items: impl IntoIterator<Item = MenuItem>,
156    ) -> Self {
157        Self {
158            id: id.into(),
159            trigger: trigger.into_any_element(),
160            items: items.into_iter().collect(),
161            mouse_button: MouseButton::Left,
162            anchor: Anchor::TopLeft,
163            close_parent: None,
164            enabled: true,
165            ancestor: None,
166            composed_trigger: None,
167        }
168    }
169
170    /// Opens on secondary click; Enter and Space still work on the trigger.
171    pub fn context(mut self) -> Self {
172        self.mouse_button = MouseButton::Right;
173        self
174    }
175
176    pub fn anchor(mut self, anchor: Anchor) -> Self {
177        self.anchor = anchor;
178        self
179    }
180
181    /// Creates a trigger whose accessible activation can open or close this menu.
182    #[doc(hidden)]
183    pub fn composed(
184        id: impl Into<ElementId>,
185        items: impl IntoIterator<Item = MenuItem>,
186        trigger: impl FnOnce(bool, Action) -> AnyElement + 'static,
187    ) -> Self {
188        let mut menu = Self::new(id, div(), items);
189        menu.composed_trigger = Some(Box::new(trigger));
190        menu
191    }
192}
193
194impl RenderOnce for Menu {
195    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
196        let direction = window_material_theme(window, cx).layout.direction;
197        let submenu = self.close_parent.is_some();
198        if !self.enabled {
199            return self.trigger;
200        }
201        let view = window.current_view();
202        let bounds = window
203            .use_keyed_state((self.id.clone(), "menu-bounds"), cx, |_, _| {
204                Rc::new(PopupBounds::default())
205            })
206            .read(cx)
207            .clone();
208        let open_state = bounds.open.clone();
209        let open = open_state.get();
210        let key_state = open_state.clone();
211        let trigger_state = open_state.clone();
212        let trigger: Action = Rc::new(move |_, cx| {
213            trigger_state.set(!trigger_state.get());
214            cx.notify(view);
215        });
216        let motion = OverlayMotion::sample(&self.id, open, window, cx);
217        let position = bounds.clone();
218        let ancestor = self.ancestor.clone();
219        if open {
220            let mut rows = bounds.items.borrow_mut();
221            rows.clear();
222            rows.extend(self.items.iter().map(MenuExitRow::from));
223        }
224        bounds.motion.set(motion);
225        let forward = if direction == Direction::Rtl {
226            "left"
227        } else {
228            "right"
229        };
230        let exit_view = motion.filter(|_| !open).map(|motion| {
231            // Closing the parent removes Base's nested popup hosts immediately.
232            // Use the last presented branch to finish their own visual exits.
233            let mut exits = div();
234            let mut level = Some(bounds.clone());
235            let mut depth = 0;
236            while let Some(bounds) = level {
237                let Some(previous) = bounds.motion.get() else {
238                    break;
239                };
240                let motion = if depth == 0 {
241                    motion
242                } else {
243                    OverlayMotion {
244                        scale: 0.8 + (motion.scale - 0.8) * (previous.scale - 0.8) / 0.2,
245                        alpha: motion.alpha * previous.alpha,
246                    }
247                };
248                exits = exits.children(menu_exit(
249                    (&self.id, depth),
250                    &bounds,
251                    motion,
252                    direction,
253                    window,
254                    cx,
255                ));
256                level = bounds.child.borrow().clone();
257                depth += 1;
258            }
259            exits
260        });
261        if !open && motion.is_none() {
262            bounds.items.borrow_mut().clear();
263            bounds.child.borrow_mut().take();
264        }
265        let menu = Popover::new(self.id)
266            .open(open)
267            .on_open_change(move |open, _, cx| {
268                open_state.set(*open);
269                cx.notify(view);
270            })
271            .anchor(logical_anchor(self.anchor, direction))
272            .offset(px(4.))
273            .mouse_button(self.mouse_button)
274            .overlay_closable(false)
275            .on_position(move |resolved, trigger| {
276                position.trigger.set(trigger);
277                position.popup.set(resolved.bounds);
278                if let Some(ancestor) = &ancestor {
279                    *ancestor.child.borrow_mut() = Some(position.clone());
280                }
281            })
282            .trigger_with(move |open, _, _| {
283                let content = self
284                    .composed_trigger
285                    .map_or(self.trigger, |build| build(open, trigger));
286                div()
287                    .id("menu-trigger")
288                    .role(Role::Group)
289                    .aria_expanded(open)
290                    .on_key_down(move |event, _, cx| {
291                        if submenu && event.keystroke.key == forward && !key_state.get() {
292                            key_state.set(true);
293                            cx.notify(view);
294                            cx.stop_propagation();
295                        }
296                    })
297                    .child(content)
298                    .into_any_element()
299            })
300            .content(move |state, window, cx| {
301                let motion = motion.expect("open menu has motion");
302                let own = cx.entity().downgrade();
303                let close_level = own.clone();
304                let close_level: Action = Rc::new(move |window, cx| {
305                    let _ = close_level.update(cx, |state: &mut PopoverState, cx| {
306                        state.dismiss(window, cx);
307                    });
308                });
309                let close: Action = Rc::new(move |window, cx| {
310                    let _ =
311                        own.update(cx, |state: &mut PopoverState, cx| state.dismiss(window, cx));
312                    if let Some(close_parent) = &self.close_parent {
313                        close_parent(window, cx);
314                    }
315                });
316                let dismissal = close_level.clone();
317                let item_bounds = bounds.clone();
318                let content = menu_content(
319                    self.items,
320                    close,
321                    submenu.then_some(close_level),
322                    state.focus_handle(cx),
323                    (direction, bounds.clone(), bounds.scroll.clone(), motion),
324                    window,
325                    cx,
326                );
327                let popup = div()
328                    .id("dismiss-menu")
329                    .opacity(motion.alpha)
330                    .on_mouse_down_out(move |event, window, cx| {
331                        let point = &event.position;
332                        if bounds.contains(point) {
333                            return;
334                        }
335                        dismissal(window, cx);
336                    })
337                    .child(content);
338                ScaledOverlay::new(popup, motion, move |menu| {
339                    menu_pivot(menu, item_bounds.trigger.get())
340                })
341                .into_any_element()
342            });
343        div()
344            .relative()
345            .child(menu)
346            .children(exit_view)
347            .into_any_element()
348    }
349}
350
351fn menu_exit(
352    (id, depth): (&ElementId, usize),
353    bounds: &PopupBounds,
354    motion: OverlayMotion,
355    direction: Direction,
356    window: &Window,
357    cx: &App,
358) -> Option<AnyElement> {
359    let exit = bounds.popup.get();
360    if exit.size.width <= px(0.) {
361        return None;
362    }
363    let trigger = bounds.trigger.get();
364    let theme = window_material_theme(window, cx);
365    let exit_ink = color(theme.colors.color(ColorRole::OnSurface));
366    let exit_muted = color(theme.colors.color(ColorRole::OnSurfaceVariant));
367    let exit_selected = color(theme.colors.color(ColorRole::SecondaryContainer));
368    let exit_selected_ink = color(theme.colors.color(ColorRole::OnSecondaryContainer));
369    let dp = |value| motion.px(value);
370    let spacing = motion.px(16.);
371    let items = bounds.items.borrow();
372    let rows = items
373        .iter()
374        .map(|item| {
375            let label = item.label.clone();
376            let tint = if item.group {
377                exit_muted
378            } else if item.disabled {
379                exit_ink.opacity(0.38)
380            } else if item.selected {
381                exit_selected_ink
382            } else {
383                exit_ink
384            };
385            div().px(spacing * 0.75).text_color(tint).when_else(
386                item.group,
387                |row| row.py(spacing * 0.5).child(label.clone()),
388                |row| {
389                    row.min_h(dp(48.))
390                        .flex()
391                        .items_center()
392                        .line_height(dp(20.))
393                        .gap(spacing * 0.5)
394                        .justify_start()
395                        .when(direction == Direction::Rtl, Styled::flex_row_reverse)
396                        .when(item.selected, |row| row.bg(exit_selected))
397                        .child(div().w(dp(18.)).flex_none().when(item.selected, |slot| {
398                            slot.child(Icon::new(IconName::Check).size(dp(18.)))
399                        }))
400                        .child(div().flex_1().min_w_0().truncate().child(label.clone()))
401                        .when(item.submenu, |row| {
402                            row.child(
403                                Icon::new(IconName::ChevronRight)
404                                    .size(dp(18.))
405                                    .mirror_in_rtl(true),
406                            )
407                        })
408                },
409            )
410        })
411        .collect::<Vec<_>>();
412    let surface = div()
413        .id(if depth == 0 {
414            ElementId::from((id.clone(), "menu-exit"))
415        } else {
416            ElementId::from((id.clone(), format!("submenu-exit-{depth}")))
417        })
418        .test_support()
419        .h(exit.size.height * motion.scale)
420        .w(exit.size.width * motion.scale)
421        .opacity(motion.alpha)
422        .overflow_y_scroll()
423        .track_scroll(&bounds.scroll)
424        .child(
425            Surface::new(ColorRole::SurfaceContainer)
426                .shadow_elevation(Elevation::Level2)
427                .shadow_scale(motion.scale)
428                .w_full()
429                .rounded(spacing * 0.25)
430                .py(spacing * 0.5)
431                .children(rows),
432        )
433        .child(div().absolute().inset_0().occlude());
434    Some(
435        gpui::deferred(
436            gpui_base::Positioner::corner(gpui::Anchor::TopLeft, exit.origin).child(
437                ScaledOverlay::new(
438                    super::text_style(
439                        surface,
440                        gpui_material_theme::TypeRole::LabelLarge,
441                        motion.scale,
442                        window,
443                        cx,
444                    ),
445                    motion,
446                    move |bounds| menu_pivot(bounds, trigger),
447                ),
448            ),
449        )
450        .with_priority(100 + depth)
451        .into_any_element(),
452    )
453}
454
455fn menu_content(
456    items: Vec<MenuItem>,
457    close: Action,
458    close_level: Option<Action>,
459    popup_focus: FocusHandle,
460    (direction, bounds, scroll, motion): (Direction, Rc<PopupBounds>, ScrollHandle, OverlayMotion),
461    window: &mut Window,
462    cx: &mut App,
463) -> AnyElement {
464    let theme = window_material_theme(window, cx);
465    let ink = color(theme.colors.color(ColorRole::OnSurface));
466    let muted = color(theme.colors.color(ColorRole::OnSurfaceVariant));
467    let selected_color = color(theme.colors.color(ColorRole::SecondaryContainer));
468    let selected_ink = color(theme.colors.color(ColorRole::OnSecondaryContainer));
469    let container = color(theme.colors.color(ColorRole::SurfaceContainer));
470    let focus = items
471        .iter()
472        .map(|item| {
473            let handle =
474                window.use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| cx.focus_handle());
475            (
476                handle.read(cx).clone(),
477                !item.disabled && !matches!(item.kind, Kind::Group),
478            )
479        })
480        .collect::<Vec<_>>();
481    let handles = focus.clone();
482    if popup_focus.is_focused(window)
483        && let Some((first, _)) = handles.iter().find(|(_, enabled)| *enabled)
484    {
485        let first = first.clone();
486        window.defer(cx, move |window, cx| {
487            if popup_focus.is_focused(window) {
488                first.focus(window, cx);
489            }
490        });
491    }
492    let viewport = window.viewport_size();
493    let limit = (viewport.height * 0.7).min(px(420.)) * motion.scale;
494    let available_width = (viewport.width - px(16.)).max(px(0.)) * motion.scale;
495    let dp = |value| motion.px(value);
496    let spacing = motion.px(16.);
497    let menu = div()
498        .id(if close_level.is_some() {
499            "submenu-content"
500        } else {
501            "menu"
502        })
503        .test_support()
504        .role(Role::Menu)
505        .overflow_y_scroll()
506        .track_scroll(&scroll)
507        .max_h(limit)
508        .on_key_down(move |event, window, cx| {
509            let backward = if direction == Direction::Rtl {
510                "right"
511            } else {
512                "left"
513            };
514            if event.keystroke.key == backward
515                && let Some(close_level) = &close_level
516            {
517                close_level(window, cx);
518                cx.stop_propagation();
519                return;
520            }
521            let items: Vec<_> = handles
522                .iter()
523                .map(|(focus, enabled)| (focus, *enabled))
524                .collect();
525            if move_roving_focus(
526                &items,
527                &event.keystroke.key,
528                Axis::Vertical,
529                direction,
530                window,
531                cx,
532            )
533            .is_some()
534            {
535                cx.stop_propagation();
536            }
537        })
538        .child(
539            Surface::new(ColorRole::SurfaceContainer)
540                .shadow_elevation(Elevation::Level2)
541                .shadow_scale(motion.scale)
542                .rounded(spacing * 0.25)
543                .min_w(dp(112.).min(available_width))
544                .max_w(dp(280.).min(available_width))
545                .py(spacing * 0.5)
546                .children(
547                    items
548                        .into_iter()
549                        .zip(focus)
550                        .map(|(item, (focus, enabled))| {
551                            if matches!(item.kind, Kind::Group) {
552                                return div()
553                                    .id(item.id)
554                                    .role(Role::Label)
555                                    .px(spacing * 0.75)
556                                    .py(spacing * 0.5)
557                                    .text_color(muted)
558                                    .child(item.label)
559                                    .into_any_element();
560                            }
561                            let action = item.action();
562                            let (role, marked) = match item.kind {
563                                Kind::Check(checked, _) => (Role::MenuItemCheckBox, checked),
564                                Kind::Select(selected, _) => (Role::MenuItem, selected),
565                                _ => (Role::MenuItem, false),
566                            };
567                            let submenu = matches!(&item.kind, Kind::Submenu(_));
568                            let row = gpui_base::Button::new(item.id.clone())
569                                .role(role)
570                                .track_focus(&focus)
571                                .disabled(!enabled)
572                                .accessibility_label(item.label.clone())
573                                .flex()
574                                .justify_start()
575                                .gap(spacing * 0.5)
576                                .w_full()
577                                .min_h(dp(48.))
578                                .line_height(dp(20.))
579                                .px(spacing * 0.75)
580                                .text_color(if !enabled {
581                                    ink.opacity(0.38)
582                                } else if marked {
583                                    selected_ink
584                                } else {
585                                    ink
586                                })
587                                .when(marked, |row| row.bg(selected_color))
588                                .when(direction == Direction::Rtl, Styled::flex_row_reverse)
589                                .when(enabled, |row| {
590                                    let background =
591                                        if marked { selected_color } else { container };
592                                    let foreground = if marked { selected_ink } else { ink };
593                                    row.hover(move |style| {
594                                        style.bg(background.blend(foreground.opacity(
595                                            gpui_material_theme::StateLayer::Hover.opacity(),
596                                        )))
597                                    })
598                                    .focus_visible(move |style| {
599                                        style.bg(background.blend(foreground.opacity(
600                                            gpui_material_theme::StateLayer::Focus.opacity(),
601                                        )))
602                                    })
603                                    .active(move |style| {
604                                        style.bg(background.blend(foreground.opacity(
605                                            gpui_material_theme::StateLayer::Pressed.opacity(),
606                                        )))
607                                    })
608                                })
609                                .when(role == Role::MenuItemCheckBox, |row| {
610                                    row.aria_toggled(if marked {
611                                        gpui::accesskit::Toggled::True
612                                    } else {
613                                        gpui::accesskit::Toggled::False
614                                    })
615                                })
616                                .when(matches!(item.kind, Kind::Select(..)), |row| {
617                                    row.aria_selected(marked)
618                                })
619                                .when(enabled && !submenu, |row| {
620                                    let activate: Action = {
621                                        let close = close.clone();
622                                        Rc::new(move |window, cx| {
623                                            close(window, cx);
624                                            if let Some(action) = &action {
625                                                action(window, cx);
626                                            }
627                                        })
628                                    };
629                                    let keyboard = activate.clone();
630                                    let accessibility = activate.clone();
631                                    row.capture_key_down(move |event, window, cx| {
632                                        if matches!(event.keystroke.key.as_str(), "enter" | "space")
633                                        {
634                                            keyboard(window, cx);
635                                            cx.stop_propagation();
636                                        }
637                                    })
638                                    .on_a11y_action(
639                                        gpui::AccessibleAction::Click,
640                                        move |_, window, cx| accessibility(window, cx),
641                                    )
642                                    .on_click(move |_, window, cx| activate(window, cx))
643                                })
644                                .child(div().w(dp(18.)).flex_none().when(marked, |slot| {
645                                    slot.child(Icon::new(IconName::Check).size(dp(18.)))
646                                }))
647                                .child(div().flex_1().min_w_0().truncate().child(item.label))
648                                .when(submenu, |row| {
649                                    row.child(
650                                        Icon::new(IconName::ChevronRight)
651                                            .size(dp(18.))
652                                            .mirror_in_rtl(true),
653                                    )
654                                });
655                            if let Kind::Submenu(children) = item.kind {
656                                Menu {
657                                    close_parent: Some(close.clone()),
658                                    enabled,
659                                    ancestor: Some(bounds.clone()),
660                                    ..Menu::new((item.id, "submenu"), row, children)
661                                        .anchor(Anchor::LeftCenter)
662                                }
663                                .into_any_element()
664                            } else {
665                                row.into_any_element()
666                            }
667                        }),
668                ),
669        );
670    super::text_style(
671        menu,
672        gpui_material_theme::TypeRole::LabelLarge,
673        motion.scale,
674        window,
675        cx,
676    )
677    .into_any_element()
678}