BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / menu / popup_menu.rs

popup_menu.rs

popup_menu.rs 52.6 KiB Download Raw
1use crate::ThemeStyled as _;
2use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
3use crate::actions::{SelectLeft, SelectRight};
4use crate::fluent::{
5 LISTBOX_MIN_WIDTH, MENU_DIVIDER_MARGIN_Y, MENU_ICON_GAP, MENU_ICON_GLYPH, MENU_ICON_SLOT,
6 MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LABEL_INSET, MENU_LIST_PADDING,
7 OPTION_CHECK_GAP, OPTION_CHECK_INSET, OPTION_CHECK_SIZE, OPTION_PADDING_RIGHT,
8};
9use crate::menu::menu_item::MenuItemElement;
10use crate::menu::selectors::{ITEMS_SELECTOR, icon_selector, item_selector, label_selector};
11use crate::scroll::ScrollableElement;
12use crate::{ActiveTheme, ElementExt, Icon, IconName, Sizable as _, h_flex, v_flex};
13use crate::{Side, Size, kbd::Kbd};
14use gpui::{
15 Action, Anchor, AnyElement, App, AppContext, Bounds, Context, DismissEvent, Edges, Entity,
16 EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyBinding,
17 ParentElement, Pixels, Render, Role, ScrollHandle, SharedString, StatefulInteractiveElement,
18 Styled, WeakEntity, Window, anchored, deferred, div, prelude::FluentBuilder, px, rems,
19};
20use gpui::{ClickEvent, Half, MouseDownEvent, OwnedMenuItem, Point, Subscription};
21use gpui_base::TestSupportExt as _;
22
23use std::rc::Rc;
24
25const CONTEXT: &str = "PopupMenu";
26
27pub fn init(cx: &mut App) {
28 cx.bind_keys([
29 KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
30 KeyBinding::new("escape", Cancel, Some(CONTEXT)),
31 KeyBinding::new("up", SelectUp, Some(CONTEXT)),
32 KeyBinding::new("down", SelectDown, Some(CONTEXT)),
33 KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
34 KeyBinding::new("right", SelectRight, Some(CONTEXT)),
35 ]);
36}
37
38/// An menu item in a popup menu.
39pub enum PopupMenuItem {
40 /// A menu separator item.
41 Separator,
42 /// A non-interactive label item.
43 Label(SharedString),
44 /// A standard menu item.
45 Item {
46 icon: Option<Icon>,
47 label: SharedString,
48 disabled: bool,
49 checked: bool,
50 is_link: bool,
51 action: Option<Box<dyn Action>>,
52 // For link item
53 handler: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
54 },
55 /// A menu item with custom element render.
56 ElementItem {
57 icon: Option<Icon>,
58 disabled: bool,
59 checked: bool,
60 action: Option<Box<dyn Action>>,
61 render: Box<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>,
62 handler: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
63 },
64 /// A submenu item that opens another popup menu.
65 Submenu {
66 icon: Option<Icon>,
67 label: SharedString,
68 disabled: bool,
69 menu: Entity<PopupMenu>,
70 },
71}
72
73impl FluentBuilder for PopupMenuItem {}
74impl PopupMenuItem {
75 /// Create a new menu item with the given label.
76 #[inline]
77 pub fn new(label: impl Into<SharedString>) -> Self {
78 PopupMenuItem::Item {
79 icon: None,
80 label: label.into(),
81 disabled: false,
82 checked: false,
83 action: None,
84 is_link: false,
85 handler: None,
86 }
87 }
88
89 /// Create a new menu item with custom element render.
90 #[inline]
91 pub fn element<F, E>(builder: F) -> Self
92 where
93 F: Fn(&mut Window, &mut App) -> E + 'static,
94 E: IntoElement,
95 {
96 PopupMenuItem::ElementItem {
97 icon: None,
98 disabled: false,
99 checked: false,
100 action: None,
101 render: Box::new(move |window, cx| builder(window, cx).into_any_element()),
102 handler: None,
103 }
104 }
105
106 /// Create a new submenu item that opens another popup menu.
107 #[inline]
108 pub fn submenu(label: impl Into<SharedString>, menu: Entity<PopupMenu>) -> Self {
109 PopupMenuItem::Submenu {
110 icon: None,
111 label: label.into(),
112 disabled: false,
113 menu,
114 }
115 }
116
117 /// Create a separator menu item.
118 #[inline]
119 pub fn separator() -> Self {
120 PopupMenuItem::Separator
121 }
122
123 /// Creates a label menu item.
124 #[inline]
125 pub fn label(label: impl Into<SharedString>) -> Self {
126 PopupMenuItem::Label(label.into())
127 }
128
129 /// Set the icon for the menu item.
130 ///
131 /// Only works for [`PopupMenuItem::Item`], [`PopupMenuItem::ElementItem`] and [`PopupMenuItem::Submenu`].
132 pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
133 match &mut self {
134 PopupMenuItem::Item { icon: i, .. } => {
135 *i = Some(icon.into());
136 }
137 PopupMenuItem::ElementItem { icon: i, .. } => {
138 *i = Some(icon.into());
139 }
140 PopupMenuItem::Submenu { icon: i, .. } => {
141 *i = Some(icon.into());
142 }
143 _ => {}
144 }
145 self
146 }
147
148 /// Set the action for the menu item.
149 ///
150 /// Only works for [`PopupMenuItem::Item`] and [`PopupMenuItem::ElementItem`].
151 pub fn action(mut self, action: Box<dyn Action>) -> Self {
152 match &mut self {
153 PopupMenuItem::Item { action: a, .. } => {
154 *a = Some(action);
155 }
156 PopupMenuItem::ElementItem { action: a, .. } => {
157 *a = Some(action);
158 }
159 _ => {}
160 }
161 self
162 }
163
164 /// Set the disabled state for the menu item.
165 ///
166 /// Only works for [`PopupMenuItem::Item`], [`PopupMenuItem::ElementItem`] and [`PopupMenuItem::Submenu`].
167 pub fn disabled(mut self, disabled: bool) -> Self {
168 match &mut self {
169 PopupMenuItem::Item { disabled: d, .. } => {
170 *d = disabled;
171 }
172 PopupMenuItem::ElementItem { disabled: d, .. } => {
173 *d = disabled;
174 }
175 PopupMenuItem::Submenu { disabled: d, .. } => {
176 *d = disabled;
177 }
178 _ => {}
179 }
180 self
181 }
182
183 /// Set checked state for the menu item.
184 ///
185 /// NOTE: If `check_side` is [`Side::Left`], the icon will replace with a check icon.
186 pub fn checked(mut self, checked: bool) -> Self {
187 match &mut self {
188 PopupMenuItem::Item { checked: c, .. } => {
189 *c = checked;
190 }
191 PopupMenuItem::ElementItem { checked: c, .. } => {
192 *c = checked;
193 }
194 _ => {}
195 }
196 self
197 }
198
199 /// Add a click handler for the menu item.
200 ///
201 /// Only works for [`PopupMenuItem::Item`] and [`PopupMenuItem::ElementItem`].
202 pub fn on_click<F>(mut self, handler: F) -> Self
203 where
204 F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
205 {
206 match &mut self {
207 PopupMenuItem::Item { handler: h, .. } => {
208 *h = Some(Rc::new(handler));
209 }
210 PopupMenuItem::ElementItem { handler: h, .. } => {
211 *h = Some(Rc::new(handler));
212 }
213 _ => {}
214 }
215 self
216 }
217
218 /// Create a link menu item.
219 #[inline]
220 pub fn link(label: impl Into<SharedString>, href: impl Into<String>) -> Self {
221 let href = href.into();
222 PopupMenuItem::Item {
223 icon: None,
224 label: label.into(),
225 disabled: false,
226 checked: false,
227 action: None,
228 is_link: true,
229 handler: Some(Rc::new(move |_, _, cx| cx.open_url(&href))),
230 }
231 }
232
233 #[inline]
234 fn is_clickable(&self) -> bool {
235 !matches!(self, PopupMenuItem::Separator)
236 && matches!(
237 self,
238 PopupMenuItem::Item {
239 disabled: false,
240 ..
241 } | PopupMenuItem::ElementItem {
242 disabled: false,
243 ..
244 } | PopupMenuItem::Submenu {
245 disabled: false,
246 ..
247 }
248 )
249 }
250
251 #[inline]
252 fn is_separator(&self) -> bool {
253 matches!(self, PopupMenuItem::Separator)
254 }
255
256 fn has_left_icon(&self, check_side: Side) -> bool {
257 match self {
258 PopupMenuItem::Item { icon, checked, .. } => {
259 icon.is_some() || (check_side.is_left() && *checked)
260 }
261 PopupMenuItem::ElementItem { icon, checked, .. } => {
262 icon.is_some() || (check_side.is_left() && *checked)
263 }
264 PopupMenuItem::Submenu { icon, .. } => icon.is_some(),
265 _ => false,
266 }
267 }
268
269 #[inline]
270 fn is_checked(&self) -> bool {
271 match self {
272 PopupMenuItem::Item { checked, .. } => *checked,
273 PopupMenuItem::ElementItem { checked, .. } => *checked,
274 _ => false,
275 }
276 }
277
278 fn a11y_label(&self) -> Option<SharedString> {
279 match self {
280 PopupMenuItem::Item { label, .. }
281 | PopupMenuItem::Label(label)
282 | PopupMenuItem::Submenu { label, .. } => Some(label.clone()),
283 PopupMenuItem::Separator | PopupMenuItem::ElementItem { .. } => None,
284 }
285 }
286}
287
288pub struct PopupMenu {
289 pub(crate) focus_handle: FocusHandle,
290 pub(crate) menu_items: Vec<PopupMenuItem>,
291 /// The focus handle of Entity to handle actions.
292 pub(crate) action_context: Option<FocusHandle>,
293 /// The focus to restore on dismiss. Unlike `action_context`, this does not
294 /// change where actions are dispatched: they still bubble from the menu's
295 /// own focus path (through the trigger element's ancestors).
296 pub(crate) previous_focus_handle: Option<FocusHandle>,
297 /// A focus handle on the trigger's dispatch path, so shortcut hints can
298 /// resolve against the key contexts the menu's actions bubble through on
299 /// the very frame the menu opens. GPUI looks a handle up in the previously
300 /// rendered frame, and the trigger was in it when the menu was not yet.
301 pub(crate) trigger_focus_handle: Option<FocusHandle>,
302 selected_index: Option<usize>,
303 min_width: Option<Pixels>,
304 max_width: Option<Pixels>,
305 max_height: Option<Pixels>,
306 bounds: Bounds<Pixels>,
307 size: Size,
308 check_side: Side,
309 listbox: bool,
310
311 /// The parent menu of this menu, if this is a submenu
312 parent_menu: Option<WeakEntity<Self>>,
313 scrollable: bool,
314 external_link_icon: bool,
315 scroll_handle: ScrollHandle,
316 // This will update on render
317 submenu_anchor: (Anchor, Pixels),
318
319 /// Paint priority for this menu layer. The top-level menu starts at 1 and
320 /// each nested submenu increments it, so deeper levels are always drawn on
321 /// top of shallower ones. This fixes background content (e.g. the
322 /// underlying list) bleeding through multi-level submenus, which happens
323 /// when nested `anchored` popovers share the same paint order.
324 ///
325 /// The top-level menu relies on its container (e.g. `Popover`,
326 /// `ContextMenu`) to `deferred`-draw it, and each submenu is deferred once
327 /// in `render_item` with `priority + 1`. Keeping a single deferred layer
328 /// per level matters because GPUI caps nested deferred depth (see
329 /// `prepaint_deferred_draws`).
330 ///
331 /// Deferring is also what lets a submenu open from a `scrollable` menu:
332 /// GPUI paints a deferred draw at the window level with no inherited
333 /// content mask, so the items container's `overflow_y_scroll` clip never
334 /// reaches it, while the scroll offset is still baked into its anchor.
335 priority: usize,
336
337 _subscriptions: Vec<Subscription>,
338}
339
340impl PopupMenu {
341 pub(crate) fn new(cx: &mut App) -> Self {
342 Self {
343 focus_handle: cx.focus_handle(),
344 action_context: None,
345 previous_focus_handle: None,
346 trigger_focus_handle: None,
347 parent_menu: None,
348 menu_items: Vec::new(),
349 selected_index: None,
350 min_width: None,
351 max_width: None,
352 max_height: None,
353 check_side: Side::Left,
354 listbox: false,
355 bounds: Bounds::default(),
356 scrollable: false,
357 scroll_handle: ScrollHandle::default(),
358 external_link_icon: true,
359 size: Size::default(),
360 submenu_anchor: (Anchor::TopLeft, Pixels::ZERO),
361 priority: gpui_base::POPUP_PRIORITY,
362 _subscriptions: vec![],
363 }
364 }
365
366 pub fn build(
367 window: &mut Window,
368 cx: &mut App,
369 f: impl FnOnce(Self, &mut Window, &mut Context<PopupMenu>) -> Self,
370 ) -> Entity<Self> {
371 cx.new(|cx| f(Self::new(cx), window, cx))
372 }
373
374 /// Set the focus handle of Entity to handle actions.
375 ///
376 /// When the menu is dismissed or before an action is triggered, the focus will be returned to this handle.
377 ///
378 /// Then the action will be dispatched to this handle.
379 pub fn action_context(mut self, handle: FocusHandle) -> Self {
380 self.action_context = Some(handle);
381 self
382 }
383
384 pub(crate) fn set_action_context(
385 &mut self,
386 action_context: Option<FocusHandle>,
387 cx: &mut Context<Self>,
388 ) {
389 self.action_context = action_context.clone();
390
391 for item in &self.menu_items {
392 if let PopupMenuItem::Submenu { menu, .. } = item {
393 menu.update(cx, |menu, cx| {
394 menu.set_action_context(action_context.clone(), cx);
395 });
396 }
397 }
398 }
399
400 /// Set the focus to restore when the menu is dismissed, without changing
401 /// where actions are dispatched.
402 pub(crate) fn set_previous_focus(
403 &mut self,
404 handle: Option<FocusHandle>,
405 cx: &mut Context<Self>,
406 ) {
407 self.previous_focus_handle = handle.clone();
408
409 for item in &self.menu_items {
410 if let PopupMenuItem::Submenu { menu, .. } = item {
411 menu.update(cx, |menu, cx| {
412 menu.set_previous_focus(handle.clone(), cx);
413 });
414 }
415 }
416 }
417
418 /// Set the focus handle on the trigger's dispatch path that shortcut hints
419 /// resolve against, without changing focus or where actions are dispatched.
420 pub(crate) fn set_trigger_focus(
421 &mut self,
422 handle: Option<FocusHandle>,
423 cx: &mut Context<Self>,
424 ) {
425 self.trigger_focus_handle = handle.clone();
426
427 for item in &self.menu_items {
428 if let PopupMenuItem::Submenu { menu, .. } = item {
429 menu.update(cx, |menu, cx| {
430 menu.set_trigger_focus(handle.clone(), cx);
431 });
432 }
433 }
434 }
435
436 /// Set min width of the popup menu, default is 120px
437 pub fn min_w(mut self, width: impl Into<Pixels>) -> Self {
438 self.min_width = Some(width.into());
439 self
440 }
441
442 /// Set max width of the popup menu, default is 500px
443 pub fn max_w(mut self, width: impl Into<Pixels>) -> Self {
444 self.max_width = Some(width.into());
445 self
446 }
447
448 /// Set max height of the popup menu, default is half of the window height
449 pub fn max_h(mut self, height: impl Into<Pixels>) -> Self {
450 self.max_height = Some(height.into());
451 self
452 }
453
454 /// Set the menu to be scrollable to show vertical scrollbar.
455 pub fn scrollable(mut self, scrollable: bool) -> Self {
456 self.scrollable = scrollable;
457 self
458 }
459
460 /// Lay the menu out as a Fluent `Listbox` under a select trigger: a check
461 /// column on every row and at least the trigger's width.
462 pub fn listbox(mut self, trigger_width: Pixels) -> Self {
463 self.listbox = true;
464 self.check_side = Side::Left;
465 self.min_width = Some(trigger_width.max(LISTBOX_MIN_WIDTH));
466 self
467 }
468
469 /// Set the side to show check icon, default is `Side::Left`.
470 pub fn check_side(mut self, side: Side) -> Self {
471 self.check_side = side;
472 self
473 }
474
475 /// Set the menu to show external link icon, default is true.
476 pub fn external_link_icon(mut self, visible: bool) -> Self {
477 self.external_link_icon = visible;
478 self
479 }
480
481 /// Add Menu Item
482 pub fn menu(self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
483 self.menu_with_disabled(label, action, false)
484 }
485
486 /// Add Menu Item with enable state
487 pub fn menu_with_enable(
488 mut self,
489 label: impl Into<SharedString>,
490 action: Box<dyn Action>,
491 enable: bool,
492 ) -> Self {
493 self.add_menu_item(label, None, action, !enable, false);
494 self
495 }
496
497 /// Add Menu Item with disabled state
498 pub fn menu_with_disabled(
499 mut self,
500 label: impl Into<SharedString>,
501 action: Box<dyn Action>,
502 disabled: bool,
503 ) -> Self {
504 self.add_menu_item(label, None, action, disabled, false);
505 self
506 }
507
508 /// Add label
509 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
510 self.menu_items.push(PopupMenuItem::label(label.into()));
511 self
512 }
513
514 /// Add Menu to open link
515 pub fn link(self, label: impl Into<SharedString>, href: impl Into<String>) -> Self {
516 self.link_with_disabled(label, href, false)
517 }
518
519 /// Add Menu to open link with disabled state
520 pub fn link_with_disabled(
521 mut self,
522 label: impl Into<SharedString>,
523 href: impl Into<String>,
524 disabled: bool,
525 ) -> Self {
526 let href = href.into();
527 self.menu_items
528 .push(PopupMenuItem::link(label, href).disabled(disabled));
529 self
530 }
531
532 /// Add Menu to open link
533 pub fn link_with_icon(
534 self,
535 label: impl Into<SharedString>,
536 icon: impl Into<Icon>,
537 href: impl Into<String>,
538 ) -> Self {
539 self.link_with_icon_and_disabled(label, icon, href, false)
540 }
541
542 /// Add Menu to open link with icon and disabled state
543 fn link_with_icon_and_disabled(
544 mut self,
545 label: impl Into<SharedString>,
546 icon: impl Into<Icon>,
547 href: impl Into<String>,
548 disabled: bool,
549 ) -> Self {
550 let href = href.into();
551 self.menu_items.push(
552 PopupMenuItem::link(label, href)
553 .icon(icon)
554 .disabled(disabled),
555 );
556 self
557 }
558
559 /// Add Menu Item with Icon.
560 pub fn menu_with_icon(
561 self,
562 label: impl Into<SharedString>,
563 icon: impl Into<Icon>,
564 action: Box<dyn Action>,
565 ) -> Self {
566 self.menu_with_icon_and_disabled(label, icon, action, false)
567 }
568
569 /// Add Menu Item with Icon and disabled state
570 pub fn menu_with_icon_and_disabled(
571 mut self,
572 label: impl Into<SharedString>,
573 icon: impl Into<Icon>,
574 action: Box<dyn Action>,
575 disabled: bool,
576 ) -> Self {
577 self.add_menu_item(label, Some(icon.into()), action, disabled, false);
578 self
579 }
580
581 /// Add Menu Item with check icon
582 pub fn menu_with_check(
583 self,
584 label: impl Into<SharedString>,
585 checked: bool,
586 action: Box<dyn Action>,
587 ) -> Self {
588 self.menu_with_check_and_disabled(label, checked, action, false)
589 }
590
591 /// Add Menu Item with check icon and disabled state
592 pub fn menu_with_check_and_disabled(
593 mut self,
594 label: impl Into<SharedString>,
595 checked: bool,
596 action: Box<dyn Action>,
597 disabled: bool,
598 ) -> Self {
599 self.add_menu_item(label, None, action, disabled, checked);
600 self
601 }
602
603 /// Add Menu Item with custom element render.
604 pub fn menu_element<F, E>(self, action: Box<dyn Action>, builder: F) -> Self
605 where
606 F: Fn(&mut Window, &mut App) -> E + 'static,
607 E: IntoElement,
608 {
609 self.menu_element_with_check(false, action, builder)
610 }
611
612 /// Add Menu Item with custom element render with disabled state.
613 pub fn menu_element_with_disabled<F, E>(
614 self,
615 action: Box<dyn Action>,
616 disabled: bool,
617 builder: F,
618 ) -> Self
619 where
620 F: Fn(&mut Window, &mut App) -> E + 'static,
621 E: IntoElement,
622 {
623 self.menu_element_with_check_and_disabled(false, action, disabled, builder)
624 }
625
626 /// Add Menu Item with custom element render with icon.
627 pub fn menu_element_with_icon<F, E>(
628 self,
629 icon: impl Into<Icon>,
630 action: Box<dyn Action>,
631 builder: F,
632 ) -> Self
633 where
634 F: Fn(&mut Window, &mut App) -> E + 'static,
635 E: IntoElement,
636 {
637 self.menu_element_with_icon_and_disabled(icon, action, false, builder)
638 }
639
640 /// Add Menu Item with custom element render with check state
641 pub fn menu_element_with_check<F, E>(
642 self,
643 checked: bool,
644 action: Box<dyn Action>,
645 builder: F,
646 ) -> Self
647 where
648 F: Fn(&mut Window, &mut App) -> E + 'static,
649 E: IntoElement,
650 {
651 self.menu_element_with_check_and_disabled(checked, action, false, builder)
652 }
653
654 /// Add Menu Item with custom element render with icon and disabled state
655 fn menu_element_with_icon_and_disabled<F, E>(
656 mut self,
657 icon: impl Into<Icon>,
658 action: Box<dyn Action>,
659 disabled: bool,
660 builder: F,
661 ) -> Self
662 where
663 F: Fn(&mut Window, &mut App) -> E + 'static,
664 E: IntoElement,
665 {
666 self.menu_items.push(
667 PopupMenuItem::element(builder)
668 .action(action)
669 .icon(icon)
670 .disabled(disabled),
671 );
672 self
673 }
674
675 /// Add Menu Item with custom element render with check state and disabled state
676 fn menu_element_with_check_and_disabled<F, E>(
677 mut self,
678 checked: bool,
679 action: Box<dyn Action>,
680 disabled: bool,
681 builder: F,
682 ) -> Self
683 where
684 F: Fn(&mut Window, &mut App) -> E + 'static,
685 E: IntoElement,
686 {
687 self.menu_items.push(
688 PopupMenuItem::element(builder)
689 .action(action)
690 .checked(checked)
691 .disabled(disabled),
692 );
693 self
694 }
695
696 /// Add a separator Menu Item
697 pub fn separator(mut self) -> Self {
698 if self.menu_items.is_empty() {
699 return self;
700 }
701
702 if let Some(PopupMenuItem::Separator) = self.menu_items.last() {
703 return self;
704 }
705
706 self.menu_items.push(PopupMenuItem::separator());
707 self
708 }
709
710 /// Add a Submenu
711 pub fn submenu(
712 self,
713 label: impl Into<SharedString>,
714 window: &mut Window,
715 cx: &mut Context<Self>,
716 f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
717 ) -> Self {
718 self.submenu_with_icon(None, label, window, cx, f)
719 }
720
721 /// Add a Submenu item with icon
722 pub fn submenu_with_icon(
723 mut self,
724 icon: Option<Icon>,
725 label: impl Into<SharedString>,
726 window: &mut Window,
727 cx: &mut Context<Self>,
728 f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
729 ) -> Self {
730 let submenu = PopupMenu::build(window, cx, f);
731 let parent_menu = cx.entity().downgrade();
732 let parent_priority = self.priority;
733 submenu.update(cx, |view, _| {
734 view.parent_menu = Some(parent_menu);
735 view.priority = parent_priority + 1;
736 });
737
738 self.menu_items.push(
739 PopupMenuItem::submenu(label, submenu).when_some(icon, |this, icon| this.icon(icon)),
740 );
741 self
742 }
743
744 /// Add menu item.
745 pub fn item(mut self, item: impl Into<PopupMenuItem>) -> Self {
746 let item: PopupMenuItem = item.into();
747 self.menu_items.push(item);
748 self
749 }
750
751 /// Replace all menu items by re-running a builder on this menu, keeping its
752 /// identity (focus, parent menu, layer priority).
753 ///
754 /// For menus whose content arrives asynchronously after the menu is shown,
755 /// e.g. swapping a "loading…" placeholder for the loaded items:
756 ///
757 /// ```ignore
758 /// cx.spawn_in(window, async move |menu, cx| {
759 /// let items = fetch_items().await;
760 /// _ = menu.update_in(cx, |menu, window, cx| {
761 /// menu.rebuild(window, cx, |menu, _, _| {
762 /// items.into_iter().fold(menu, |menu, item| {
763 /// menu.menu(item.label, Box::new(item.action))
764 /// })
765 /// });
766 /// });
767 /// })
768 /// .detach();
769 /// ```
770 pub fn rebuild(
771 &mut self,
772 window: &mut Window,
773 cx: &mut Context<Self>,
774 f: impl FnOnce(Self, &mut Window, &mut Context<Self>) -> Self,
775 ) {
776 let mut menu = std::mem::replace(self, Self::new(cx));
777 menu.menu_items.clear();
778 menu.selected_index = None;
779 *self = f(menu, window, cx);
780 cx.notify();
781 }
782
783 fn add_menu_item(
784 &mut self,
785 label: impl Into<SharedString>,
786 icon: Option<Icon>,
787 action: Box<dyn Action>,
788 disabled: bool,
789 checked: bool,
790 ) -> &mut Self {
791 self.menu_items.push(
792 PopupMenuItem::new(label)
793 .when_some(icon, |item, icon| item.icon(icon))
794 .disabled(disabled)
795 .checked(checked)
796 .action(action),
797 );
798 self
799 }
800
801 pub(super) fn with_menu_items<I>(
802 mut self,
803 items: impl IntoIterator<Item = I>,
804 window: &mut Window,
805 cx: &mut Context<Self>,
806 ) -> Self
807 where
808 I: Into<OwnedMenuItem>,
809 {
810 for item in items {
811 match item.into() {
812 OwnedMenuItem::Action {
813 name,
814 action,
815 checked,
816 disabled,
817 ..
818 } => {
819 self = self.menu_with_check_and_disabled(
820 name,
821 checked,
822 action.boxed_clone(),
823 disabled,
824 )
825 }
826 OwnedMenuItem::Separator => {
827 self = self.separator();
828 }
829 OwnedMenuItem::Submenu(submenu) => {
830 self = self.submenu(submenu.name, window, cx, move |menu, window, cx| {
831 menu.with_menu_items(submenu.items.clone(), window, cx)
832 })
833 }
834 OwnedMenuItem::SystemMenu(_) => {}
835 }
836 }
837
838 if self.menu_items.len() > 20 {
839 self.scrollable = true;
840 }
841
842 self
843 }
844
845 pub(crate) fn active_submenu(&self) -> Option<Entity<PopupMenu>> {
846 if let Some(ix) = self.selected_index {
847 if let Some(item) = self.menu_items.get(ix) {
848 return match item {
849 PopupMenuItem::Submenu { menu, .. } => Some(menu.clone()),
850 _ => None,
851 };
852 }
853 }
854
855 None
856 }
857
858 pub fn is_empty(&self) -> bool {
859 self.menu_items.is_empty()
860 }
861
862 fn clickable_menu_items(&self) -> impl Iterator<Item = (usize, &PopupMenuItem)> {
863 self.menu_items
864 .iter()
865 .enumerate()
866 .filter(|(_, item)| item.is_clickable())
867 }
868
869 fn on_click(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
870 cx.stop_propagation();
871 window.prevent_default();
872 self.selected_index = Some(ix);
873 self.confirm(&Confirm { secondary: false }, window, cx);
874 }
875
876 fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
877 match self.selected_index {
878 Some(index) => {
879 let item = self.menu_items.get(index);
880 match item {
881 Some(PopupMenuItem::Item {
882 handler, action, ..
883 }) => {
884 if let Some(handler) = handler {
885 handler(&ClickEvent::default(), window, cx);
886 } else if let Some(action) = action.as_ref() {
887 self.dispatch_confirm_action(action, window, cx);
888 }
889
890 self.dismiss(&Cancel, window, cx)
891 }
892 Some(PopupMenuItem::ElementItem {
893 handler, action, ..
894 }) => {
895 if let Some(handler) = handler {
896 handler(&ClickEvent::default(), window, cx);
897 } else if let Some(action) = action.as_ref() {
898 self.dispatch_confirm_action(action, window, cx);
899 }
900 self.dismiss(&Cancel, window, cx)
901 }
902 _ => {}
903 }
904 }
905 _ => {}
906 }
907 }
908
909 fn dispatch_confirm_action(
910 &self,
911 action: &Box<dyn Action>,
912 window: &mut Window,
913 cx: &mut Context<Self>,
914 ) {
915 if let Some(context) = self.action_context.as_ref() {
916 context.focus(window, cx);
917 }
918
919 window.dispatch_action(action.boxed_clone(), cx);
920 }
921
922 fn set_selected_index(&mut self, ix: usize, cx: &mut Context<Self>) {
923 if self.selected_index != Some(ix) {
924 self.selected_index = Some(ix);
925 self.scroll_handle.scroll_to_item(ix);
926 cx.notify();
927 }
928 }
929
930 fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
931 cx.stop_propagation();
932 let ix = self.selected_index.unwrap_or(0);
933
934 if let Some((prev_ix, _)) = self
935 .menu_items
936 .iter()
937 .enumerate()
938 .rev()
939 .find(|(i, item)| *i < ix && item.is_clickable())
940 {
941 self.set_selected_index(prev_ix, cx);
942 return;
943 }
944
945 let last_clickable_ix = self.clickable_menu_items().last().map(|(ix, _)| ix);
946 self.set_selected_index(last_clickable_ix.unwrap_or(0), cx);
947 }
948
949 fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
950 cx.stop_propagation();
951 let Some(ix) = self.selected_index else {
952 self.set_selected_index(0, cx);
953 return;
954 };
955
956 if let Some((next_ix, _)) = self
957 .menu_items
958 .iter()
959 .enumerate()
960 .find(|(i, item)| *i > ix && item.is_clickable())
961 {
962 self.set_selected_index(next_ix, cx);
963 return;
964 }
965
966 self.set_selected_index(0, cx);
967 }
968
969 fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
970 let handled = if matches!(self.submenu_anchor.0, Anchor::TopLeft | Anchor::BottomLeft) {
971 self._unselect_submenu(window, cx)
972 } else {
973 self._select_submenu(window, cx)
974 };
975
976 if self.parent_side(cx).is_left() {
977 self._focus_parent_menu(window, cx);
978 }
979
980 if handled {
981 return;
982 }
983
984 // For parent AppMenuBar to handle.
985 if self.parent_menu.is_none() {
986 cx.propagate();
987 }
988 }
989
990 fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
991 let handled = if matches!(self.submenu_anchor.0, Anchor::TopLeft | Anchor::BottomLeft) {
992 self._select_submenu(window, cx)
993 } else {
994 self._unselect_submenu(window, cx)
995 };
996
997 if self.parent_side(cx).is_right() {
998 self._focus_parent_menu(window, cx);
999 }
1000
1001 if handled {
1002 return;
1003 }
1004
1005 // For parent AppMenuBar to handle.
1006 if self.parent_menu.is_none() {
1007 cx.propagate();
1008 }
1009 }
1010
1011 fn _select_submenu(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1012 if let Some(active_submenu) = self.active_submenu() {
1013 // Focus the submenu, so that can be handle the action.
1014 active_submenu.update(cx, |view, cx| {
1015 view.set_selected_index(0, cx);
1016 view.focus_handle.focus(window, cx);
1017 });
1018 cx.notify();
1019 return true;
1020 }
1021
1022 return false;
1023 }
1024
1025 fn _unselect_submenu(&mut self, _: &mut Window, cx: &mut Context<Self>) -> bool {
1026 if let Some(active_submenu) = self.active_submenu() {
1027 active_submenu.update(cx, |view, cx| {
1028 view.selected_index = None;
1029 cx.notify();
1030 });
1031 return true;
1032 }
1033
1034 return false;
1035 }
1036
1037 fn _focus_parent_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1038 let Some(parent) = self.parent_menu.as_ref() else {
1039 return;
1040 };
1041 let Some(parent) = parent.upgrade() else {
1042 return;
1043 };
1044
1045 self.selected_index = None;
1046 parent.update(cx, |view, cx| {
1047 view.focus_handle.focus(window, cx);
1048 cx.notify();
1049 });
1050 }
1051
1052 fn parent_side(&self, cx: &App) -> Side {
1053 let Some(parent) = self.parent_menu.as_ref() else {
1054 return Side::Left;
1055 };
1056
1057 let Some(parent) = parent.upgrade() else {
1058 return Side::Left;
1059 };
1060
1061 match parent.read(cx).submenu_anchor.0 {
1062 Anchor::TopLeft | Anchor::BottomLeft => Side::Left,
1063 Anchor::TopRight | Anchor::BottomRight => Side::Right,
1064 // Center anchors are not used for submenu positioning, but we must cover them.
1065 _ => Side::Left,
1066 }
1067 }
1068
1069 /// Dismiss the menu and the entire parent chain.
1070 ///
1071 /// The submenu is closed together with its parent, same as macOS menus.
1072 fn dismiss(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
1073 self.selected_index = None;
1074 cx.emit(DismissEvent);
1075
1076 // Focus back to the previous focused handle, unless the item's click
1077 // handler has already moved focus elsewhere (e.g. opened a dialog and
1078 // focused its input) -- stealing focus back would break that.
1079 let focus_moved_away =
1080 window.focused(cx).is_some() && !self.focus_handle.contains_focused(window, cx);
1081 if !focus_moved_away {
1082 if let Some(handle) = self
1083 .previous_focus_handle
1084 .as_ref()
1085 .or(self.action_context.as_ref())
1086 {
1087 window.focus(handle, cx);
1088 }
1089 }
1090
1091 let Some(parent_menu) = self.parent_menu.clone() else {
1092 return;
1093 };
1094
1095 // Dismiss parent menu, when this menu is dismissed
1096 _ = parent_menu.update(cx, |view, cx| {
1097 view.dismiss(&Cancel, window, cx);
1098 });
1099 }
1100
1101 fn handle_dismiss(
1102 &mut self,
1103 position: &Point<Pixels>,
1104 window: &mut Window,
1105 cx: &mut Context<Self>,
1106 ) {
1107 // Do not dismiss, if click inside the parent menu
1108 if let Some(parent) = self.parent_menu.as_ref() {
1109 if let Some(parent) = parent.upgrade() {
1110 if parent.read(cx).bounds.contains(position) {
1111 return;
1112 }
1113 }
1114 }
1115
1116 // Do not dismiss, if there have an active submenu, the click may be
1117 // inside the submenu, let the submenu to handle it.
1118 //
1119 // Otherwise the submenu will be dismissed before its item's `on_click`.
1120 if self.active_submenu().is_some() {
1121 return;
1122 }
1123
1124 self.dismiss(&Cancel, window, cx);
1125 }
1126
1127 fn on_mouse_down_out(
1128 &mut self,
1129 e: &MouseDownEvent,
1130 window: &mut Window,
1131 cx: &mut Context<Self>,
1132 ) {
1133 self.handle_dismiss(&e.position, window, cx);
1134 }
1135
1136 fn render_key_binding(
1137 &self,
1138 action: Option<Box<dyn Action>>,
1139 window: &mut Window,
1140 _: &mut Context<Self>,
1141 ) -> Option<Kbd> {
1142 let action = action?;
1143
1144 // Each handle names a dispatch path GPUI can resolve in the previously
1145 // rendered frame: the explicit action target, the trigger the menu
1146 // opened from (already rendered when the menu first draws), the focus
1147 // the menu interrupted, then the menu's own path once it has been
1148 // rendered. A binding registered without a key context applies on
1149 // every path, so it is the last resort rather than the window's
1150 // leftover context stack, which only holds the path of whatever
1151 // element happened to paint last.
1152 [
1153 self.action_context.as_ref(),
1154 self.trigger_focus_handle.as_ref(),
1155 self.previous_focus_handle.as_ref(),
1156 Some(&self.focus_handle),
1157 ]
1158 .into_iter()
1159 .flatten()
1160 .find_map(|handle| Kbd::binding_for_action_in(action.as_ref(), handle, window))
1161 .or_else(|| Kbd::global_binding_for_action(action.as_ref(), window))
1162 .map(|this| {
1163 this.p_0()
1164 .flex_nowrap()
1165 .border_0()
1166 .bg(gpui::transparent_white())
1167 })
1168 }
1169
1170 fn render_icon(
1171 index: usize,
1172 has_icon: bool,
1173 checked: bool,
1174 icon: Option<Icon>,
1175 listbox: bool,
1176 ) -> Option<impl IntoElement> {
1177 if !has_icon {
1178 return None;
1179 }
1180
1181 let (slot, glyph) = if listbox {
1182 (OPTION_CHECK_SIZE, OPTION_CHECK_SIZE)
1183 } else {
1184 (MENU_ICON_SLOT, MENU_ICON_GLYPH)
1185 };
1186 let icon = match icon {
1187 Some(icon) if icon.has_explicit_size() => icon,
1188 Some(icon) => icon.with_size(glyph),
1189 None if checked => Icon::new(IconName::Check).with_size(glyph),
1190 None => Icon::empty().with_size(glyph),
1191 };
1192
1193 Some(
1194 h_flex()
1195 .debug_selector(|| icon_selector(index))
1196 .size(slot)
1197 .flex_none()
1198 .items_center()
1199 .justify_center()
1200 .child(icon),
1201 )
1202 }
1203
1204 #[inline]
1205 fn max_width(&self) -> Pixels {
1206 self.max_width.unwrap_or(px(500.))
1207 }
1208
1209 /// Calculate the anchor corner and left offset for child submenu
1210 fn update_submenu_menu_anchor(&mut self, window: &Window) {
1211 let bounds = self.bounds;
1212 let max_width = self.max_width();
1213 let (anchor, left) = if max_width + bounds.origin.x > window.bounds().size.width {
1214 (Anchor::TopRight, -px(16.))
1215 } else {
1216 (Anchor::TopLeft, bounds.size.width - px(8.))
1217 };
1218
1219 let is_bottom_pos = bounds.origin.y + bounds.size.height > window.bounds().size.height;
1220 self.submenu_anchor = if is_bottom_pos {
1221 (anchor.other_side_along(gpui::Axis::Vertical), left)
1222 } else {
1223 (anchor, left)
1224 };
1225 }
1226
1227 fn render_item(
1228 &self,
1229 ix: usize,
1230 item: &PopupMenuItem,
1231 options: RenderOptions,
1232 window: &mut Window,
1233 cx: &mut Context<Self>,
1234 ) -> MenuItemElement {
1235 let has_left_icon = options.has_left_icon || self.listbox;
1236 let is_left_check = options.check_side.is_left() && item.is_checked();
1237 let right_check_icon = if options.check_side.is_right() && item.is_checked() {
1238 Some(Icon::new(IconName::Check).xsmall())
1239 } else {
1240 None
1241 };
1242
1243 let selected = self.selected_index == Some(ix);
1244 const EDGE_PADDING: Pixels = px(4.);
1245 let listbox = self.listbox;
1246 let (padding_left, padding_right, icon_gap, label_inset) = if listbox {
1247 (
1248 OPTION_CHECK_INSET,
1249 OPTION_PADDING_RIGHT,
1250 OPTION_CHECK_GAP,
1251 px(0.),
1252 )
1253 } else {
1254 (
1255 MENU_ITEM_PADDING_X,
1256 MENU_ITEM_PADDING_X,
1257 MENU_ICON_GAP,
1258 MENU_LABEL_INSET,
1259 )
1260 };
1261
1262 let is_submenu = matches!(item, PopupMenuItem::Submenu { .. });
1263
1264 let (item_height, radius) = match self.size {
1265 Size::Small => (px(20.), options.radius.half()),
1266 _ => (MENU_ITEM_HEIGHT, options.radius),
1267 };
1268
1269 let this = MenuItemElement::new(ix)
1270 .debug_selector(move || item_selector(ix))
1271 .relative()
1272 .text_sm()
1273 .py_0()
1274 .pl(padding_left)
1275 .pr(padding_right)
1276 .rounded(radius)
1277 .items_center()
1278 .selected(selected)
1279 .on_hover(cx.listener(move |this, hovered, window, cx| {
1280 if *hovered {
1281 this.selected_index = Some(ix);
1282 } else if !is_submenu
1283 && this.selected_index == Some(ix)
1284 // A key press ends hover under a still pointer; keep the
1285 // highlight so the next arrow key moves on from this item.
1286 && !window.last_input_was_keyboard()
1287 {
1288 // TODO: Better handle the submenu unselection when hover out
1289 this.selected_index = None;
1290 }
1291
1292 cx.notify();
1293 }))
1294 .when_some(item.a11y_label(), |this, label| this.aria_label(label));
1295
1296 match item {
1297 PopupMenuItem::Separator => this
1298 .h_auto()
1299 .p_0()
1300 .my(MENU_DIVIDER_MARGIN_Y)
1301 .mx_neg_1()
1302 .border_b(px(1.))
1303 .border_color(cx.theme().tokens.sidebar_accent)
1304 .disabled(true),
1305 PopupMenuItem::Label(label) => this.disabled(true).cursor_default().child(
1306 h_flex()
1307 .cursor_default()
1308 .items_center()
1309 .gap(icon_gap)
1310 .children(Self::render_icon(ix, has_left_icon, false, None, listbox))
1311 .child(
1312 div().flex_1().px(label_inset).child(
1313 div()
1314 .debug_selector(|| label_selector(ix))
1315 .child(label.clone()),
1316 ),
1317 ),
1318 ),
1319 PopupMenuItem::ElementItem {
1320 render,
1321 icon,
1322 disabled,
1323 ..
1324 } => this
1325 .when(!disabled, |this| {
1326 this.on_click(
1327 cx.listener(move |this, _, window, cx| this.on_click(ix, window, cx)),
1328 )
1329 })
1330 .disabled(*disabled)
1331 .child(
1332 h_flex()
1333 .flex_1()
1334 .min_h(item_height)
1335 .items_center()
1336 .gap(icon_gap)
1337 .children(Self::render_icon(
1338 ix,
1339 has_left_icon,
1340 is_left_check,
1341 icon.clone(),
1342 listbox,
1343 ))
1344 .child(
1345 div().flex_1().min_w_0().px(label_inset).child(
1346 div()
1347 .debug_selector(|| label_selector(ix))
1348 .child((render)(window, cx)),
1349 ),
1350 )
1351 .children(right_check_icon.map(|icon| icon.ml_3())),
1352 ),
1353 PopupMenuItem::Item {
1354 icon,
1355 label,
1356 action,
1357 disabled,
1358 is_link,
1359 ..
1360 } => {
1361 let show_link_icon = *is_link && self.external_link_icon;
1362 let action = action.as_ref().map(|action| action.boxed_clone());
1363 let key = self.render_key_binding(action, window, cx);
1364
1365 this.when(!disabled, |this| {
1366 this.on_click(
1367 cx.listener(move |this, _, window, cx| this.on_click(ix, window, cx)),
1368 )
1369 })
1370 .disabled(*disabled)
1371 .h(item_height)
1372 .gap(icon_gap)
1373 .children(Self::render_icon(
1374 ix,
1375 has_left_icon,
1376 is_left_check,
1377 icon.clone(),
1378 listbox,
1379 ))
1380 .child(
1381 h_flex()
1382 .w_full()
1383 .px(label_inset)
1384 .gap_3()
1385 .items_center()
1386 .justify_between()
1387 .when(!show_link_icon, |this| {
1388 this.child(
1389 div()
1390 .debug_selector(|| label_selector(ix))
1391 .child(label.clone()),
1392 )
1393 })
1394 .children(right_check_icon)
1395 .when(show_link_icon, |this| {
1396 this.child(
1397 h_flex()
1398 .w_full()
1399 .justify_between()
1400 .gap_1p5()
1401 .child(label.clone())
1402 .child(
1403 Icon::new(IconName::ExternalLink)
1404 .xsmall()
1405 .text_color(cx.theme().muted_foreground),
1406 ),
1407 )
1408 })
1409 .children(key),
1410 )
1411 }
1412 PopupMenuItem::Submenu {
1413 icon,
1414 label,
1415 menu,
1416 disabled,
1417 } => this
1418 .selected(selected)
1419 .disabled(*disabled)
1420 .items_start()
1421 .child(
1422 h_flex()
1423 .min_h(item_height)
1424 .size_full()
1425 .items_center()
1426 .gap(icon_gap)
1427 .children(Self::render_icon(
1428 ix,
1429 has_left_icon,
1430 false,
1431 icon.clone(),
1432 listbox,
1433 ))
1434 .child(
1435 h_flex()
1436 .flex_1()
1437 .px(label_inset)
1438 .gap_2()
1439 .items_center()
1440 .justify_between()
1441 .child(
1442 div()
1443 .debug_selector(|| label_selector(ix))
1444 .child(label.clone()),
1445 )
1446 .child(
1447 Icon::new(IconName::ChevronRight)
1448 .xsmall()
1449 .text_color(cx.theme().muted_foreground),
1450 ),
1451 ),
1452 )
1453 .when(selected, |this| {
1454 this.child({
1455 let (anchor, left) = self.submenu_anchor;
1456 let is_bottom_pos =
1457 matches!(anchor, Anchor::BottomLeft | Anchor::BottomRight);
1458 deferred(
1459 anchored()
1460 .anchor(anchor)
1461 .child(
1462 div()
1463 .id("submenu")
1464 .test_support()
1465 .occlude()
1466 .when(is_bottom_pos, |this| this.bottom_0())
1467 .when(!is_bottom_pos, |this| this.top_neg_1())
1468 .left(left)
1469 .child(menu.clone()),
1470 )
1471 .snap_to_window_with_margin(Edges::all(EDGE_PADDING)),
1472 )
1473 .with_priority(self.priority + 1)
1474 })
1475 }),
1476 }
1477 }
1478}
1479
1480impl FluentBuilder for PopupMenu {}
1481impl EventEmitter<DismissEvent> for PopupMenu {}
1482impl Focusable for PopupMenu {
1483 fn focus_handle(&self, _: &App) -> FocusHandle {
1484 self.focus_handle.clone()
1485 }
1486}
1487
1488#[derive(Clone, Copy)]
1489struct RenderOptions {
1490 has_left_icon: bool,
1491 check_side: Side,
1492 radius: Pixels,
1493}
1494
1495impl Render for PopupMenu {
1496 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1497 self.update_submenu_menu_anchor(window);
1498
1499 // Submenus attached via the public `item()` + `PopupMenuItem::submenu()`
1500 // path (from contexts that only have the menu value, e.g. a table
1501 // delegate's `context_menu`) have no parent wired at construction time.
1502 // Wire them here so the dismiss chain, click-outside checks and keyboard
1503 // navigation treat them the same as `submenu()`-built children.
1504 let parent = cx.entity().downgrade();
1505 let parent_priority = self.priority;
1506 for item in &self.menu_items {
1507 if let PopupMenuItem::Submenu { menu, .. } = item {
1508 if menu.read(cx).parent_menu.is_none() {
1509 menu.update(cx, |menu, _| {
1510 menu.parent_menu = Some(parent.clone());
1511 menu.priority = parent_priority + 1;
1512 });
1513 }
1514 }
1515 }
1516
1517 let view = cx.entity().clone();
1518 let items_count = self.menu_items.len();
1519
1520 let max_height = self.max_height.unwrap_or_else(|| {
1521 let window_half_height = window.window_bounds().get_bounds().size.height * 0.5;
1522 window_half_height.min(px(450.))
1523 });
1524
1525 let has_left_icon = self
1526 .menu_items
1527 .iter()
1528 .any(|item| item.has_left_icon(self.check_side));
1529
1530 let max_width = self.max_width();
1531 let options = RenderOptions {
1532 has_left_icon,
1533 check_side: self.check_side,
1534 radius: cx.theme().radius.min(px(8.)),
1535 };
1536
1537 v_flex()
1538 .id("popup-menu")
1539 .debug_selector(|| "popup-menu".into())
1540 .test_support()
1541 .role(Role::Menu)
1542 .key_context(CONTEXT)
1543 .track_focus(&self.focus_handle)
1544 .on_action(cx.listener(Self::select_up))
1545 .on_action(cx.listener(Self::select_down))
1546 .on_action(cx.listener(Self::select_left))
1547 .on_action(cx.listener(Self::select_right))
1548 .on_action(cx.listener(Self::confirm))
1549 .on_action(cx.listener(Self::dismiss))
1550 .on_mouse_down_out(cx.listener(Self::on_mouse_down_out))
1551 .popover_style(window, cx)
1552 .text_color(cx.theme().popover_foreground)
1553 .relative()
1554 .occlude()
1555 .child(
1556 v_flex()
1557 .id("items")
1558 .debug_selector(|| ITEMS_SELECTOR.into())
1559 .p(MENU_LIST_PADDING)
1560 .gap_y(MENU_ITEM_GAP)
1561 .min_w(rems(8.))
1562 .when_some(self.min_width, |this, min_width| this.min_w(min_width))
1563 .max_w(max_width)
1564 .when(self.scrollable, |this| {
1565 this.max_h(max_height)
1566 .overflow_y_scroll()
1567 .track_scroll(&self.scroll_handle)
1568 })
1569 .children(
1570 self.menu_items
1571 .iter()
1572 .enumerate()
1573 // Ignore last separator
1574 .filter(|(ix, item)| !(*ix + 1 == items_count && item.is_separator()))
1575 .map(|(ix, item)| self.render_item(ix, item, options, window, cx)),
1576 )
1577 .on_prepaint(move |bounds, _, cx| view.update(cx, |r, _| r.bounds = bounds)),
1578 )
1579 .when(self.scrollable, |this| {
1580 this.vertical_scrollbar(&self.scroll_handle)
1581 })
1582 }
1583}
1584
1585#[cfg(test)]
1586mod tests {
1587 use super::*;
1588
1589 #[gpui::test]
1590 fn popup_menu_item_a11y_label_uses_visible_label(cx: &mut gpui::TestAppContext) {
1591 let submenu = cx.update(|cx| cx.new(|cx| PopupMenu::new(cx)));
1592
1593 assert_eq!(PopupMenuItem::new("Open").a11y_label(), Some("Open".into()));
1594 assert_eq!(
1595 PopupMenuItem::link("Docs", "https://example.com").a11y_label(),
1596 Some("Docs".into())
1597 );
1598 assert_eq!(
1599 PopupMenuItem::label("Recent files").a11y_label(),
1600 Some("Recent files".into())
1601 );
1602 assert_eq!(
1603 PopupMenuItem::submenu("More", submenu).a11y_label(),
1604 Some("More".into())
1605 );
1606 assert_eq!(PopupMenuItem::separator().a11y_label(), None);
1607 assert_eq!(PopupMenuItem::element(|_, _| div()).a11y_label(), None);
1608 }
1609}