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, FocusHandle, Focusable, InteractiveElement,
11 IntoElement, MouseButton, ParentElement, Pixels, Point, RenderOnce, Role, ScrollHandle,
12 SharedString, Size, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder,
13 px,
14};
15use gpui_base::{
16 Popover, PopoverState, Popup, Positioner, TestSupportExt,
17 actions::{Cancel, Confirm},
18};
19use gpui_material_foundation::{ThemeScope, current_material_theme, logical_anchor};
20use gpui_material_theme::{CornerShape, Direction, TypeRole, TypographyEmphasis};
21
22mod content;
23
24use content::{MenuExitRow, menu_content, menu_exit};
25
26type Action = Rc<dyn Fn(&mut Window, &mut App)>;
27type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
28type ItemContent = Rc<dyn Fn() -> AnyElement>;
29type ComposedTrigger = Box<dyn FnOnce(bool, Action) -> AnyElement>;
30type LazyItems = Box<dyn FnOnce(&mut Window, &mut App) -> Vec<MenuItem>>;
31
32enum MenuItems {
33 Eager(Vec<MenuItem>),
34 Lazy(LazyItems),
35}
36
37impl MenuItems {
38 fn resolve(self, window: &mut Window, cx: &mut App) -> Vec<MenuItem> {
39 match self {
40 Self::Eager(items) => items,
41 Self::Lazy(build) => build(window, cx),
42 }
43 }
44}
45
46pub struct MenuItem {
48 id: ElementId,
49 label: SharedString,
50 disabled: bool,
51 kind: Kind,
52 slots: ItemSlots,
53 on_checked_change: Option<Change>,
54 tone: SemanticTone,
55 style: MenuItemStyle,
56}
57
58enum Kind {
59 Action(Option<Action>),
60 Check(bool, Option<Action>),
61 Select(bool, Option<Action>),
62 Heading,
63 Divider,
64 Section {
65 rows: Vec<MenuItem>,
66 style: MenuSurfaceStyle,
67 inactive_shape: Option<CornerShape>,
68 },
69 Submenu(Vec<MenuItem>),
70}
71
72#[derive(Clone, Default)]
73struct ItemSlots {
74 content: Option<ItemContent>,
75 leading: Option<ItemContent>,
76 supporting: Option<ItemContent>,
77 trailing: Option<ItemContent>,
78 shortcut: Option<SharedString>,
79 selection_icon: Option<ItemContent>,
80}
81
82impl ItemSlots {
83 fn label(&self, label: SharedString) -> AnyElement {
84 self.content
85 .as_ref()
86 .map_or_else(|| label.into_any_element(), |content| content())
87 }
88
89 fn children(
90 &self,
91 label: SharedString,
92 marked: bool,
93 submenu: bool,
94 paint: Paint<'_>,
95 (supporting_color, shortcut_color): (gpui::Hsla, gpui::Hsla),
96 active: bool,
97 ) -> Vec<AnyElement> {
98 let motion = paint.motion;
99 let icon_size = motion.px(18.);
100 let leading = if marked {
101 Some(self.selection_icon.as_ref().map_or_else(
102 || {
103 Icon::new(IconName::Check)
104 .size(icon_size)
105 .into_any_element()
106 },
107 |icon| icon(),
108 ))
109 } else {
110 self.leading.as_ref().map(|icon| icon())
111 };
112 let supporting_scale = paint.theme.typography.text_scale();
113 let body = div()
114 .flex_1()
115 .min_w_0()
116 .overflow_hidden()
117 .child(div().truncate().child(self.label(label)))
118 .children(self.supporting.as_ref().map(|supporting| {
119 div()
120 .text_size(motion.px(12. * supporting_scale))
121 .line_height(motion.px(16. * supporting_scale))
122 .text_color(supporting_color)
123 .child(supporting())
124 }));
125 let mut children = vec![
126 div()
127 .min_w(icon_size)
128 .flex_none()
129 .children(leading)
130 .into_any_element(),
131 body.into_any_element(),
132 ];
133 if let Some(trailing) = self.trailing.as_ref() {
134 children.push(trailing());
135 } else if let Some(shortcut) = self.shortcut.as_ref().filter(|text| !text.is_empty()) {
136 let label_small = paint
137 .theme
138 .typography
139 .scale_style(TypeRole::LabelSmall.style(TypographyEmphasis::Baseline));
140 let hint = div()
141 .flex_none()
142 .text_size(motion.px(label_small.size))
143 .line_height(motion.px(label_small.line_height))
144 .text_color(shortcut_color)
145 .child(shortcut.clone());
146 children.push(if active {
147 hint.id("shortcut").test_support().into_any_element()
148 } else {
149 hint.into_any_element()
150 });
151 }
152 children.extend(submenu.then(|| {
153 Icon::new(IconName::ChevronRight)
154 .size(icon_size)
155 .mirror_in_rtl(true)
156 .into_any_element()
157 }));
158 children
159 }
160}
161
162impl MenuItem {
163 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
165 Self {
166 id: id.into(),
167 label: label.into(),
168 disabled: false,
169 kind: Kind::Action(None),
170 slots: ItemSlots::default(),
171 on_checked_change: None,
172 tone: SemanticTone::Default,
173 style: MenuItemStyle::default(),
174 }
175 }
176
177 pub fn group(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
179 Self {
180 kind: Kind::Heading,
181 ..Self::new(id, title)
182 }
183 }
184
185 pub fn divider(id: impl Into<ElementId>) -> Self {
188 Self {
189 kind: Kind::Divider,
190 ..Self::new(id, "")
191 }
192 }
193
194 pub fn section(
196 id: impl Into<ElementId>,
197 name: impl Into<SharedString>,
198 rows: impl IntoIterator<Item = MenuItem>,
199 ) -> Self {
200 Self {
201 kind: Kind::Section {
202 rows: rows.into_iter().collect(),
203 style: MenuSurfaceStyle::default(),
204 inactive_shape: None,
205 },
206 ..Self::new(id, name)
207 }
208 }
209
210 pub fn group_appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
212 if let Kind::Section { style, .. } = &mut self.kind {
213 *style = appearance;
214 }
215 self
216 }
217
218 pub fn inactive_shape(mut self, shape: CornerShape) -> Self {
220 if let Kind::Section { inactive_shape, .. } = &mut self.kind {
221 *inactive_shape = Some(shape);
222 }
223 self
224 }
225
226 pub fn appearance(mut self, style: MenuItemStyle) -> Self {
228 self.style = style;
229 self
230 }
231
232 pub fn tone(mut self, tone: SemanticTone) -> Self {
235 self.tone = tone;
236 self
237 }
238
239 pub fn destructive(self) -> Self {
241 self.tone(SemanticTone::Danger)
242 }
243
244 pub fn shortcut(mut self, text: impl Into<SharedString>) -> Self {
248 self.slots.shortcut = Some(text.into());
249 self
250 }
251
252 pub fn submenu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
254 self.kind = Kind::Submenu(items.into_iter().collect());
255 self
256 }
257
258 pub fn disabled(mut self, disabled: bool) -> Self {
260 self.disabled = disabled;
261 self
262 }
263
264 pub fn checked(mut self, checked: bool) -> Self {
266 self.kind = Kind::Check(checked, self.action());
267 self
268 }
269
270 pub fn selected(mut self, selected: bool) -> Self {
272 self.kind = Kind::Select(selected, self.action());
273 self
274 }
275
276 pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
279 self.slots.content = Some(Rc::new(move || build().into_any_element()));
280 self
281 }
282
283 pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
285 self.slots.leading = Some(Rc::new(move || build().into_any_element()));
286 self
287 }
288
289 pub fn supporting<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
291 self.slots.supporting = Some(Rc::new(move || build().into_any_element()));
292 self
293 }
294
295 pub fn trailing<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
297 self.slots.trailing = Some(Rc::new(move || build().into_any_element()));
298 self
299 }
300
301 pub fn selection_icon<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
303 self.slots.selection_icon = Some(Rc::new(move || build().into_any_element()));
304 self
305 }
306
307 pub fn on_checked_change(
310 mut self,
311 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
312 ) -> Self {
313 self.on_checked_change = Some(Rc::new(callback));
314 self
315 }
316
317 fn action(&self) -> Option<Action> {
318 match &self.kind {
319 Kind::Action(action) | Kind::Check(_, action) | Kind::Select(_, action) => {
320 action.clone()
321 }
322 _ => None,
323 }
324 }
325
326 fn activation(&self) -> Option<Action> {
327 if let Kind::Check(checked, _) = self.kind
328 && let Some(callback) = &self.on_checked_change
329 {
330 let callback = callback.clone();
331 return Some(Rc::new(move |window, cx| callback(!checked, window, cx)));
332 }
333 self.action()
334 }
335
336 pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
338 match &mut self.kind {
339 Kind::Action(handler) | Kind::Check(_, handler) | Kind::Select(_, handler) => {
340 *handler = Some(Rc::new(action));
341 }
342 _ => {}
343 }
344 self
345 }
346}
347
348#[derive(IntoElement)]
351pub struct Menu {
352 id: ElementId,
353 trigger: AnyElement,
354 items: MenuItems,
355 mouse_button: MouseButton,
356 anchor: Anchor,
357 close_parent: Option<Action>,
358 enabled: bool,
359 ancestor: Option<Rc<PopupBounds>>,
360 composed_trigger: Option<ComposedTrigger>,
361 open: Option<bool>,
362 on_open_change: Option<Change>,
363 on_dismiss: Option<Action>,
364 color: MenuColor,
365 appearance: MenuSurfaceStyle,
366 decoration: Option<ItemContent>,
367 scroll: Option<ScrollHandle>,
368 offset: Pixels,
369 position: Option<Point<Pixels>>,
370}
371
372#[derive(Default)]
373struct PopupBounds {
374 trigger: Cell<Bounds<Pixels>>,
375 popup: Cell<Bounds<Pixels>>,
376 context_position: Cell<Option<Point<Pixels>>>,
377 context_was_open: Cell<bool>,
378 context_focus: RefCell<Option<FocusHandle>>,
379 context_previous_focus: RefCell<Option<FocusHandle>>,
380 child: RefCell<Option<Rc<PopupBounds>>>,
381 presented: RefCell<Option<PresentedMenu>>,
382 scroll: ScrollHandle,
383 motion: Cell<Option<OverlayMotion>>,
384 open: Rc<Cell<bool>>,
385}
386
387#[derive(Clone)]
388struct MenuPresentation {
389 color: MenuColor,
390 appearance: MenuSurfaceStyle,
391 decoration: Option<ItemContent>,
392 scroll: ScrollHandle,
393}
394
395struct PresentedMenu {
396 items: Rc<[MenuExitRow]>,
397 presentation: MenuPresentation,
398}
399
400impl PopupBounds {
401 fn popup_contains(&self, point: &Point<Pixels>) -> bool {
402 self.popup.get().contains(point)
403 || self
404 .child
405 .borrow()
406 .as_ref()
407 .is_some_and(|child| child.open.get() && child.contains(point))
408 }
409
410 fn contains(&self, point: &Point<Pixels>) -> bool {
411 self.trigger.get().contains(point) || self.popup_contains(point)
412 }
413}
414
415impl Menu {
416 pub fn new(
418 id: impl Into<ElementId>,
419 trigger: impl IntoElement,
420 items: impl IntoIterator<Item = MenuItem>,
421 ) -> Self {
422 Self::with_items(
423 id.into(),
424 trigger.into_any_element(),
425 MenuItems::Eager(items.into_iter().collect()),
426 )
427 }
428
429 pub fn new_with<I>(
431 id: impl Into<ElementId>,
432 trigger: impl IntoElement,
433 build: impl FnOnce(&mut Window, &mut App) -> I + 'static,
434 ) -> Self
435 where
436 I: IntoIterator<Item = MenuItem>,
437 {
438 Self::with_items(
439 id.into(),
440 trigger.into_any_element(),
441 MenuItems::Lazy(Box::new(move |window, cx| {
442 build(window, cx).into_iter().collect()
443 })),
444 )
445 }
446
447 fn with_items(id: ElementId, trigger: AnyElement, items: MenuItems) -> Self {
448 Self {
449 id,
450 trigger,
451 items,
452 mouse_button: MouseButton::Left,
453 anchor: Anchor::TopLeft,
454 close_parent: None,
455 enabled: true,
456 ancestor: None,
457 composed_trigger: None,
458 open: None,
459 on_open_change: None,
460 on_dismiss: None,
461 color: MenuColor::default(),
462 appearance: MenuSurfaceStyle::default(),
463 decoration: None,
464 scroll: None,
465 offset: px(4.),
466 position: None,
467 }
468 }
469
470 pub fn disabled(mut self, disabled: bool) -> Self {
472 self.enabled = !disabled;
473 self
474 }
475
476 pub fn context(mut self) -> Self {
480 self.mouse_button = MouseButton::Right;
481 self
482 }
483
484 pub fn anchor(mut self, anchor: Anchor) -> Self {
486 self.anchor = anchor;
487 self
488 }
489
490 pub fn offset(mut self, offset: Pixels) -> Self {
492 if f32::from(offset).is_finite() {
493 self.offset = offset;
494 }
495 self
496 }
497
498 pub fn position(mut self, position: Point<Pixels>) -> Self {
500 self.position = (f32::from(position.x).is_finite() && f32::from(position.y).is_finite())
501 .then_some(position);
502 self
503 }
504
505 pub fn color(mut self, color: MenuColor) -> Self {
507 self.color = color;
508 self
509 }
510
511 pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
513 self.appearance = appearance;
514 self
515 }
516
517 pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
520 self.decoration = Some(Rc::new(move || build().into_any_element()));
521 self
522 }
523
524 pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
526 self.scroll = Some(scroll.clone());
527 self
528 }
529
530 pub fn composed(
535 id: impl Into<ElementId>,
536 items: impl IntoIterator<Item = MenuItem>,
537 trigger: impl FnOnce(bool, Action) -> AnyElement + 'static,
538 ) -> Self {
539 let mut menu = Self::new(id, div(), items);
540 menu.composed_trigger = Some(Box::new(trigger));
541 menu
542 }
543
544 pub fn open(mut self, open: bool) -> Self {
546 self.open = Some(open);
547 self
548 }
549
550 pub fn on_open_change(
553 mut self,
554 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
555 ) -> Self {
556 self.on_open_change = Some(Rc::new(callback));
557 self
558 }
559
560 pub fn on_dismiss(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
563 self.on_dismiss = Some(Rc::new(callback));
564 self
565 }
566}
567
568fn build_exit_branch(
569 id: &ElementId,
570 bounds: &Rc<PopupBounds>,
571 motion: OverlayMotion,
572 direction: Direction,
573 window: &Window,
574 cx: &App,
575) -> gpui::Div {
576 let mut exits = div();
579 let mut level = Some(bounds.clone());
580 let mut depth = 0;
581 while let Some(bounds) = level {
582 let Some(previous) = bounds.motion.get() else {
583 break;
584 };
585 let motion = if depth == 0 {
586 motion
587 } else {
588 OverlayMotion {
589 scale: 0.8 + (motion.scale - 0.8) * (previous.scale - 0.8) / 0.2,
590 alpha: motion.alpha * previous.alpha,
591 }
592 };
593 exits = exits.children(menu_exit(
594 (id, depth),
595 &bounds,
596 motion,
597 direction,
598 window,
599 cx,
600 ));
601 level = bounds.child.borrow().clone();
602 depth += 1;
603 }
604 exits
605}
606
607impl RenderOnce for Menu {
608 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
609 let direction = current_material_theme(window, cx).layout.direction;
610 let submenu = self.close_parent.is_some();
611 let is_context = self.mouse_button == MouseButton::Right;
612 if !self.enabled {
613 return self.trigger;
614 }
615 let view = window.current_view();
616 let bounds = window
617 .use_keyed_state((self.id.clone(), "menu-bounds"), cx, |_, _| {
618 Rc::new(PopupBounds::default())
619 })
620 .read(cx)
621 .clone();
622 let open_state = bounds.open.clone();
623 let controlled = self.open.is_some();
624 let open = self.open.unwrap_or_else(|| open_state.get());
625 open_state.set(open);
626 let key_state = open_state.clone();
627 let trigger_state = open_state.clone();
628 let context_open_state = open_state.clone();
629 let request: Change = {
630 let on_open_change = self.on_open_change;
631 let on_dismiss = self.on_dismiss;
632 Rc::new(move |requested, window, cx| {
633 if !controlled {
634 open_state.set(requested);
635 cx.notify(view);
636 }
637 if let Some(callback) = &on_open_change {
638 callback(requested, window, cx);
639 }
640 if !requested && let Some(callback) = &on_dismiss {
641 callback(window, cx);
642 }
643 })
644 };
645 let trigger: Action = {
646 let request = request.clone();
647 Rc::new(move |window, cx| {
648 let displayed = if controlled {
649 open
650 } else {
651 trigger_state.get()
652 };
653 request(!displayed, window, cx);
654 })
655 };
656 let key_trigger = trigger.clone();
657 let mouse_trigger = trigger.clone();
658 let context_open: Action = {
659 let request = request.clone();
660 Rc::new(move |window, cx| request(true, window, cx))
661 };
662 let context_key_open = context_open.clone();
663 let popover_request = request.clone();
664 let popup_request = request;
665 let motion = OverlayMotion::sample(&self.id, open, window, cx);
666 let position = bounds.clone();
667 let context_mouse_bounds = bounds.clone();
668 let context_key_bounds = bounds.clone();
669 let ancestor = self.ancestor.clone();
670 let anchor = logical_anchor(self.anchor, direction);
671 if !open && motion.is_none() {
672 bounds.presented.borrow_mut().take();
673 bounds.child.borrow_mut().take();
674 bounds.context_position.set(None);
675 }
676 let explicit_position = self
677 .position
678 .or_else(|| is_context.then(|| bounds.context_position.get()).flatten());
679 let presentation = MenuPresentation {
680 color: self.color,
681 appearance: self.appearance,
682 decoration: self.decoration,
683 scroll: self.scroll.unwrap_or_else(|| bounds.scroll.clone()),
684 };
685 let resolved_items = open.then(|| self.items.resolve(window, cx));
686 if let Some(items) = resolved_items.as_ref()
687 && !cx.reduce_motion()
688 {
689 *bounds.presented.borrow_mut() = Some(PresentedMenu {
690 items: items.iter().map(MenuExitRow::from).collect(),
691 presentation: presentation.clone(),
692 });
693 }
694 bounds.motion.set(motion);
695 let forward = if direction == Direction::Rtl {
696 "left"
697 } else {
698 "right"
699 };
700 let exit_view = motion
701 .filter(|_| !open)
702 .map(|motion| build_exit_branch(&self.id, &bounds, motion, direction, window, cx));
703 let menu_id = self.id.clone();
704 let menu_element: AnyElement = if is_context {
705 let content_focus = {
706 let mut slot = bounds.context_focus.borrow_mut();
707 slot.get_or_insert_with(|| cx.focus_handle()).clone()
708 };
709 let was_open = bounds.context_was_open.replace(open);
710 if open && !was_open {
711 *bounds.context_previous_focus.borrow_mut() = window.focused(cx);
712 content_focus.focus(window, cx);
713 } else if !open && was_open {
714 let previous = bounds.context_previous_focus.borrow_mut().take();
715 if content_focus.contains_focused(window, cx) {
716 match previous {
717 Some(previous) => previous.focus(window, cx),
718 None => window.blur(cx),
719 }
720 }
721 }
722
723 let content = self
724 .composed_trigger
725 .map_or(self.trigger, |build| build(open, trigger));
726 let trigger_el = div()
727 .id("menu-trigger")
728 .role(Role::Group)
729 .aria_expanded(open)
730 .on_mouse_down(MouseButton::Right, move |event, window, cx| {
731 cx.stop_propagation();
732 context_mouse_bounds
733 .context_position
734 .set(Some(event.position));
735 if context_open_state.get() {
736 cx.notify(view);
737 } else {
738 context_open(window, cx);
739 }
740 })
741 .on_key_down(move |event, window, cx| {
742 if is_context_menu_key(&event.keystroke) {
743 context_key_bounds.context_position.set(None);
744 context_key_open(window, cx);
745 cx.stop_propagation();
746 }
747 })
748 .child(content);
749
750 let popup = Popup::new(self.id, trigger_el)
751 .anchor(anchor)
752 .offset(self.offset)
753 .on_position(move |resolved, trigger| {
754 position.trigger.set(trigger);
755 if explicit_position.is_none() {
756 position.popup.set(resolved.bounds);
757 }
758 if let Some(ancestor) = &ancestor {
759 *ancestor.child.borrow_mut() = Some(position.clone());
760 }
761 });
762
763 if open {
764 let motion = motion.expect("open menu has motion");
765 let close_level: Action =
766 Rc::new(move |window, cx| popup_request(false, window, cx));
767 let close: Action = {
768 let close_level = close_level.clone();
769 Rc::new(move |window, cx| {
770 close_level(window, cx);
771 if let Some(close_parent) = &self.close_parent {
772 close_parent(window, cx);
773 }
774 })
775 };
776 let dismissal = close_level.clone();
777 let escape = close_level.clone();
778 let item_bounds = bounds.clone();
779 let items = resolved_items.unwrap_or_default();
780 let body = window.with_id(menu_id, |window| {
781 menu_content(
782 items,
783 close,
784 submenu.then_some(close_level),
785 content_focus.clone(),
786 (direction, bounds.clone(), presentation, motion),
787 window,
788 cx,
789 )
790 });
791 let dismiss_shell = div()
792 .id("dismiss-menu")
793 .opacity(motion.alpha)
794 .on_key_down(move |event, window, cx| {
795 if event.keystroke.key == "escape" && !event.keystroke.modifiers.modified()
796 {
797 escape(window, cx);
798 cx.stop_propagation();
799 }
800 })
801 .on_mouse_down_out(move |event, window, cx| {
802 let point = &event.position;
803 if bounds.popup_contains(point)
804 || (event.button == MouseButton::Right
805 && bounds.trigger.get().contains(point))
806 {
807 return;
808 }
809 dismissal(window, cx);
810 })
811 .child(body);
812 let pivot = item_bounds.clone();
813 let overlay = ScaledOverlay::new(dismiss_shell, motion, move |menu| {
814 let anchor_bounds = explicit_position.map_or_else(
815 || pivot.trigger.get(),
816 |pos| Bounds::new(pos, Size::default()),
817 );
818 menu_pivot(menu, anchor_bounds)
819 });
820 let overlay = ThemeScope::inherit(overlay, window, cx);
821 let positioned: AnyElement = if let Some(position) = explicit_position {
822 Positioner::corner(anchor, position)
823 .on_position(move |resolved| item_bounds.popup.set(resolved.bounds))
824 .occlude()
825 .child(overlay)
826 .into_any_element()
827 } else {
828 overlay
829 };
830 popup
831 .content(
832 div()
833 .id("content")
834 .role(Role::Dialog)
835 .occlude()
836 .tab_group()
837 .track_focus(&content_focus)
838 .child(positioned),
839 )
840 .into_any_element()
841 } else {
842 popup.into_any_element()
843 }
844 } else {
845 Popover::new(self.id)
846 .open(open)
847 .on_open_change(move |requested, window, cx| {
848 popover_request(*requested, window, cx)
849 })
850 .anchor(anchor)
851 .offset(self.offset)
852 .mouse_button(self.mouse_button)
853 .overlay_closable(false)
854 .on_position(move |resolved, trigger| {
855 position.trigger.set(trigger);
856 if explicit_position.is_none() {
857 position.popup.set(resolved.bounds);
858 }
859 if let Some(ancestor) = &ancestor {
860 *ancestor.child.borrow_mut() = Some(position.clone());
861 }
862 })
863 .trigger_with(move |open, _, _| {
864 let content = self
865 .composed_trigger
866 .map_or(self.trigger, |build| build(open, trigger));
867 div()
868 .id("menu-trigger")
869 .role(Role::Group)
870 .aria_expanded(open)
871 .when(controlled, |trigger| {
872 trigger
875 .on_action(move |_: &Confirm, window, cx| key_trigger(window, cx))
876 .on_mouse_down(self.mouse_button, move |_, window, cx| {
877 cx.stop_propagation();
878 mouse_trigger(window, cx);
879 })
880 })
881 .on_key_down(move |event, _, cx| {
882 if submenu && event.keystroke.key == forward && !key_state.get() {
883 key_state.set(true);
884 cx.notify(view);
885 cx.stop_propagation();
886 }
887 })
888 .child(content)
889 .into_any_element()
890 })
891 .content(move |state, window, cx| {
892 let motion = motion.expect("open menu has motion");
893 let close_level: Action = if controlled {
894 Rc::new(move |window, cx| popup_request(false, window, cx))
895 } else {
896 let own = cx.entity().downgrade();
897 Rc::new(move |window, cx| {
898 let _ = own.update(cx, |state: &mut PopoverState, cx| {
899 state.dismiss(window, cx);
900 });
901 })
902 };
903 let close: Action = {
904 let close_level = close_level.clone();
905 Rc::new(move |window, cx| {
906 close_level(window, cx);
907 if let Some(close_parent) = &self.close_parent {
908 close_parent(window, cx);
909 }
910 })
911 };
912 let dismissal = close_level.clone();
913 let escape = close_level.clone();
914 let item_bounds = bounds.clone();
915 let items = resolved_items.unwrap_or_default();
916 let content = window.with_id(menu_id, |window| {
917 menu_content(
918 items,
919 close,
920 submenu.then_some(close_level),
921 state.focus_handle(cx),
922 (direction, bounds.clone(), presentation, motion),
923 window,
924 cx,
925 )
926 });
927 let popup = div()
928 .id("dismiss-menu")
929 .opacity(motion.alpha)
930 .when(controlled, |popup| {
931 popup.on_action(move |_: &Cancel, window, cx| escape(window, cx))
932 })
933 .on_mouse_down_out(move |event, window, cx| {
934 let point = &event.position;
935 if bounds.contains(point) {
936 return;
937 }
938 dismissal(window, cx);
939 })
940 .child(content);
941 let pivot = item_bounds.clone();
942 let overlay = ScaledOverlay::new(popup, motion, move |menu| {
943 let anchor_bounds = explicit_position.map_or_else(
944 || pivot.trigger.get(),
945 |pos| Bounds::new(pos, Size::default()),
946 );
947 menu_pivot(menu, anchor_bounds)
948 });
949 let overlay = ThemeScope::inherit(overlay, window, cx);
950 if let Some(position) = explicit_position {
951 Positioner::corner(anchor, position)
952 .on_position(move |resolved| item_bounds.popup.set(resolved.bounds))
953 .occlude()
954 .child(overlay)
955 .into_any_element()
956 } else {
957 overlay
958 }
959 })
960 .into_any_element()
961 };
962 div()
963 .relative()
964 .child(menu_element)
965 .children(exit_view)
966 .into_any_element()
967 }
968}
969
970fn is_context_menu_key(keystroke: &gpui::Keystroke) -> bool {
971 let mods = &keystroke.modifiers;
972 if keystroke.key == "contextmenu" && !mods.modified() {
973 return true;
974 }
975 keystroke.key == "f10"
976 && mods.shift
977 && !mods.control
978 && !mods.alt
979 && !mods.platform
980 && !mods.function
981}