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};
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,
16 actions::{Cancel, Confirm},
17};
18use gpui_material_foundation::{ThemeScope, current_material_theme, logical_anchor};
19use gpui_material_theme::{CornerShape, Direction};
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
30pub struct MenuItem {
32 id: ElementId,
33 label: SharedString,
34 disabled: bool,
35 kind: Kind,
36 slots: ItemSlots,
37 on_checked_change: Option<Change>,
38 style: MenuItemStyle,
39}
40
41enum Kind {
42 Action(Option<Action>),
43 Check(bool, Option<Action>),
44 Select(bool, Option<Action>),
45 Heading,
46 Section {
47 rows: Vec<MenuItem>,
48 style: MenuSurfaceStyle,
49 inactive_shape: Option<CornerShape>,
50 },
51 Submenu(Vec<MenuItem>),
52}
53
54#[derive(Clone, Default)]
55struct ItemSlots {
56 content: Option<ItemContent>,
57 leading: Option<ItemContent>,
58 supporting: Option<ItemContent>,
59 trailing: Option<ItemContent>,
60 selection_icon: Option<ItemContent>,
61}
62
63impl ItemSlots {
64 fn label(&self, label: SharedString) -> AnyElement {
65 self.content
66 .as_ref()
67 .map_or_else(|| label.into_any_element(), |content| content())
68 }
69
70 fn children(
71 &self,
72 label: SharedString,
73 marked: bool,
74 submenu: bool,
75 paint: Paint<'_>,
76 supporting_color: gpui::Hsla,
77 ) -> Vec<AnyElement> {
78 let motion = paint.motion;
79 let icon_size = motion.px(18.);
80 let leading = if marked {
81 Some(self.selection_icon.as_ref().map_or_else(
82 || {
83 Icon::new(IconName::Check)
84 .size(icon_size)
85 .into_any_element()
86 },
87 |icon| icon(),
88 ))
89 } else {
90 self.leading.as_ref().map(|icon| icon())
91 };
92 let supporting_scale = paint.theme.typography.text_scale();
93 let body = div()
94 .flex_1()
95 .min_w_0()
96 .overflow_hidden()
97 .child(div().truncate().child(self.label(label)))
98 .children(self.supporting.as_ref().map(|supporting| {
99 div()
100 .text_size(motion.px(12. * supporting_scale))
101 .line_height(motion.px(16. * supporting_scale))
102 .text_color(supporting_color)
103 .child(supporting())
104 }));
105 let mut children = vec![
106 div()
107 .min_w(icon_size)
108 .flex_none()
109 .children(leading)
110 .into_any_element(),
111 body.into_any_element(),
112 ];
113 children.extend(self.trailing.as_ref().map(|trailing| trailing()));
114 children.extend(submenu.then(|| {
115 Icon::new(IconName::ChevronRight)
116 .size(icon_size)
117 .mirror_in_rtl(true)
118 .into_any_element()
119 }));
120 children
121 }
122}
123
124impl MenuItem {
125 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
126 Self {
127 id: id.into(),
128 label: label.into(),
129 disabled: false,
130 kind: Kind::Action(None),
131 slots: ItemSlots::default(),
132 on_checked_change: None,
133 style: MenuItemStyle::default(),
134 }
135 }
136
137 pub fn group(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
138 Self {
139 kind: Kind::Heading,
140 ..Self::new(id, title)
141 }
142 }
143
144 pub fn section(
146 id: impl Into<ElementId>,
147 name: impl Into<SharedString>,
148 rows: impl IntoIterator<Item = MenuItem>,
149 ) -> Self {
150 Self {
151 kind: Kind::Section {
152 rows: rows.into_iter().collect(),
153 style: MenuSurfaceStyle::default(),
154 inactive_shape: None,
155 },
156 ..Self::new(id, name)
157 }
158 }
159
160 pub fn group_appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
162 if let Kind::Section { style, .. } = &mut self.kind {
163 *style = appearance;
164 }
165 self
166 }
167
168 pub fn inactive_shape(mut self, shape: CornerShape) -> Self {
170 if let Kind::Section { inactive_shape, .. } = &mut self.kind {
171 *inactive_shape = Some(shape);
172 }
173 self
174 }
175
176 pub fn appearance(mut self, style: MenuItemStyle) -> Self {
178 self.style = style;
179 self
180 }
181
182 pub fn submenu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
183 self.kind = Kind::Submenu(items.into_iter().collect());
184 self
185 }
186
187 pub fn disabled(mut self, disabled: bool) -> Self {
188 self.disabled = disabled;
189 self
190 }
191
192 pub fn checked(mut self, checked: bool) -> Self {
193 self.kind = Kind::Check(checked, self.action());
194 self
195 }
196
197 pub fn selected(mut self, selected: bool) -> Self {
198 self.kind = Kind::Select(selected, self.action());
199 self
200 }
201
202 pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
205 self.slots.content = Some(Rc::new(move || build().into_any_element()));
206 self
207 }
208
209 pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
211 self.slots.leading = Some(Rc::new(move || build().into_any_element()));
212 self
213 }
214
215 pub fn supporting<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
217 self.slots.supporting = Some(Rc::new(move || build().into_any_element()));
218 self
219 }
220
221 pub fn trailing<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
223 self.slots.trailing = Some(Rc::new(move || build().into_any_element()));
224 self
225 }
226
227 pub fn selection_icon<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
229 self.slots.selection_icon = Some(Rc::new(move || build().into_any_element()));
230 self
231 }
232
233 pub fn on_checked_change(
236 mut self,
237 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
238 ) -> Self {
239 self.on_checked_change = Some(Rc::new(callback));
240 self
241 }
242
243 fn action(&self) -> Option<Action> {
244 match &self.kind {
245 Kind::Action(action) | Kind::Check(_, action) | Kind::Select(_, action) => {
246 action.clone()
247 }
248 _ => None,
249 }
250 }
251
252 fn activation(&self) -> Option<Action> {
253 if let Kind::Check(checked, _) = self.kind
254 && let Some(callback) = &self.on_checked_change
255 {
256 let callback = callback.clone();
257 return Some(Rc::new(move |window, cx| callback(!checked, window, cx)));
258 }
259 self.action()
260 }
261
262 pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
263 match &mut self.kind {
264 Kind::Action(handler) | Kind::Check(_, handler) | Kind::Select(_, handler) => {
265 *handler = Some(Rc::new(action));
266 }
267 _ => {}
268 }
269 self
270 }
271}
272
273#[derive(IntoElement)]
276pub struct Menu {
277 id: ElementId,
278 trigger: AnyElement,
279 items: Vec<MenuItem>,
280 mouse_button: MouseButton,
281 anchor: Anchor,
282 close_parent: Option<Action>,
283 enabled: bool,
284 ancestor: Option<Rc<PopupBounds>>,
285 composed_trigger: Option<ComposedTrigger>,
286 open: Option<bool>,
287 on_open_change: Option<Change>,
288 on_dismiss: Option<Action>,
289 color: MenuColor,
290 appearance: MenuSurfaceStyle,
291 decoration: Option<ItemContent>,
292 scroll: Option<ScrollHandle>,
293 offset: Pixels,
294 position: Option<Point<Pixels>>,
295}
296
297#[derive(Default)]
298struct PopupBounds {
299 trigger: Cell<Bounds<Pixels>>,
300 popup: Cell<Bounds<Pixels>>,
301 child: RefCell<Option<Rc<PopupBounds>>>,
302 presented: RefCell<Option<PresentedMenu>>,
303 scroll: ScrollHandle,
304 motion: Cell<Option<OverlayMotion>>,
305 open: Rc<Cell<bool>>,
306}
307
308#[derive(Clone)]
309struct MenuPresentation {
310 color: MenuColor,
311 appearance: MenuSurfaceStyle,
312 decoration: Option<ItemContent>,
313 scroll: ScrollHandle,
314}
315
316struct PresentedMenu {
317 items: Vec<MenuExitRow>,
318 presentation: MenuPresentation,
319}
320
321impl PopupBounds {
322 fn contains(&self, point: &Point<Pixels>) -> bool {
323 self.trigger.get().contains(point)
324 || self.popup.get().contains(point)
325 || self
326 .child
327 .borrow()
328 .as_ref()
329 .is_some_and(|child| child.open.get() && child.contains(point))
330 }
331}
332
333impl Menu {
334 pub fn new(
335 id: impl Into<ElementId>,
336 trigger: impl IntoElement,
337 items: impl IntoIterator<Item = MenuItem>,
338 ) -> Self {
339 Self {
340 id: id.into(),
341 trigger: trigger.into_any_element(),
342 items: items.into_iter().collect(),
343 mouse_button: MouseButton::Left,
344 anchor: Anchor::TopLeft,
345 close_parent: None,
346 enabled: true,
347 ancestor: None,
348 composed_trigger: None,
349 open: None,
350 on_open_change: None,
351 on_dismiss: None,
352 color: MenuColor::default(),
353 appearance: MenuSurfaceStyle::default(),
354 decoration: None,
355 scroll: None,
356 offset: px(4.),
357 position: None,
358 }
359 }
360
361 pub fn context(mut self) -> Self {
363 self.mouse_button = MouseButton::Right;
364 self
365 }
366
367 pub fn anchor(mut self, anchor: Anchor) -> Self {
368 self.anchor = anchor;
369 self
370 }
371
372 pub fn offset(mut self, offset: Pixels) -> Self {
374 if f32::from(offset).is_finite() {
375 self.offset = offset;
376 }
377 self
378 }
379
380 pub fn position(mut self, position: Point<Pixels>) -> Self {
382 self.position = (f32::from(position.x).is_finite() && f32::from(position.y).is_finite())
383 .then_some(position);
384 self
385 }
386
387 pub fn color(mut self, color: MenuColor) -> Self {
389 self.color = color;
390 self
391 }
392
393 pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
395 self.appearance = appearance;
396 self
397 }
398
399 pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
402 self.decoration = Some(Rc::new(move || build().into_any_element()));
403 self
404 }
405
406 pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
408 self.scroll = Some(scroll.clone());
409 self
410 }
411
412 pub fn composed(
417 id: impl Into<ElementId>,
418 items: impl IntoIterator<Item = MenuItem>,
419 trigger: impl FnOnce(bool, Action) -> AnyElement + 'static,
420 ) -> Self {
421 let mut menu = Self::new(id, div(), items);
422 menu.composed_trigger = Some(Box::new(trigger));
423 menu
424 }
425
426 pub fn open(mut self, open: bool) -> Self {
428 self.open = Some(open);
429 self
430 }
431
432 pub fn on_open_change(
435 mut self,
436 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
437 ) -> Self {
438 self.on_open_change = Some(Rc::new(callback));
439 self
440 }
441
442 pub fn on_dismiss(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
445 self.on_dismiss = Some(Rc::new(callback));
446 self
447 }
448}
449
450fn build_exit_branch(
451 id: &ElementId,
452 bounds: &Rc<PopupBounds>,
453 motion: OverlayMotion,
454 direction: Direction,
455 window: &Window,
456 cx: &App,
457) -> gpui::Div {
458 let mut exits = div();
461 let mut level = Some(bounds.clone());
462 let mut depth = 0;
463 while let Some(bounds) = level {
464 let Some(previous) = bounds.motion.get() else {
465 break;
466 };
467 let motion = if depth == 0 {
468 motion
469 } else {
470 OverlayMotion {
471 scale: 0.8 + (motion.scale - 0.8) * (previous.scale - 0.8) / 0.2,
472 alpha: motion.alpha * previous.alpha,
473 }
474 };
475 exits = exits.children(menu_exit(
476 (id, depth),
477 &bounds,
478 motion,
479 direction,
480 window,
481 cx,
482 ));
483 level = bounds.child.borrow().clone();
484 depth += 1;
485 }
486 exits
487}
488
489impl RenderOnce for Menu {
490 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
491 let direction = current_material_theme(window, cx).layout.direction;
492 let submenu = self.close_parent.is_some();
493 if !self.enabled {
494 return self.trigger;
495 }
496 let view = window.current_view();
497 let bounds = window
498 .use_keyed_state((self.id.clone(), "menu-bounds"), cx, |_, _| {
499 Rc::new(PopupBounds::default())
500 })
501 .read(cx)
502 .clone();
503 let open_state = bounds.open.clone();
504 let controlled = self.open.is_some();
505 let open = self.open.unwrap_or_else(|| open_state.get());
506 open_state.set(open);
507 let key_state = open_state.clone();
508 let trigger_state = open_state.clone();
509 let request: Change = {
510 let on_open_change = self.on_open_change;
511 let on_dismiss = self.on_dismiss;
512 Rc::new(move |requested, window, cx| {
513 if !controlled {
514 open_state.set(requested);
515 cx.notify(view);
516 }
517 if let Some(callback) = &on_open_change {
518 callback(requested, window, cx);
519 }
520 if !requested && let Some(callback) = &on_dismiss {
521 callback(window, cx);
522 }
523 })
524 };
525 let trigger: Action = {
526 let request = request.clone();
527 Rc::new(move |window, cx| {
528 let displayed = if controlled {
529 open
530 } else {
531 trigger_state.get()
532 };
533 request(!displayed, window, cx);
534 })
535 };
536 let key_trigger = trigger.clone();
537 let mouse_trigger = trigger.clone();
538 let popover_request = request.clone();
539 let popup_request = request;
540 let motion = OverlayMotion::sample(&self.id, open, window, cx);
541 let position = bounds.clone();
542 let ancestor = self.ancestor.clone();
543 let anchor = logical_anchor(self.anchor, direction);
544 let explicit_position = self.position;
545 let presentation = MenuPresentation {
546 color: self.color,
547 appearance: self.appearance,
548 decoration: self.decoration,
549 scroll: self.scroll.unwrap_or_else(|| bounds.scroll.clone()),
550 };
551 if open {
552 *bounds.presented.borrow_mut() = Some(PresentedMenu {
553 items: self.items.iter().map(MenuExitRow::from).collect(),
554 presentation: presentation.clone(),
555 });
556 }
557 bounds.motion.set(motion);
558 let forward = if direction == Direction::Rtl {
559 "left"
560 } else {
561 "right"
562 };
563 let exit_view = motion
564 .filter(|_| !open)
565 .map(|motion| build_exit_branch(&self.id, &bounds, motion, direction, window, cx));
566 if !open && motion.is_none() {
567 bounds.presented.borrow_mut().take();
568 bounds.child.borrow_mut().take();
569 }
570 let menu_id = self.id.clone();
571 let menu = Popover::new(self.id)
572 .open(open)
573 .on_open_change(move |open, window, cx| popover_request(*open, window, cx))
574 .anchor(anchor)
575 .offset(self.offset)
576 .mouse_button(self.mouse_button)
577 .overlay_closable(false)
578 .on_position(move |resolved, trigger| {
579 position.trigger.set(trigger);
580 if explicit_position.is_none() {
581 position.popup.set(resolved.bounds);
582 }
583 if let Some(ancestor) = &ancestor {
584 *ancestor.child.borrow_mut() = Some(position.clone());
585 }
586 })
587 .trigger_with(move |open, _, _| {
588 let content = self
589 .composed_trigger
590 .map_or(self.trigger, |build| build(open, trigger));
591 div()
592 .id("menu-trigger")
593 .role(Role::Group)
594 .aria_expanded(open)
595 .when(controlled, |trigger| {
596 trigger
599 .on_action(move |_: &Confirm, window, cx| key_trigger(window, cx))
600 .on_mouse_down(self.mouse_button, move |_, window, cx| {
601 cx.stop_propagation();
602 mouse_trigger(window, cx);
603 })
604 })
605 .on_key_down(move |event, _, cx| {
606 if submenu && event.keystroke.key == forward && !key_state.get() {
607 key_state.set(true);
608 cx.notify(view);
609 cx.stop_propagation();
610 }
611 })
612 .child(content)
613 .into_any_element()
614 })
615 .content(move |state, window, cx| {
616 let motion = motion.expect("open menu has motion");
617 let close_level: Action = if controlled {
618 Rc::new(move |window, cx| popup_request(false, window, cx))
619 } else {
620 let own = cx.entity().downgrade();
621 Rc::new(move |window, cx| {
622 let _ = own.update(cx, |state: &mut PopoverState, cx| {
623 state.dismiss(window, cx);
624 });
625 })
626 };
627 let close: Action = {
628 let close_level = close_level.clone();
629 Rc::new(move |window, cx| {
630 close_level(window, cx);
631 if let Some(close_parent) = &self.close_parent {
632 close_parent(window, cx);
633 }
634 })
635 };
636 let dismissal = close_level.clone();
637 let escape = close_level.clone();
638 let item_bounds = bounds.clone();
639 let content = window.with_id(menu_id, |window| {
640 menu_content(
641 self.items,
642 close,
643 submenu.then_some(close_level),
644 state.focus_handle(cx),
645 (direction, bounds.clone(), presentation, motion),
646 window,
647 cx,
648 )
649 });
650 let popup = div()
651 .id("dismiss-menu")
652 .opacity(motion.alpha)
653 .when(controlled, |popup| {
654 popup.on_action(move |_: &Cancel, window, cx| escape(window, cx))
655 })
656 .on_mouse_down_out(move |event, window, cx| {
657 let point = &event.position;
658 if bounds.contains(point) {
659 return;
660 }
661 dismissal(window, cx);
662 })
663 .child(content);
664 let pivot = item_bounds.clone();
665 let overlay = ScaledOverlay::new(popup, motion, move |menu| {
666 menu_pivot(menu, pivot.trigger.get())
667 });
668 let overlay = ThemeScope::inherit(overlay, window, cx);
669 if let Some(position) = explicit_position {
670 Positioner::corner(anchor, position)
671 .on_position(move |resolved| item_bounds.popup.set(resolved.bounds))
672 .occlude()
673 .child(overlay)
674 .into_any_element()
675 } else {
676 overlay
677 }
678 });
679 div()
680 .relative()
681 .child(menu)
682 .children(exit_view)
683 .into_any_element()
684 }
685}