Skip to main content

gpui_material_components/overlay/
menu.rs

1use std::rc::Rc;
2
3use gpui::{
4    Anchor, AnyElement, App, ElementId, IntoElement, MouseButton, ParentElement, Pixels, Point,
5    RenderOnce, ScrollHandle, Styled, Window, div, px,
6};
7use gpui_material_foundation::{OverlayMotion, current_material_theme, logical_anchor};
8
9pub use crate::menu_appearance::{MenuColor, MenuItemStyle, MenuSurfaceStyle};
10
11mod content;
12mod exit;
13mod item;
14mod popup;
15mod state;
16
17pub use item::MenuItem;
18
19use exit::build_exit_branch;
20use item::{Action, Change, ComposedTrigger, ItemContent, MenuItems};
21use popup::{PopupHostConfig, render_popup_host};
22use state::{MenuPresentation, PopupBounds};
23
24/// Positions a Material menu against a caller-owned, keyboard-focusable trigger.
25/// Pointer and keyboard activation use the same Base popover focus lifecycle.
26#[derive(IntoElement)]
27pub struct Menu {
28    id: ElementId,
29    trigger: AnyElement,
30    items: MenuItems,
31    mouse_button: MouseButton,
32    anchor: Anchor,
33    close_parent: Option<Action>,
34    enabled: bool,
35    ancestor: Option<Rc<PopupBounds>>,
36    composed_trigger: Option<ComposedTrigger>,
37    open: Option<bool>,
38    on_open_change: Option<Change>,
39    on_dismiss_request: Option<Action>,
40    color: MenuColor,
41    appearance: MenuSurfaceStyle,
42    decoration: Option<ItemContent>,
43    scroll: Option<ScrollHandle>,
44    offset: Pixels,
45    position: Option<Point<Pixels>>,
46}
47
48impl Menu {
49    /// Creates a menu anchored to `trigger` with eagerly constructed items.
50    pub fn new(
51        id: impl Into<ElementId>,
52        trigger: impl IntoElement,
53        items: impl IntoIterator<Item = MenuItem>,
54    ) -> Self {
55        Self::with_items(
56            id.into(),
57            trigger.into_any_element(),
58            MenuItems::Eager(items.into_iter().collect()),
59        )
60    }
61
62    /// Creates a menu whose items are built lazily only while the menu is open.
63    pub fn new_with<I>(
64        id: impl Into<ElementId>,
65        trigger: impl IntoElement,
66        build: impl FnOnce(&mut Window, &mut App) -> I + 'static,
67    ) -> Self
68    where
69        I: IntoIterator<Item = MenuItem>,
70    {
71        Self::with_items(
72            id.into(),
73            trigger.into_any_element(),
74            MenuItems::Lazy(Box::new(move |window, cx| {
75                build(window, cx).into_iter().collect()
76            })),
77        )
78    }
79
80    fn with_items(id: ElementId, trigger: AnyElement, items: MenuItems) -> Self {
81        Self {
82            id,
83            trigger,
84            items,
85            mouse_button: MouseButton::Left,
86            anchor: Anchor::TopLeft,
87            close_parent: None,
88            enabled: true,
89            ancestor: None,
90            composed_trigger: None,
91            open: None,
92            on_open_change: None,
93            on_dismiss_request: None,
94            color: MenuColor::default(),
95            appearance: MenuSurfaceStyle::default(),
96            decoration: None,
97            scroll: None,
98            offset: px(4.),
99            position: None,
100        }
101    }
102
103    /// Disables menu activation while continuing to render the trigger element.
104    pub fn disabled(mut self, disabled: bool) -> Self {
105        self.enabled = !disabled;
106        self
107    }
108
109    /// Opens on secondary click at the pointer location (viewport-clamped), or
110    /// anchored to the trigger on `Shift+F10` / `ContextMenu`, without hijacking
111    /// the trigger's own `Enter` or `Space` activation.
112    pub fn context(mut self) -> Self {
113        self.mouse_button = MouseButton::Right;
114        self
115    }
116
117    /// Sets the anchor corner used to align the popup against its trigger (default [`Anchor::TopLeft`]).
118    pub fn anchor(mut self, anchor: Anchor) -> Self {
119        self.anchor = anchor;
120        self
121    }
122
123    /// Sets the outward gap between the trigger and popup.
124    pub fn offset(mut self, offset: Pixels) -> Self {
125        if f32::from(offset).is_finite() {
126            self.offset = offset;
127        }
128        self
129    }
130
131    /// Anchors the popup at a window-local point. It remains clamped to the viewport.
132    pub fn position(mut self, position: Point<Pixels>) -> Self {
133        self.position = (f32::from(position.x).is_finite() && f32::from(position.y).is_finite())
134            .then_some(position);
135        self
136    }
137
138    /// Applies a semantic color preset to the menu and its submenus.
139    pub fn color(mut self, color: MenuColor) -> Self {
140        self.color = color;
141        self
142    }
143
144    /// Applies overrides to this popup's surface.
145    pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
146        self.appearance = appearance;
147        self
148    }
149
150    /// Renders arbitrary content before the menu rows. Use a repeatable factory
151    /// for content that also needs to appear during exit.
152    pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
153        self.decoration = Some(Rc::new(move || build().into_any_element()));
154        self
155    }
156
157    /// Tracks the popup's scrolling through a caller-owned handle.
158    pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
159        self.scroll = Some(scroll.clone());
160        self
161    }
162
163    /// Builds a trigger from the displayed open value and its activation callback.
164    ///
165    /// Keep the trigger focusable and use the supplied callback for a custom
166    /// accessibility action. The menu owns pointer and keyboard activation.
167    pub fn composed(
168        id: impl Into<ElementId>,
169        items: impl IntoIterator<Item = MenuItem>,
170        trigger: impl FnOnce(bool, Action) -> AnyElement + 'static,
171    ) -> Self {
172        let mut menu = Self::new(id, div(), items);
173        menu.composed_trigger = Some(Box::new(trigger));
174        menu
175    }
176
177    /// Sets the displayed open value from caller-owned state.
178    pub fn open(mut self, open: bool) -> Self {
179        self.open = Some(open);
180        self
181    }
182
183    /// Receives user requests to open or close the menu. In controlled mode,
184    /// apply the requested value and render with `open` to accept a request.
185    pub fn on_open_change(
186        mut self,
187        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
188    ) -> Self {
189        self.on_open_change = Some(Rc::new(callback));
190        self
191    }
192
193    /// Receives a user request to close. Setting `open(false)` externally
194    /// synchronizes the menu without running this callback.
195    pub fn on_dismiss_request(
196        mut self,
197        callback: impl Fn(&mut Window, &mut App) + 'static,
198    ) -> Self {
199        self.on_dismiss_request = Some(Rc::new(callback));
200        self
201    }
202}
203
204impl RenderOnce for Menu {
205    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
206        if !self.enabled {
207            return match self.composed_trigger {
208                Some(build) => build(false, Rc::new(|_, _| {})),
209                None => self.trigger,
210            };
211        }
212        let direction = current_material_theme(window, cx).layout.direction;
213        let submenu = self.close_parent.is_some();
214        let is_context = self.mouse_button == MouseButton::Right;
215        let view = window.current_view();
216        let bounds = window
217            .use_keyed_state((self.id.clone(), "menu-bounds"), cx, |_, _| {
218                Rc::new(PopupBounds::default())
219            })
220            .read(cx)
221            .clone();
222        let open_state = bounds.open.clone();
223        let controlled = self.open.is_some();
224        let open = self.open.unwrap_or_else(|| open_state.get());
225        open_state.set(open);
226        let sibling_close: Action = {
227            let on_open_change = self.on_open_change.clone();
228            Rc::new(move |window, cx| {
229                if !controlled {
230                    cx.notify(view);
231                } else if let Some(callback) = &on_open_change {
232                    callback(false, window, cx);
233                }
234            })
235        };
236        *bounds.close_handler.borrow_mut() = Some(sibling_close);
237        let request: Change = {
238            let on_open_change = self.on_open_change;
239            let on_dismiss_request = self.on_dismiss_request;
240            let ancestor = self.ancestor.clone();
241            let bounds = bounds.clone();
242            Rc::new(move |requested, window, cx| {
243                if requested && let Some(ancestor) = &ancestor {
244                    ancestor.activate_child(&bounds, window, cx);
245                }
246                if !controlled {
247                    open_state.set(requested);
248                    cx.notify(view);
249                }
250                if let Some(callback) = &on_open_change {
251                    callback(requested, window, cx);
252                }
253                if !requested && let Some(callback) = &on_dismiss_request {
254                    callback(window, cx);
255                }
256            })
257        };
258        let motion = OverlayMotion::sample(&self.id, open, window, cx);
259        let anchor = logical_anchor(self.anchor, direction);
260        if !open && motion.is_none() {
261            bounds.presented.borrow_mut().take();
262            bounds.child.borrow_mut().take();
263            bounds.context_position.set(None);
264        }
265        let explicit_position = self
266            .position
267            .or_else(|| is_context.then(|| bounds.context_position.get()).flatten());
268        let presentation = MenuPresentation {
269            color: self.color,
270            appearance: self.appearance,
271            decoration: self.decoration,
272            scroll: self.scroll.unwrap_or_else(|| bounds.scroll.clone()),
273        };
274        let resolved_items = open.then(|| self.items.resolve(window, cx));
275        if let Some(items) = resolved_items.as_ref()
276            && !cx.reduce_motion()
277        {
278            bounds.sync_presented(items, &presentation);
279        }
280        bounds.motion.set(motion);
281        let exit_view = motion
282            .filter(|_| !open)
283            .map(|motion| build_exit_branch(&self.id, &bounds, motion, direction, window, cx));
284        let menu_element = render_popup_host(
285            PopupHostConfig {
286                id: self.id,
287                trigger: self.trigger,
288                composed_trigger: self.composed_trigger,
289                items: resolved_items,
290                mouse_button: self.mouse_button,
291                anchor,
292                offset: self.offset,
293                explicit_position,
294                open,
295                controlled,
296                submenu,
297                direction,
298                motion,
299                presentation,
300                bounds,
301                ancestor: self.ancestor,
302                close_parent: self.close_parent,
303                request,
304                view,
305            },
306            window,
307            cx,
308        );
309        div()
310            .relative()
311            .child(menu_element)
312            .children(exit_view)
313            .into_any_element()
314    }
315}