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 {
164 Self {
165 id: id.into(),
166 label: label.into(),
167 disabled: false,
168 kind: Kind::Action(None),
169 slots: ItemSlots::default(),
170 on_checked_change: None,
171 tone: SemanticTone::Default,
172 style: MenuItemStyle::default(),
173 }
174 }
175
176 pub fn group(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
177 Self {
178 kind: Kind::Heading,
179 ..Self::new(id, title)
180 }
181 }
182
183 pub fn divider(id: impl Into<ElementId>) -> Self {
186 Self {
187 kind: Kind::Divider,
188 ..Self::new(id, "")
189 }
190 }
191
192 pub fn section(
194 id: impl Into<ElementId>,
195 name: impl Into<SharedString>,
196 rows: impl IntoIterator<Item = MenuItem>,
197 ) -> Self {
198 Self {
199 kind: Kind::Section {
200 rows: rows.into_iter().collect(),
201 style: MenuSurfaceStyle::default(),
202 inactive_shape: None,
203 },
204 ..Self::new(id, name)
205 }
206 }
207
208 pub fn group_appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
210 if let Kind::Section { style, .. } = &mut self.kind {
211 *style = appearance;
212 }
213 self
214 }
215
216 pub fn inactive_shape(mut self, shape: CornerShape) -> Self {
218 if let Kind::Section { inactive_shape, .. } = &mut self.kind {
219 *inactive_shape = Some(shape);
220 }
221 self
222 }
223
224 pub fn appearance(mut self, style: MenuItemStyle) -> Self {
226 self.style = style;
227 self
228 }
229
230 pub fn tone(mut self, tone: SemanticTone) -> Self {
233 self.tone = tone;
234 self
235 }
236
237 pub fn destructive(self) -> Self {
239 self.tone(SemanticTone::Danger)
240 }
241
242 pub fn shortcut(mut self, text: impl Into<SharedString>) -> Self {
246 self.slots.shortcut = Some(text.into());
247 self
248 }
249
250 pub fn submenu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
251 self.kind = Kind::Submenu(items.into_iter().collect());
252 self
253 }
254
255 pub fn disabled(mut self, disabled: bool) -> Self {
256 self.disabled = disabled;
257 self
258 }
259
260 pub fn checked(mut self, checked: bool) -> Self {
261 self.kind = Kind::Check(checked, self.action());
262 self
263 }
264
265 pub fn selected(mut self, selected: bool) -> Self {
266 self.kind = Kind::Select(selected, self.action());
267 self
268 }
269
270 pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
273 self.slots.content = Some(Rc::new(move || build().into_any_element()));
274 self
275 }
276
277 pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
279 self.slots.leading = Some(Rc::new(move || build().into_any_element()));
280 self
281 }
282
283 pub fn supporting<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
285 self.slots.supporting = Some(Rc::new(move || build().into_any_element()));
286 self
287 }
288
289 pub fn trailing<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
291 self.slots.trailing = Some(Rc::new(move || build().into_any_element()));
292 self
293 }
294
295 pub fn selection_icon<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
297 self.slots.selection_icon = Some(Rc::new(move || build().into_any_element()));
298 self
299 }
300
301 pub fn on_checked_change(
304 mut self,
305 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
306 ) -> Self {
307 self.on_checked_change = Some(Rc::new(callback));
308 self
309 }
310
311 fn action(&self) -> Option<Action> {
312 match &self.kind {
313 Kind::Action(action) | Kind::Check(_, action) | Kind::Select(_, action) => {
314 action.clone()
315 }
316 _ => None,
317 }
318 }
319
320 fn activation(&self) -> Option<Action> {
321 if let Kind::Check(checked, _) = self.kind
322 && let Some(callback) = &self.on_checked_change
323 {
324 let callback = callback.clone();
325 return Some(Rc::new(move |window, cx| callback(!checked, window, cx)));
326 }
327 self.action()
328 }
329
330 pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
331 match &mut self.kind {
332 Kind::Action(handler) | Kind::Check(_, handler) | Kind::Select(_, handler) => {
333 *handler = Some(Rc::new(action));
334 }
335 _ => {}
336 }
337 self
338 }
339}
340
341#[derive(IntoElement)]
344pub struct Menu {
345 id: ElementId,
346 trigger: AnyElement,
347 items: MenuItems,
348 mouse_button: MouseButton,
349 anchor: Anchor,
350 close_parent: Option<Action>,
351 enabled: bool,
352 ancestor: Option<Rc<PopupBounds>>,
353 composed_trigger: Option<ComposedTrigger>,
354 open: Option<bool>,
355 on_open_change: Option<Change>,
356 on_dismiss: Option<Action>,
357 color: MenuColor,
358 appearance: MenuSurfaceStyle,
359 decoration: Option<ItemContent>,
360 scroll: Option<ScrollHandle>,
361 offset: Pixels,
362 position: Option<Point<Pixels>>,
363}
364
365#[derive(Default)]
366struct PopupBounds {
367 trigger: Cell<Bounds<Pixels>>,
368 popup: Cell<Bounds<Pixels>>,
369 context_position: Cell<Option<Point<Pixels>>>,
370 context_was_open: Cell<bool>,
371 context_focus: RefCell<Option<FocusHandle>>,
372 context_previous_focus: RefCell<Option<FocusHandle>>,
373 child: RefCell<Option<Rc<PopupBounds>>>,
374 presented: RefCell<Option<PresentedMenu>>,
375 scroll: ScrollHandle,
376 motion: Cell<Option<OverlayMotion>>,
377 open: Rc<Cell<bool>>,
378}
379
380#[derive(Clone)]
381struct MenuPresentation {
382 color: MenuColor,
383 appearance: MenuSurfaceStyle,
384 decoration: Option<ItemContent>,
385 scroll: ScrollHandle,
386}
387
388struct PresentedMenu {
389 items: Rc<[MenuExitRow]>,
390 presentation: MenuPresentation,
391}
392
393impl PopupBounds {
394 fn popup_contains(&self, point: &Point<Pixels>) -> bool {
395 self.popup.get().contains(point)
396 || self
397 .child
398 .borrow()
399 .as_ref()
400 .is_some_and(|child| child.open.get() && child.contains(point))
401 }
402
403 fn contains(&self, point: &Point<Pixels>) -> bool {
404 self.trigger.get().contains(point) || self.popup_contains(point)
405 }
406}
407
408impl Menu {
409 pub fn new(
410 id: impl Into<ElementId>,
411 trigger: impl IntoElement,
412 items: impl IntoIterator<Item = MenuItem>,
413 ) -> Self {
414 Self::with_items(
415 id.into(),
416 trigger.into_any_element(),
417 MenuItems::Eager(items.into_iter().collect()),
418 )
419 }
420
421 pub fn new_with<I>(
423 id: impl Into<ElementId>,
424 trigger: impl IntoElement,
425 build: impl FnOnce(&mut Window, &mut App) -> I + 'static,
426 ) -> Self
427 where
428 I: IntoIterator<Item = MenuItem>,
429 {
430 Self::with_items(
431 id.into(),
432 trigger.into_any_element(),
433 MenuItems::Lazy(Box::new(move |window, cx| {
434 build(window, cx).into_iter().collect()
435 })),
436 )
437 }
438
439 fn with_items(id: ElementId, trigger: AnyElement, items: MenuItems) -> Self {
440 Self {
441 id,
442 trigger,
443 items,
444 mouse_button: MouseButton::Left,
445 anchor: Anchor::TopLeft,
446 close_parent: None,
447 enabled: true,
448 ancestor: None,
449 composed_trigger: None,
450 open: None,
451 on_open_change: None,
452 on_dismiss: None,
453 color: MenuColor::default(),
454 appearance: MenuSurfaceStyle::default(),
455 decoration: None,
456 scroll: None,
457 offset: px(4.),
458 position: None,
459 }
460 }
461
462 pub fn disabled(mut self, disabled: bool) -> Self {
464 self.enabled = !disabled;
465 self
466 }
467
468 pub fn context(mut self) -> Self {
472 self.mouse_button = MouseButton::Right;
473 self
474 }
475
476 pub fn anchor(mut self, anchor: Anchor) -> Self {
477 self.anchor = anchor;
478 self
479 }
480
481 pub fn offset(mut self, offset: Pixels) -> Self {
483 if f32::from(offset).is_finite() {
484 self.offset = offset;
485 }
486 self
487 }
488
489 pub fn position(mut self, position: Point<Pixels>) -> Self {
491 self.position = (f32::from(position.x).is_finite() && f32::from(position.y).is_finite())
492 .then_some(position);
493 self
494 }
495
496 pub fn color(mut self, color: MenuColor) -> Self {
498 self.color = color;
499 self
500 }
501
502 pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
504 self.appearance = appearance;
505 self
506 }
507
508 pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
511 self.decoration = Some(Rc::new(move || build().into_any_element()));
512 self
513 }
514
515 pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
517 self.scroll = Some(scroll.clone());
518 self
519 }
520
521 pub fn composed(
526 id: impl Into<ElementId>,
527 items: impl IntoIterator<Item = MenuItem>,
528 trigger: impl FnOnce(bool, Action) -> AnyElement + 'static,
529 ) -> Self {
530 let mut menu = Self::new(id, div(), items);
531 menu.composed_trigger = Some(Box::new(trigger));
532 menu
533 }
534
535 pub fn open(mut self, open: bool) -> Self {
537 self.open = Some(open);
538 self
539 }
540
541 pub fn on_open_change(
544 mut self,
545 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
546 ) -> Self {
547 self.on_open_change = Some(Rc::new(callback));
548 self
549 }
550
551 pub fn on_dismiss(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
554 self.on_dismiss = Some(Rc::new(callback));
555 self
556 }
557}
558
559fn build_exit_branch(
560 id: &ElementId,
561 bounds: &Rc<PopupBounds>,
562 motion: OverlayMotion,
563 direction: Direction,
564 window: &Window,
565 cx: &App,
566) -> gpui::Div {
567 let mut exits = div();
570 let mut level = Some(bounds.clone());
571 let mut depth = 0;
572 while let Some(bounds) = level {
573 let Some(previous) = bounds.motion.get() else {
574 break;
575 };
576 let motion = if depth == 0 {
577 motion
578 } else {
579 OverlayMotion {
580 scale: 0.8 + (motion.scale - 0.8) * (previous.scale - 0.8) / 0.2,
581 alpha: motion.alpha * previous.alpha,
582 }
583 };
584 exits = exits.children(menu_exit(
585 (id, depth),
586 &bounds,
587 motion,
588 direction,
589 window,
590 cx,
591 ));
592 level = bounds.child.borrow().clone();
593 depth += 1;
594 }
595 exits
596}
597
598impl RenderOnce for Menu {
599 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
600 let direction = current_material_theme(window, cx).layout.direction;
601 let submenu = self.close_parent.is_some();
602 let is_context = self.mouse_button == MouseButton::Right;
603 if !self.enabled {
604 return self.trigger;
605 }
606 let view = window.current_view();
607 let bounds = window
608 .use_keyed_state((self.id.clone(), "menu-bounds"), cx, |_, _| {
609 Rc::new(PopupBounds::default())
610 })
611 .read(cx)
612 .clone();
613 let open_state = bounds.open.clone();
614 let controlled = self.open.is_some();
615 let open = self.open.unwrap_or_else(|| open_state.get());
616 open_state.set(open);
617 let key_state = open_state.clone();
618 let trigger_state = open_state.clone();
619 let context_open_state = open_state.clone();
620 let request: Change = {
621 let on_open_change = self.on_open_change;
622 let on_dismiss = self.on_dismiss;
623 Rc::new(move |requested, window, cx| {
624 if !controlled {
625 open_state.set(requested);
626 cx.notify(view);
627 }
628 if let Some(callback) = &on_open_change {
629 callback(requested, window, cx);
630 }
631 if !requested && let Some(callback) = &on_dismiss {
632 callback(window, cx);
633 }
634 })
635 };
636 let trigger: Action = {
637 let request = request.clone();
638 Rc::new(move |window, cx| {
639 let displayed = if controlled {
640 open
641 } else {
642 trigger_state.get()
643 };
644 request(!displayed, window, cx);
645 })
646 };
647 let key_trigger = trigger.clone();
648 let mouse_trigger = trigger.clone();
649 let context_open: Action = {
650 let request = request.clone();
651 Rc::new(move |window, cx| request(true, window, cx))
652 };
653 let context_key_open = context_open.clone();
654 let popover_request = request.clone();
655 let popup_request = request;
656 let motion = OverlayMotion::sample(&self.id, open, window, cx);
657 let position = bounds.clone();
658 let context_mouse_bounds = bounds.clone();
659 let context_key_bounds = bounds.clone();
660 let ancestor = self.ancestor.clone();
661 let anchor = logical_anchor(self.anchor, direction);
662 if !open && motion.is_none() {
663 bounds.presented.borrow_mut().take();
664 bounds.child.borrow_mut().take();
665 bounds.context_position.set(None);
666 }
667 let explicit_position = self
668 .position
669 .or_else(|| is_context.then(|| bounds.context_position.get()).flatten());
670 let presentation = MenuPresentation {
671 color: self.color,
672 appearance: self.appearance,
673 decoration: self.decoration,
674 scroll: self.scroll.unwrap_or_else(|| bounds.scroll.clone()),
675 };
676 let resolved_items = open.then(|| self.items.resolve(window, cx));
677 if let Some(items) = resolved_items.as_ref()
678 && !cx.reduce_motion()
679 {
680 *bounds.presented.borrow_mut() = Some(PresentedMenu {
681 items: items.iter().map(MenuExitRow::from).collect(),
682 presentation: presentation.clone(),
683 });
684 }
685 bounds.motion.set(motion);
686 let forward = if direction == Direction::Rtl {
687 "left"
688 } else {
689 "right"
690 };
691 let exit_view = motion
692 .filter(|_| !open)
693 .map(|motion| build_exit_branch(&self.id, &bounds, motion, direction, window, cx));
694 let menu_id = self.id.clone();
695 let menu_element: AnyElement = if is_context {
696 let content_focus = {
697 let mut slot = bounds.context_focus.borrow_mut();
698 slot.get_or_insert_with(|| cx.focus_handle()).clone()
699 };
700 let was_open = bounds.context_was_open.replace(open);
701 if open && !was_open {
702 *bounds.context_previous_focus.borrow_mut() = window.focused(cx);
703 content_focus.focus(window, cx);
704 } else if !open && was_open {
705 let previous = bounds.context_previous_focus.borrow_mut().take();
706 if content_focus.contains_focused(window, cx) {
707 match previous {
708 Some(previous) => previous.focus(window, cx),
709 None => window.blur(cx),
710 }
711 }
712 }
713
714 let content = self
715 .composed_trigger
716 .map_or(self.trigger, |build| build(open, trigger));
717 let trigger_el = div()
718 .id("menu-trigger")
719 .role(Role::Group)
720 .aria_expanded(open)
721 .on_mouse_down(MouseButton::Right, move |event, window, cx| {
722 cx.stop_propagation();
723 context_mouse_bounds
724 .context_position
725 .set(Some(event.position));
726 if context_open_state.get() {
727 cx.notify(view);
728 } else {
729 context_open(window, cx);
730 }
731 })
732 .on_key_down(move |event, window, cx| {
733 if is_context_menu_key(&event.keystroke) {
734 context_key_bounds.context_position.set(None);
735 context_key_open(window, cx);
736 cx.stop_propagation();
737 }
738 })
739 .child(content);
740
741 let popup = Popup::new(self.id, trigger_el)
742 .anchor(anchor)
743 .offset(self.offset)
744 .on_position(move |resolved, trigger| {
745 position.trigger.set(trigger);
746 if explicit_position.is_none() {
747 position.popup.set(resolved.bounds);
748 }
749 if let Some(ancestor) = &ancestor {
750 *ancestor.child.borrow_mut() = Some(position.clone());
751 }
752 });
753
754 if open {
755 let motion = motion.expect("open menu has motion");
756 let close_level: Action =
757 Rc::new(move |window, cx| popup_request(false, window, cx));
758 let close: Action = {
759 let close_level = close_level.clone();
760 Rc::new(move |window, cx| {
761 close_level(window, cx);
762 if let Some(close_parent) = &self.close_parent {
763 close_parent(window, cx);
764 }
765 })
766 };
767 let dismissal = close_level.clone();
768 let escape = close_level.clone();
769 let item_bounds = bounds.clone();
770 let items = resolved_items.unwrap_or_default();
771 let body = window.with_id(menu_id, |window| {
772 menu_content(
773 items,
774 close,
775 submenu.then_some(close_level),
776 content_focus.clone(),
777 (direction, bounds.clone(), presentation, motion),
778 window,
779 cx,
780 )
781 });
782 let dismiss_shell = div()
783 .id("dismiss-menu")
784 .opacity(motion.alpha)
785 .on_key_down(move |event, window, cx| {
786 if event.keystroke.key == "escape" && !event.keystroke.modifiers.modified()
787 {
788 escape(window, cx);
789 cx.stop_propagation();
790 }
791 })
792 .on_mouse_down_out(move |event, window, cx| {
793 let point = &event.position;
794 if bounds.popup_contains(point)
795 || (event.button == MouseButton::Right
796 && bounds.trigger.get().contains(point))
797 {
798 return;
799 }
800 dismissal(window, cx);
801 })
802 .child(body);
803 let pivot = item_bounds.clone();
804 let overlay = ScaledOverlay::new(dismiss_shell, motion, move |menu| {
805 let anchor_bounds = explicit_position.map_or_else(
806 || pivot.trigger.get(),
807 |pos| Bounds::new(pos, Size::default()),
808 );
809 menu_pivot(menu, anchor_bounds)
810 });
811 let overlay = ThemeScope::inherit(overlay, window, cx);
812 let positioned: AnyElement = if let Some(position) = explicit_position {
813 Positioner::corner(anchor, position)
814 .on_position(move |resolved| item_bounds.popup.set(resolved.bounds))
815 .occlude()
816 .child(overlay)
817 .into_any_element()
818 } else {
819 overlay
820 };
821 popup
822 .content(
823 div()
824 .id("content")
825 .role(Role::Dialog)
826 .occlude()
827 .tab_group()
828 .track_focus(&content_focus)
829 .child(positioned),
830 )
831 .into_any_element()
832 } else {
833 popup.into_any_element()
834 }
835 } else {
836 Popover::new(self.id)
837 .open(open)
838 .on_open_change(move |requested, window, cx| {
839 popover_request(*requested, window, cx)
840 })
841 .anchor(anchor)
842 .offset(self.offset)
843 .mouse_button(self.mouse_button)
844 .overlay_closable(false)
845 .on_position(move |resolved, trigger| {
846 position.trigger.set(trigger);
847 if explicit_position.is_none() {
848 position.popup.set(resolved.bounds);
849 }
850 if let Some(ancestor) = &ancestor {
851 *ancestor.child.borrow_mut() = Some(position.clone());
852 }
853 })
854 .trigger_with(move |open, _, _| {
855 let content = self
856 .composed_trigger
857 .map_or(self.trigger, |build| build(open, trigger));
858 div()
859 .id("menu-trigger")
860 .role(Role::Group)
861 .aria_expanded(open)
862 .when(controlled, |trigger| {
863 trigger
866 .on_action(move |_: &Confirm, window, cx| key_trigger(window, cx))
867 .on_mouse_down(self.mouse_button, move |_, window, cx| {
868 cx.stop_propagation();
869 mouse_trigger(window, cx);
870 })
871 })
872 .on_key_down(move |event, _, cx| {
873 if submenu && event.keystroke.key == forward && !key_state.get() {
874 key_state.set(true);
875 cx.notify(view);
876 cx.stop_propagation();
877 }
878 })
879 .child(content)
880 .into_any_element()
881 })
882 .content(move |state, window, cx| {
883 let motion = motion.expect("open menu has motion");
884 let close_level: Action = if controlled {
885 Rc::new(move |window, cx| popup_request(false, window, cx))
886 } else {
887 let own = cx.entity().downgrade();
888 Rc::new(move |window, cx| {
889 let _ = own.update(cx, |state: &mut PopoverState, cx| {
890 state.dismiss(window, cx);
891 });
892 })
893 };
894 let close: Action = {
895 let close_level = close_level.clone();
896 Rc::new(move |window, cx| {
897 close_level(window, cx);
898 if let Some(close_parent) = &self.close_parent {
899 close_parent(window, cx);
900 }
901 })
902 };
903 let dismissal = close_level.clone();
904 let escape = close_level.clone();
905 let item_bounds = bounds.clone();
906 let items = resolved_items.unwrap_or_default();
907 let content = window.with_id(menu_id, |window| {
908 menu_content(
909 items,
910 close,
911 submenu.then_some(close_level),
912 state.focus_handle(cx),
913 (direction, bounds.clone(), presentation, motion),
914 window,
915 cx,
916 )
917 });
918 let popup = div()
919 .id("dismiss-menu")
920 .opacity(motion.alpha)
921 .when(controlled, |popup| {
922 popup.on_action(move |_: &Cancel, window, cx| escape(window, cx))
923 })
924 .on_mouse_down_out(move |event, window, cx| {
925 let point = &event.position;
926 if bounds.contains(point) {
927 return;
928 }
929 dismissal(window, cx);
930 })
931 .child(content);
932 let pivot = item_bounds.clone();
933 let overlay = ScaledOverlay::new(popup, motion, move |menu| {
934 let anchor_bounds = explicit_position.map_or_else(
935 || pivot.trigger.get(),
936 |pos| Bounds::new(pos, Size::default()),
937 );
938 menu_pivot(menu, anchor_bounds)
939 });
940 let overlay = ThemeScope::inherit(overlay, window, cx);
941 if let Some(position) = explicit_position {
942 Positioner::corner(anchor, position)
943 .on_position(move |resolved| item_bounds.popup.set(resolved.bounds))
944 .occlude()
945 .child(overlay)
946 .into_any_element()
947 } else {
948 overlay
949 }
950 })
951 .into_any_element()
952 };
953 div()
954 .relative()
955 .child(menu_element)
956 .children(exit_view)
957 .into_any_element()
958 }
959}
960
961fn is_context_menu_key(keystroke: &gpui::Keystroke) -> bool {
962 let mods = &keystroke.modifiers;
963 if keystroke.key == "contextmenu" && !mods.modified() {
964 return true;
965 }
966 keystroke.key == "f10"
967 && mods.shift
968 && !mods.control
969 && !mods.alt
970 && !mods.platform
971 && !mods.function
972}