Skip to main content

gpui_material_components/overlay/
menu.rs

1use std::cell::{Cell, RefCell};
2use std::rc::Rc;
3
4use crate::menu_appearance::Paint;
5pub use crate::menu_appearance::{MenuColor, MenuItemStyle, MenuSurfaceStyle};
6
7use crate::motion::{OverlayMotion, ScaledOverlay, menu_pivot};
8use crate::{Icon, IconName, SemanticTone};
9use gpui::{
10    Anchor, AnyElement, App, Bounds, ElementId, Focusable, InteractiveElement, IntoElement,
11    MouseButton, ParentElement, Pixels, Point, RenderOnce, Role, ScrollHandle, SharedString,
12    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
13};
14use gpui_base::{
15    Popover, PopoverState, Positioner, TestSupportExt,
16    actions::{Cancel, Confirm},
17};
18use gpui_material_foundation::{ThemeScope, current_material_theme, logical_anchor};
19use gpui_material_theme::{CornerShape, Direction, TypeRole, TypographyEmphasis};
20
21mod content;
22
23use content::{MenuExitRow, menu_content, menu_exit};
24
25type Action = Rc<dyn Fn(&mut Window, &mut App)>;
26type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
27type ItemContent = Rc<dyn Fn() -> AnyElement>;
28type ComposedTrigger = Box<dyn FnOnce(bool, Action) -> AnyElement>;
29
30/// An item in a Material menu. Callers retain command and selection state.
31pub struct MenuItem {
32    id: ElementId,
33    label: SharedString,
34    disabled: bool,
35    kind: Kind,
36    slots: ItemSlots,
37    on_checked_change: Option<Change>,
38    tone: SemanticTone,
39    style: MenuItemStyle,
40}
41
42enum Kind {
43    Action(Option<Action>),
44    Check(bool, Option<Action>),
45    Select(bool, Option<Action>),
46    Heading,
47    Divider,
48    Section {
49        rows: Vec<MenuItem>,
50        style: MenuSurfaceStyle,
51        inactive_shape: Option<CornerShape>,
52    },
53    Submenu(Vec<MenuItem>),
54}
55
56#[derive(Clone, Default)]
57struct ItemSlots {
58    content: Option<ItemContent>,
59    leading: Option<ItemContent>,
60    supporting: Option<ItemContent>,
61    trailing: Option<ItemContent>,
62    shortcut: Option<SharedString>,
63    selection_icon: Option<ItemContent>,
64}
65
66impl ItemSlots {
67    fn label(&self, label: SharedString) -> AnyElement {
68        self.content
69            .as_ref()
70            .map_or_else(|| label.into_any_element(), |content| content())
71    }
72
73    fn children(
74        &self,
75        label: SharedString,
76        marked: bool,
77        submenu: bool,
78        paint: Paint<'_>,
79        (supporting_color, shortcut_color): (gpui::Hsla, gpui::Hsla),
80        active: bool,
81    ) -> Vec<AnyElement> {
82        let motion = paint.motion;
83        let icon_size = motion.px(18.);
84        let leading = if marked {
85            Some(self.selection_icon.as_ref().map_or_else(
86                || {
87                    Icon::new(IconName::Check)
88                        .size(icon_size)
89                        .into_any_element()
90                },
91                |icon| icon(),
92            ))
93        } else {
94            self.leading.as_ref().map(|icon| icon())
95        };
96        let supporting_scale = paint.theme.typography.text_scale();
97        let body = div()
98            .flex_1()
99            .min_w_0()
100            .overflow_hidden()
101            .child(div().truncate().child(self.label(label)))
102            .children(self.supporting.as_ref().map(|supporting| {
103                div()
104                    .text_size(motion.px(12. * supporting_scale))
105                    .line_height(motion.px(16. * supporting_scale))
106                    .text_color(supporting_color)
107                    .child(supporting())
108            }));
109        let mut children = vec![
110            div()
111                .min_w(icon_size)
112                .flex_none()
113                .children(leading)
114                .into_any_element(),
115            body.into_any_element(),
116        ];
117        if let Some(trailing) = self.trailing.as_ref() {
118            children.push(trailing());
119        } else if let Some(shortcut) = self.shortcut.as_ref().filter(|text| !text.is_empty()) {
120            let label_small = paint
121                .theme
122                .typography
123                .scale_style(TypeRole::LabelSmall.style(TypographyEmphasis::Baseline));
124            let hint = div()
125                .flex_none()
126                .text_size(motion.px(label_small.size))
127                .line_height(motion.px(label_small.line_height))
128                .text_color(shortcut_color)
129                .child(shortcut.clone());
130            children.push(if active {
131                hint.id("shortcut").test_support().into_any_element()
132            } else {
133                hint.into_any_element()
134            });
135        }
136        children.extend(submenu.then(|| {
137            Icon::new(IconName::ChevronRight)
138                .size(icon_size)
139                .mirror_in_rtl(true)
140                .into_any_element()
141        }));
142        children
143    }
144}
145
146impl MenuItem {
147    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
148        Self {
149            id: id.into(),
150            label: label.into(),
151            disabled: false,
152            kind: Kind::Action(None),
153            slots: ItemSlots::default(),
154            on_checked_change: None,
155            tone: SemanticTone::Default,
156            style: MenuItemStyle::default(),
157        }
158    }
159
160    pub fn group(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
161        Self {
162            kind: Kind::Heading,
163            ..Self::new(id, title)
164        }
165    }
166
167    /// Creates a non-interactive horizontal divider row inside a menu that is
168    /// skipped by keyboard navigation.
169    pub fn divider(id: impl Into<ElementId>) -> Self {
170        Self {
171            kind: Kind::Divider,
172            ..Self::new(id, "")
173        }
174    }
175
176    /// Creates a surfaced group with rows in the owning menu's navigation order.
177    pub fn section(
178        id: impl Into<ElementId>,
179        name: impl Into<SharedString>,
180        rows: impl IntoIterator<Item = MenuItem>,
181    ) -> Self {
182        Self {
183            kind: Kind::Section {
184                rows: rows.into_iter().collect(),
185                style: MenuSurfaceStyle::default(),
186                inactive_shape: None,
187            },
188            ..Self::new(id, name)
189        }
190    }
191
192    /// Sets the styled section's surface appearance.
193    pub fn group_appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
194        if let Kind::Section { style, .. } = &mut self.kind {
195            *style = appearance;
196        }
197        self
198    }
199
200    /// Sets the section shape used after the pointer leaves the section.
201    pub fn inactive_shape(mut self, shape: CornerShape) -> Self {
202        if let Kind::Section { inactive_shape, .. } = &mut self.kind {
203            *inactive_shape = Some(shape);
204        }
205        self
206    }
207
208    /// Configures the appearance of an action, checked or selected row.
209    pub fn appearance(mut self, style: MenuItemStyle) -> Self {
210        self.style = style;
211        self
212    }
213
214    /// Applies a Material 3 semantic tone to this row's foreground and selected roles.
215    /// Explicit [`MenuItemStyle`] overrides and disabled styling still take precedence.
216    pub fn tone(mut self, tone: SemanticTone) -> Self {
217        self.tone = tone;
218        self
219    }
220
221    /// Shorthand for `.tone(SemanticTone::Danger)` on destructive menu commands.
222    pub fn destructive(self) -> Self {
223        self.tone(SemanticTone::Danger)
224    }
225
226    /// Renders a desktop shortcut hint in the trailing slot using `LabelSmall`
227    /// and `OnSurfaceVariant` (or disabled color when disabled), unless an
228    /// explicit `.trailing(...)` overrides it.
229    pub fn shortcut(mut self, text: impl Into<SharedString>) -> Self {
230        self.slots.shortcut = Some(text.into());
231        self
232    }
233
234    pub fn submenu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
235        self.kind = Kind::Submenu(items.into_iter().collect());
236        self
237    }
238
239    pub fn disabled(mut self, disabled: bool) -> Self {
240        self.disabled = disabled;
241        self
242    }
243
244    pub fn checked(mut self, checked: bool) -> Self {
245        self.kind = Kind::Check(checked, self.action());
246        self
247    }
248
249    pub fn selected(mut self, selected: bool) -> Self {
250        self.kind = Kind::Select(selected, self.action());
251        self
252    }
253
254    /// Replaces the visible label while retaining the name passed to `new`.
255    /// Supply a repeatable factory so the content also appears during exit.
256    pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
257        self.slots.content = Some(Rc::new(move || build().into_any_element()));
258        self
259    }
260
261    /// Supplies a decorative element at the logical start of an unmarked row.
262    pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
263        self.slots.leading = Some(Rc::new(move || build().into_any_element()));
264        self
265    }
266
267    /// Supplies additional visual content below the label.
268    pub fn supporting<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
269        self.slots.supporting = Some(Rc::new(move || build().into_any_element()));
270        self
271    }
272
273    /// Supplies decorative content at the logical end of the row.
274    pub fn trailing<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
275        self.slots.trailing = Some(Rc::new(move || build().into_any_element()));
276        self
277    }
278
279    /// Replaces the leading check mark of a checked or selected row.
280    pub fn selection_icon<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
281        self.slots.selection_icon = Some(Rc::new(move || build().into_any_element()));
282        self
283    }
284
285    /// Requests the inverse of the supplied checked value on activation.
286    /// The checked callback takes precedence over `on_activate` on checked rows.
287    pub fn on_checked_change(
288        mut self,
289        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
290    ) -> Self {
291        self.on_checked_change = Some(Rc::new(callback));
292        self
293    }
294
295    fn action(&self) -> Option<Action> {
296        match &self.kind {
297            Kind::Action(action) | Kind::Check(_, action) | Kind::Select(_, action) => {
298                action.clone()
299            }
300            _ => None,
301        }
302    }
303
304    fn activation(&self) -> Option<Action> {
305        if let Kind::Check(checked, _) = self.kind
306            && let Some(callback) = &self.on_checked_change
307        {
308            let callback = callback.clone();
309            return Some(Rc::new(move |window, cx| callback(!checked, window, cx)));
310        }
311        self.action()
312    }
313
314    pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
315        match &mut self.kind {
316            Kind::Action(handler) | Kind::Check(_, handler) | Kind::Select(_, handler) => {
317                *handler = Some(Rc::new(action));
318            }
319            _ => {}
320        }
321        self
322    }
323}
324
325/// Positions a Material menu against a caller-owned, keyboard-focusable trigger.
326/// Pointer and keyboard activation use the same Base popover focus lifecycle.
327#[derive(IntoElement)]
328pub struct Menu {
329    id: ElementId,
330    trigger: AnyElement,
331    items: Vec<MenuItem>,
332    mouse_button: MouseButton,
333    anchor: Anchor,
334    close_parent: Option<Action>,
335    enabled: bool,
336    ancestor: Option<Rc<PopupBounds>>,
337    composed_trigger: Option<ComposedTrigger>,
338    open: Option<bool>,
339    on_open_change: Option<Change>,
340    on_dismiss: Option<Action>,
341    color: MenuColor,
342    appearance: MenuSurfaceStyle,
343    decoration: Option<ItemContent>,
344    scroll: Option<ScrollHandle>,
345    offset: Pixels,
346    position: Option<Point<Pixels>>,
347}
348
349#[derive(Default)]
350struct PopupBounds {
351    trigger: Cell<Bounds<Pixels>>,
352    popup: Cell<Bounds<Pixels>>,
353    child: RefCell<Option<Rc<PopupBounds>>>,
354    presented: RefCell<Option<PresentedMenu>>,
355    scroll: ScrollHandle,
356    motion: Cell<Option<OverlayMotion>>,
357    open: Rc<Cell<bool>>,
358}
359
360#[derive(Clone)]
361struct MenuPresentation {
362    color: MenuColor,
363    appearance: MenuSurfaceStyle,
364    decoration: Option<ItemContent>,
365    scroll: ScrollHandle,
366}
367
368struct PresentedMenu {
369    items: Rc<[MenuExitRow]>,
370    presentation: MenuPresentation,
371}
372
373impl PopupBounds {
374    fn contains(&self, point: &Point<Pixels>) -> bool {
375        self.trigger.get().contains(point)
376            || self.popup.get().contains(point)
377            || self
378                .child
379                .borrow()
380                .as_ref()
381                .is_some_and(|child| child.open.get() && child.contains(point))
382    }
383}
384
385impl Menu {
386    pub fn new(
387        id: impl Into<ElementId>,
388        trigger: impl IntoElement,
389        items: impl IntoIterator<Item = MenuItem>,
390    ) -> Self {
391        Self {
392            id: id.into(),
393            trigger: trigger.into_any_element(),
394            items: items.into_iter().collect(),
395            mouse_button: MouseButton::Left,
396            anchor: Anchor::TopLeft,
397            close_parent: None,
398            enabled: true,
399            ancestor: None,
400            composed_trigger: None,
401            open: None,
402            on_open_change: None,
403            on_dismiss: None,
404            color: MenuColor::default(),
405            appearance: MenuSurfaceStyle::default(),
406            decoration: None,
407            scroll: None,
408            offset: px(4.),
409            position: None,
410        }
411    }
412
413    /// Opens on secondary click; Enter and Space still work on the trigger.
414    pub fn context(mut self) -> Self {
415        self.mouse_button = MouseButton::Right;
416        self
417    }
418
419    pub fn anchor(mut self, anchor: Anchor) -> Self {
420        self.anchor = anchor;
421        self
422    }
423
424    /// Sets the outward gap between the trigger and popup.
425    pub fn offset(mut self, offset: Pixels) -> Self {
426        if f32::from(offset).is_finite() {
427            self.offset = offset;
428        }
429        self
430    }
431
432    /// Anchors the popup at a window-local point. It remains clamped to the viewport.
433    pub fn position(mut self, position: Point<Pixels>) -> Self {
434        self.position = (f32::from(position.x).is_finite() && f32::from(position.y).is_finite())
435            .then_some(position);
436        self
437    }
438
439    /// Applies a semantic color preset to the menu and its submenus.
440    pub fn color(mut self, color: MenuColor) -> Self {
441        self.color = color;
442        self
443    }
444
445    /// Applies overrides to this popup's surface.
446    pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
447        self.appearance = appearance;
448        self
449    }
450
451    /// Renders arbitrary content before the menu rows. Use a repeatable factory
452    /// for content that also needs to appear during exit.
453    pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
454        self.decoration = Some(Rc::new(move || build().into_any_element()));
455        self
456    }
457
458    /// Tracks the popup's scrolling through a caller-owned handle.
459    pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
460        self.scroll = Some(scroll.clone());
461        self
462    }
463
464    /// Builds a trigger from the displayed open value and its activation callback.
465    ///
466    /// Keep the trigger focusable and use the supplied callback for a custom
467    /// accessibility action. The menu owns pointer and keyboard activation.
468    pub fn composed(
469        id: impl Into<ElementId>,
470        items: impl IntoIterator<Item = MenuItem>,
471        trigger: impl FnOnce(bool, Action) -> AnyElement + 'static,
472    ) -> Self {
473        let mut menu = Self::new(id, div(), items);
474        menu.composed_trigger = Some(Box::new(trigger));
475        menu
476    }
477
478    /// Sets the displayed open value from caller-owned state.
479    pub fn open(mut self, open: bool) -> Self {
480        self.open = Some(open);
481        self
482    }
483
484    /// Receives user requests to open or close the menu. In controlled mode,
485    /// apply the requested value and render with `open` to accept a request.
486    pub fn on_open_change(
487        mut self,
488        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
489    ) -> Self {
490        self.on_open_change = Some(Rc::new(callback));
491        self
492    }
493
494    /// Receives a user request to close. Setting `open(false)` externally
495    /// synchronizes the menu without running this callback.
496    pub fn on_dismiss(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
497        self.on_dismiss = Some(Rc::new(callback));
498        self
499    }
500}
501
502fn build_exit_branch(
503    id: &ElementId,
504    bounds: &Rc<PopupBounds>,
505    motion: OverlayMotion,
506    direction: Direction,
507    window: &Window,
508    cx: &App,
509) -> gpui::Div {
510    // Closing the parent removes Base's nested popup hosts immediately.
511    // Use the last presented branch to finish their own visual exits.
512    let mut exits = div();
513    let mut level = Some(bounds.clone());
514    let mut depth = 0;
515    while let Some(bounds) = level {
516        let Some(previous) = bounds.motion.get() else {
517            break;
518        };
519        let motion = if depth == 0 {
520            motion
521        } else {
522            OverlayMotion {
523                scale: 0.8 + (motion.scale - 0.8) * (previous.scale - 0.8) / 0.2,
524                alpha: motion.alpha * previous.alpha,
525            }
526        };
527        exits = exits.children(menu_exit(
528            (id, depth),
529            &bounds,
530            motion,
531            direction,
532            window,
533            cx,
534        ));
535        level = bounds.child.borrow().clone();
536        depth += 1;
537    }
538    exits
539}
540
541impl RenderOnce for Menu {
542    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
543        let direction = current_material_theme(window, cx).layout.direction;
544        let submenu = self.close_parent.is_some();
545        if !self.enabled {
546            return self.trigger;
547        }
548        let view = window.current_view();
549        let bounds = window
550            .use_keyed_state((self.id.clone(), "menu-bounds"), cx, |_, _| {
551                Rc::new(PopupBounds::default())
552            })
553            .read(cx)
554            .clone();
555        let open_state = bounds.open.clone();
556        let controlled = self.open.is_some();
557        let open = self.open.unwrap_or_else(|| open_state.get());
558        open_state.set(open);
559        let key_state = open_state.clone();
560        let trigger_state = open_state.clone();
561        let request: Change = {
562            let on_open_change = self.on_open_change;
563            let on_dismiss = self.on_dismiss;
564            Rc::new(move |requested, window, cx| {
565                if !controlled {
566                    open_state.set(requested);
567                    cx.notify(view);
568                }
569                if let Some(callback) = &on_open_change {
570                    callback(requested, window, cx);
571                }
572                if !requested && let Some(callback) = &on_dismiss {
573                    callback(window, cx);
574                }
575            })
576        };
577        let trigger: Action = {
578            let request = request.clone();
579            Rc::new(move |window, cx| {
580                let displayed = if controlled {
581                    open
582                } else {
583                    trigger_state.get()
584                };
585                request(!displayed, window, cx);
586            })
587        };
588        let key_trigger = trigger.clone();
589        let mouse_trigger = trigger.clone();
590        let popover_request = request.clone();
591        let popup_request = request;
592        let motion = OverlayMotion::sample(&self.id, open, window, cx);
593        let position = bounds.clone();
594        let ancestor = self.ancestor.clone();
595        let anchor = logical_anchor(self.anchor, direction);
596        let explicit_position = self.position;
597        let presentation = MenuPresentation {
598            color: self.color,
599            appearance: self.appearance,
600            decoration: self.decoration,
601            scroll: self.scroll.unwrap_or_else(|| bounds.scroll.clone()),
602        };
603        if open && !cx.reduce_motion() {
604            *bounds.presented.borrow_mut() = Some(PresentedMenu {
605                items: self.items.iter().map(MenuExitRow::from).collect(),
606                presentation: presentation.clone(),
607            });
608        }
609        bounds.motion.set(motion);
610        let forward = if direction == Direction::Rtl {
611            "left"
612        } else {
613            "right"
614        };
615        let exit_view = motion
616            .filter(|_| !open)
617            .map(|motion| build_exit_branch(&self.id, &bounds, motion, direction, window, cx));
618        if !open && motion.is_none() {
619            bounds.presented.borrow_mut().take();
620            bounds.child.borrow_mut().take();
621        }
622        let menu_id = self.id.clone();
623        let menu = Popover::new(self.id)
624            .open(open)
625            .on_open_change(move |open, window, cx| popover_request(*open, window, cx))
626            .anchor(anchor)
627            .offset(self.offset)
628            .mouse_button(self.mouse_button)
629            .overlay_closable(false)
630            .on_position(move |resolved, trigger| {
631                position.trigger.set(trigger);
632                if explicit_position.is_none() {
633                    position.popup.set(resolved.bounds);
634                }
635                if let Some(ancestor) = &ancestor {
636                    *ancestor.child.borrow_mut() = Some(position.clone());
637                }
638            })
639            .trigger_with(move |open, _, _| {
640                let content = self
641                    .composed_trigger
642                    .map_or(self.trigger, |build| build(open, trigger));
643                div()
644                    .id("menu-trigger")
645                    .role(Role::Group)
646                    .aria_expanded(open)
647                    .when(controlled, |trigger| {
648                        // Accepting the request through Popover::open applies
649                        // the Base focus lifecycle only after the owner agrees.
650                        trigger
651                            .on_action(move |_: &Confirm, window, cx| key_trigger(window, cx))
652                            .on_mouse_down(self.mouse_button, move |_, window, cx| {
653                                cx.stop_propagation();
654                                mouse_trigger(window, cx);
655                            })
656                    })
657                    .on_key_down(move |event, _, cx| {
658                        if submenu && event.keystroke.key == forward && !key_state.get() {
659                            key_state.set(true);
660                            cx.notify(view);
661                            cx.stop_propagation();
662                        }
663                    })
664                    .child(content)
665                    .into_any_element()
666            })
667            .content(move |state, window, cx| {
668                let motion = motion.expect("open menu has motion");
669                let close_level: Action = if controlled {
670                    Rc::new(move |window, cx| popup_request(false, window, cx))
671                } else {
672                    let own = cx.entity().downgrade();
673                    Rc::new(move |window, cx| {
674                        let _ = own.update(cx, |state: &mut PopoverState, cx| {
675                            state.dismiss(window, cx);
676                        });
677                    })
678                };
679                let close: Action = {
680                    let close_level = close_level.clone();
681                    Rc::new(move |window, cx| {
682                        close_level(window, cx);
683                        if let Some(close_parent) = &self.close_parent {
684                            close_parent(window, cx);
685                        }
686                    })
687                };
688                let dismissal = close_level.clone();
689                let escape = close_level.clone();
690                let item_bounds = bounds.clone();
691                let content = window.with_id(menu_id, |window| {
692                    menu_content(
693                        self.items,
694                        close,
695                        submenu.then_some(close_level),
696                        state.focus_handle(cx),
697                        (direction, bounds.clone(), presentation, motion),
698                        window,
699                        cx,
700                    )
701                });
702                let popup = div()
703                    .id("dismiss-menu")
704                    .opacity(motion.alpha)
705                    .when(controlled, |popup| {
706                        popup.on_action(move |_: &Cancel, window, cx| escape(window, cx))
707                    })
708                    .on_mouse_down_out(move |event, window, cx| {
709                        let point = &event.position;
710                        if bounds.contains(point) {
711                            return;
712                        }
713                        dismissal(window, cx);
714                    })
715                    .child(content);
716                let pivot = item_bounds.clone();
717                let overlay = ScaledOverlay::new(popup, motion, move |menu| {
718                    menu_pivot(menu, pivot.trigger.get())
719                });
720                let overlay = ThemeScope::inherit(overlay, window, cx);
721                if let Some(position) = explicit_position {
722                    Positioner::corner(anchor, position)
723                        .on_position(move |resolved| item_bounds.popup.set(resolved.bounds))
724                        .occlude()
725                        .child(overlay)
726                        .into_any_element()
727                } else {
728                    overlay
729                }
730            });
731        div()
732            .relative()
733            .child(menu)
734            .children(exit_view)
735            .into_any_element()
736    }
737}