1use std::cell::{Cell, RefCell};
2use std::rc::Rc;
3
4mod appearance;
5pub use appearance::{MenuColor, MenuItemStyle, MenuSurfaceStyle};
6use appearance::{Paint, Palette, axis_padding};
7
8use crate::motion::{OverlayMotion, ScaledOverlay, menu_pivot};
9use crate::{Icon, IconName};
10use gpui::{
11 Anchor, AnyElement, App, Axis, Bounds, ElementId, FocusHandle, Focusable, InteractiveElement,
12 IntoElement, MouseButton, ParentElement, Pixels, Point, RenderOnce, Role, ScrollHandle,
13 SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
14};
15use gpui_base::{
16 Popover, PopoverState, Positioner, TestSupportExt,
17 actions::{Cancel, Confirm},
18};
19use gpui_material_foundation::{logical_anchor, move_roving_focus, window_material_theme};
20use gpui_material_theme::{CornerRole, CornerShape, Direction, StateLayer, TypeRole};
21
22type Action = Rc<dyn Fn(&mut Window, &mut App)>;
23type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
24type ItemContent = Rc<dyn Fn() -> AnyElement>;
25type ComposedTrigger = Box<dyn FnOnce(bool, Action) -> AnyElement>;
26
27pub struct MenuItem {
29 id: ElementId,
30 label: SharedString,
31 disabled: bool,
32 kind: Kind,
33 slots: ItemSlots,
34 on_checked_change: Option<Change>,
35 style: MenuItemStyle,
36}
37
38enum Kind {
39 Action(Option<Action>),
40 Check(bool, Option<Action>),
41 Select(bool, Option<Action>),
42 Heading,
43 Section {
44 rows: Vec<MenuItem>,
45 style: MenuSurfaceStyle,
46 inactive_shape: Option<CornerShape>,
47 },
48 Submenu(Vec<MenuItem>),
49}
50
51#[derive(Clone, Default)]
52struct ItemSlots {
53 content: Option<ItemContent>,
54 leading: Option<ItemContent>,
55 supporting: Option<ItemContent>,
56 trailing: Option<ItemContent>,
57 selection_icon: Option<ItemContent>,
58}
59
60impl ItemSlots {
61 fn label(&self, label: SharedString) -> AnyElement {
62 self.content
63 .as_ref()
64 .map_or_else(|| label.into_any_element(), |content| content())
65 }
66
67 fn children(
68 &self,
69 label: SharedString,
70 marked: bool,
71 submenu: bool,
72 motion: OverlayMotion,
73 supporting_color: gpui::Hsla,
74 ) -> Vec<AnyElement> {
75 let icon_size = motion.px(18.);
76 let leading = if marked {
77 Some(self.selection_icon.as_ref().map_or_else(
78 || {
79 Icon::new(IconName::Check)
80 .size(icon_size)
81 .into_any_element()
82 },
83 |icon| icon(),
84 ))
85 } else {
86 self.leading.as_ref().map(|icon| icon())
87 };
88 let body = div()
89 .flex_1()
90 .min_w_0()
91 .overflow_hidden()
92 .child(div().truncate().child(self.label(label)))
93 .children(self.supporting.as_ref().map(|supporting| {
94 div()
95 .text_size(motion.px(12.))
96 .line_height(motion.px(16.))
97 .text_color(supporting_color)
98 .child(supporting())
99 }));
100 let mut children = vec![
101 div()
102 .min_w(icon_size)
103 .flex_none()
104 .children(leading)
105 .into_any_element(),
106 body.into_any_element(),
107 ];
108 children.extend(self.trailing.as_ref().map(|trailing| trailing()));
109 children.extend(submenu.then(|| {
110 Icon::new(IconName::ChevronRight)
111 .size(icon_size)
112 .mirror_in_rtl(true)
113 .into_any_element()
114 }));
115 children
116 }
117}
118
119struct MenuExitRow {
120 label: SharedString,
121 disabled: bool,
122 heading: bool,
123 section: Option<(MenuSurfaceStyle, Vec<MenuExitRow>)>,
124 selected: bool,
125 submenu: bool,
126 slots: ItemSlots,
127 style: MenuItemStyle,
128}
129
130impl From<&MenuItem> for MenuExitRow {
131 fn from(item: &MenuItem) -> Self {
132 Self {
133 label: item.label.clone(),
134 disabled: item.disabled,
135 heading: matches!(item.kind, Kind::Heading),
136 section: match &item.kind {
137 Kind::Section { rows, style, .. } => {
138 Some((*style, rows.iter().map(Self::from).collect()))
139 }
140 _ => None,
141 },
142 selected: matches!(item.kind, Kind::Check(true, _) | Kind::Select(true, _)),
143 submenu: matches!(item.kind, Kind::Submenu(_)),
144 slots: item.slots.clone(),
145 style: item.style,
146 }
147 }
148}
149
150impl MenuItem {
151 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
152 Self {
153 id: id.into(),
154 label: label.into(),
155 disabled: false,
156 kind: Kind::Action(None),
157 slots: ItemSlots::default(),
158 on_checked_change: None,
159 style: MenuItemStyle::default(),
160 }
161 }
162
163 pub fn group(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
164 Self {
165 kind: Kind::Heading,
166 ..Self::new(id, title)
167 }
168 }
169
170 pub fn section(
172 id: impl Into<ElementId>,
173 name: impl Into<SharedString>,
174 rows: impl IntoIterator<Item = MenuItem>,
175 ) -> Self {
176 Self {
177 kind: Kind::Section {
178 rows: rows.into_iter().collect(),
179 style: MenuSurfaceStyle::default(),
180 inactive_shape: None,
181 },
182 ..Self::new(id, name)
183 }
184 }
185
186 pub fn group_appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
188 if let Kind::Section { style, .. } = &mut self.kind {
189 *style = appearance;
190 }
191 self
192 }
193
194 pub fn inactive_shape(mut self, shape: CornerShape) -> Self {
196 if let Kind::Section { inactive_shape, .. } = &mut self.kind {
197 *inactive_shape = Some(shape);
198 }
199 self
200 }
201
202 pub fn appearance(mut self, style: MenuItemStyle) -> Self {
204 self.style = style;
205 self
206 }
207
208 pub fn submenu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
209 self.kind = Kind::Submenu(items.into_iter().collect());
210 self
211 }
212
213 pub fn disabled(mut self, disabled: bool) -> Self {
214 self.disabled = disabled;
215 self
216 }
217
218 pub fn checked(mut self, checked: bool) -> Self {
219 self.kind = Kind::Check(checked, self.action());
220 self
221 }
222
223 pub fn selected(mut self, selected: bool) -> Self {
224 self.kind = Kind::Select(selected, self.action());
225 self
226 }
227
228 pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
231 self.slots.content = Some(Rc::new(move || build().into_any_element()));
232 self
233 }
234
235 pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
237 self.slots.leading = Some(Rc::new(move || build().into_any_element()));
238 self
239 }
240
241 pub fn supporting<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
243 self.slots.supporting = Some(Rc::new(move || build().into_any_element()));
244 self
245 }
246
247 pub fn trailing<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
249 self.slots.trailing = Some(Rc::new(move || build().into_any_element()));
250 self
251 }
252
253 pub fn selection_icon<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
255 self.slots.selection_icon = Some(Rc::new(move || build().into_any_element()));
256 self
257 }
258
259 pub fn on_checked_change(
262 mut self,
263 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
264 ) -> Self {
265 self.on_checked_change = Some(Rc::new(callback));
266 self
267 }
268
269 fn action(&self) -> Option<Action> {
270 match &self.kind {
271 Kind::Action(action) | Kind::Check(_, action) | Kind::Select(_, action) => {
272 action.clone()
273 }
274 _ => None,
275 }
276 }
277
278 fn activation(&self) -> Option<Action> {
279 if let Kind::Check(checked, _) = self.kind
280 && let Some(callback) = &self.on_checked_change
281 {
282 let callback = callback.clone();
283 return Some(Rc::new(move |window, cx| callback(!checked, window, cx)));
284 }
285 self.action()
286 }
287
288 pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
289 match &mut self.kind {
290 Kind::Action(handler) | Kind::Check(_, handler) | Kind::Select(_, handler) => {
291 *handler = Some(Rc::new(action));
292 }
293 _ => {}
294 }
295 self
296 }
297}
298
299#[derive(IntoElement)]
302pub struct Menu {
303 id: ElementId,
304 trigger: AnyElement,
305 items: Vec<MenuItem>,
306 mouse_button: MouseButton,
307 anchor: Anchor,
308 close_parent: Option<Action>,
309 enabled: bool,
310 ancestor: Option<Rc<PopupBounds>>,
311 composed_trigger: Option<ComposedTrigger>,
312 open: Option<bool>,
313 on_open_change: Option<Change>,
314 on_dismiss: Option<Action>,
315 color: MenuColor,
316 appearance: MenuSurfaceStyle,
317 decoration: Option<ItemContent>,
318 scroll: Option<ScrollHandle>,
319 offset: Pixels,
320 position: Option<Point<Pixels>>,
321}
322
323#[derive(Default)]
324struct PopupBounds {
325 trigger: Cell<Bounds<gpui::Pixels>>,
326 popup: Cell<Bounds<gpui::Pixels>>,
327 child: RefCell<Option<Rc<PopupBounds>>>,
328 presented: RefCell<Option<PresentedMenu>>,
329 scroll: ScrollHandle,
330 motion: Cell<Option<OverlayMotion>>,
331 open: Rc<Cell<bool>>,
332}
333
334#[derive(Clone)]
335struct MenuPresentation {
336 color: MenuColor,
337 appearance: MenuSurfaceStyle,
338 decoration: Option<ItemContent>,
339 scroll: ScrollHandle,
340}
341
342struct PresentedMenu {
343 items: Vec<MenuExitRow>,
344 presentation: MenuPresentation,
345}
346
347impl PopupBounds {
348 fn contains(&self, point: &gpui::Point<gpui::Pixels>) -> bool {
349 self.trigger.get().contains(point)
350 || self.popup.get().contains(point)
351 || self
352 .child
353 .borrow()
354 .as_ref()
355 .is_some_and(|child| child.open.get() && child.contains(point))
356 }
357}
358
359impl Menu {
360 pub fn new(
361 id: impl Into<ElementId>,
362 trigger: impl IntoElement,
363 items: impl IntoIterator<Item = MenuItem>,
364 ) -> Self {
365 Self {
366 id: id.into(),
367 trigger: trigger.into_any_element(),
368 items: items.into_iter().collect(),
369 mouse_button: MouseButton::Left,
370 anchor: Anchor::TopLeft,
371 close_parent: None,
372 enabled: true,
373 ancestor: None,
374 composed_trigger: None,
375 open: None,
376 on_open_change: None,
377 on_dismiss: None,
378 color: MenuColor::default(),
379 appearance: MenuSurfaceStyle::default(),
380 decoration: None,
381 scroll: None,
382 offset: px(4.),
383 position: None,
384 }
385 }
386
387 pub fn context(mut self) -> Self {
389 self.mouse_button = MouseButton::Right;
390 self
391 }
392
393 pub fn anchor(mut self, anchor: Anchor) -> Self {
394 self.anchor = anchor;
395 self
396 }
397
398 pub fn offset(mut self, offset: Pixels) -> Self {
400 if f32::from(offset).is_finite() {
401 self.offset = offset;
402 }
403 self
404 }
405
406 pub fn position(mut self, position: Point<Pixels>) -> Self {
408 self.position = (f32::from(position.x).is_finite() && f32::from(position.y).is_finite())
409 .then_some(position);
410 self
411 }
412
413 pub fn color(mut self, color: MenuColor) -> Self {
415 self.color = color;
416 self
417 }
418
419 pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
421 self.appearance = appearance;
422 self
423 }
424
425 pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
428 self.decoration = Some(Rc::new(move || build().into_any_element()));
429 self
430 }
431
432 pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
434 self.scroll = Some(scroll.clone());
435 self
436 }
437
438 pub fn composed(
443 id: impl Into<ElementId>,
444 items: impl IntoIterator<Item = MenuItem>,
445 trigger: impl FnOnce(bool, Action) -> AnyElement + 'static,
446 ) -> Self {
447 let mut menu = Self::new(id, div(), items);
448 menu.composed_trigger = Some(Box::new(trigger));
449 menu
450 }
451
452 pub fn open(mut self, open: bool) -> Self {
454 self.open = Some(open);
455 self
456 }
457
458 pub fn on_open_change(
461 mut self,
462 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
463 ) -> Self {
464 self.on_open_change = Some(Rc::new(callback));
465 self
466 }
467
468 pub fn on_dismiss(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
471 self.on_dismiss = Some(Rc::new(callback));
472 self
473 }
474}
475
476impl RenderOnce for Menu {
477 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
478 let direction = window_material_theme(window, cx).layout.direction;
479 let submenu = self.close_parent.is_some();
480 if !self.enabled {
481 return self.trigger;
482 }
483 let view = window.current_view();
484 let bounds = window
485 .use_keyed_state((self.id.clone(), "menu-bounds"), cx, |_, _| {
486 Rc::new(PopupBounds::default())
487 })
488 .read(cx)
489 .clone();
490 let open_state = bounds.open.clone();
491 let controlled = self.open.is_some();
492 let open = self.open.unwrap_or_else(|| open_state.get());
493 open_state.set(open);
494 let key_state = open_state.clone();
495 let trigger_state = open_state.clone();
496 let request: Change = {
497 let on_open_change = self.on_open_change;
498 let on_dismiss = self.on_dismiss;
499 Rc::new(move |requested, window, cx| {
500 if !controlled {
501 open_state.set(requested);
502 cx.notify(view);
503 }
504 if let Some(callback) = &on_open_change {
505 callback(requested, window, cx);
506 }
507 if !requested && let Some(callback) = &on_dismiss {
508 callback(window, cx);
509 }
510 })
511 };
512 let trigger: Action = {
513 let request = request.clone();
514 Rc::new(move |window, cx| {
515 let displayed = if controlled {
516 open
517 } else {
518 trigger_state.get()
519 };
520 request(!displayed, window, cx);
521 })
522 };
523 let key_trigger = trigger.clone();
524 let mouse_trigger = trigger.clone();
525 let popover_request = request.clone();
526 let popup_request = request;
527 let motion = OverlayMotion::sample(&self.id, open, window, cx);
528 let position = bounds.clone();
529 let ancestor = self.ancestor.clone();
530 let anchor = logical_anchor(self.anchor, direction);
531 let explicit_position = self.position;
532 let presentation = MenuPresentation {
533 color: self.color,
534 appearance: self.appearance,
535 decoration: self.decoration,
536 scroll: self.scroll.unwrap_or_else(|| bounds.scroll.clone()),
537 };
538 if open {
539 *bounds.presented.borrow_mut() = Some(PresentedMenu {
540 items: self.items.iter().map(MenuExitRow::from).collect(),
541 presentation: presentation.clone(),
542 });
543 }
544 bounds.motion.set(motion);
545 let forward = if direction == Direction::Rtl {
546 "left"
547 } else {
548 "right"
549 };
550 let exit_view = motion.filter(|_| !open).map(|motion| {
551 let mut exits = div();
554 let mut level = Some(bounds.clone());
555 let mut depth = 0;
556 while let Some(bounds) = level {
557 let Some(previous) = bounds.motion.get() else {
558 break;
559 };
560 let motion = if depth == 0 {
561 motion
562 } else {
563 OverlayMotion {
564 scale: 0.8 + (motion.scale - 0.8) * (previous.scale - 0.8) / 0.2,
565 alpha: motion.alpha * previous.alpha,
566 }
567 };
568 exits = exits.children(menu_exit(
569 (&self.id, depth),
570 &bounds,
571 motion,
572 direction,
573 window,
574 cx,
575 ));
576 level = bounds.child.borrow().clone();
577 depth += 1;
578 }
579 exits
580 });
581 if !open && motion.is_none() {
582 bounds.presented.borrow_mut().take();
583 bounds.child.borrow_mut().take();
584 }
585 let menu_id = self.id.clone();
586 let menu = Popover::new(self.id)
587 .open(open)
588 .on_open_change(move |open, window, cx| popover_request(*open, window, cx))
589 .anchor(anchor)
590 .offset(self.offset)
591 .mouse_button(self.mouse_button)
592 .overlay_closable(false)
593 .on_position(move |resolved, trigger| {
594 position.trigger.set(trigger);
595 if explicit_position.is_none() {
596 position.popup.set(resolved.bounds);
597 }
598 if let Some(ancestor) = &ancestor {
599 *ancestor.child.borrow_mut() = Some(position.clone());
600 }
601 })
602 .trigger_with(move |open, _, _| {
603 let content = self
604 .composed_trigger
605 .map_or(self.trigger, |build| build(open, trigger));
606 div()
607 .id("menu-trigger")
608 .role(Role::Group)
609 .aria_expanded(open)
610 .when(controlled, |trigger| {
611 trigger
614 .on_action(move |_: &Confirm, window, cx| key_trigger(window, cx))
615 .on_mouse_down(self.mouse_button, move |_, window, cx| {
616 cx.stop_propagation();
617 mouse_trigger(window, cx);
618 })
619 })
620 .on_key_down(move |event, _, cx| {
621 if submenu && event.keystroke.key == forward && !key_state.get() {
622 key_state.set(true);
623 cx.notify(view);
624 cx.stop_propagation();
625 }
626 })
627 .child(content)
628 .into_any_element()
629 })
630 .content(move |state, window, cx| {
631 let motion = motion.expect("open menu has motion");
632 let close_level: Action = if controlled {
633 Rc::new(move |window, cx| popup_request(false, window, cx))
634 } else {
635 let own = cx.entity().downgrade();
636 Rc::new(move |window, cx| {
637 let _ = own.update(cx, |state: &mut PopoverState, cx| {
638 state.dismiss(window, cx);
639 });
640 })
641 };
642 let close: Action = {
643 let close_level = close_level.clone();
644 Rc::new(move |window, cx| {
645 close_level(window, cx);
646 if let Some(close_parent) = &self.close_parent {
647 close_parent(window, cx);
648 }
649 })
650 };
651 let dismissal = close_level.clone();
652 let escape = close_level.clone();
653 let item_bounds = bounds.clone();
654 let content = window.with_id(menu_id, |window| {
655 menu_content(
656 self.items,
657 close,
658 submenu.then_some(close_level),
659 state.focus_handle(cx),
660 (direction, bounds.clone(), presentation, motion),
661 window,
662 cx,
663 )
664 });
665 let popup = div()
666 .id("dismiss-menu")
667 .opacity(motion.alpha)
668 .when(controlled, |popup| {
669 popup.on_action(move |_: &Cancel, window, cx| escape(window, cx))
670 })
671 .on_mouse_down_out(move |event, window, cx| {
672 let point = &event.position;
673 if bounds.contains(point) {
674 return;
675 }
676 dismissal(window, cx);
677 })
678 .child(content);
679 let pivot = item_bounds.clone();
680 let overlay = ScaledOverlay::new(popup, motion, move |menu| {
681 menu_pivot(menu, pivot.trigger.get())
682 });
683 if let Some(position) = explicit_position {
684 Positioner::corner(anchor, position)
685 .on_position(move |resolved| item_bounds.popup.set(resolved.bounds))
686 .occlude()
687 .child(overlay)
688 .into_any_element()
689 } else {
690 overlay.into_any_element()
691 }
692 });
693 div()
694 .relative()
695 .child(menu)
696 .children(exit_view)
697 .into_any_element()
698 }
699}
700
701fn menu_exit(
702 (id, depth): (&ElementId, usize),
703 bounds: &PopupBounds,
704 motion: OverlayMotion,
705 direction: Direction,
706 window: &Window,
707 cx: &App,
708) -> Option<AnyElement> {
709 let exit = bounds.popup.get();
710 if exit.size.width <= px(0.) {
711 return None;
712 }
713 let presented = bounds.presented.borrow();
714 let PresentedMenu {
715 items,
716 presentation,
717 } = presented.as_ref()?;
718 let trigger = bounds.trigger.get();
719 let paint = Paint {
720 theme: window_material_theme(window, cx),
721 motion,
722 direction,
723 };
724 let palette = presentation
725 .color
726 .palette(false, presentation.appearance.container);
727 let surface = div()
728 .id(if depth == 0 {
729 ElementId::from((id.clone(), "menu-exit"))
730 } else {
731 ElementId::from((id.clone(), format!("submenu-exit-{depth}")))
732 })
733 .test_support()
734 .h(exit.size.height * motion.scale)
735 .w(exit.size.width * motion.scale)
736 .opacity(motion.alpha)
737 .overflow_y_scroll()
738 .track_scroll(&presentation.scroll)
739 .child(
740 paint
741 .surface(presentation.appearance, palette, false)
742 .w_full()
743 .children(presentation.decoration.as_ref().map(|build| build()))
744 .children(exit_rows(items, paint, presentation.color, palette, false)),
745 )
746 .child(div().absolute().inset_0().occlude());
747 Some(
748 gpui::deferred(
749 Positioner::corner(Anchor::TopLeft, exit.origin).child(ScaledOverlay::new(
750 super::text_style(surface, TypeRole::LabelLarge, motion.scale, window, cx),
751 motion,
752 move |bounds| menu_pivot(bounds, trigger),
753 )),
754 )
755 .with_priority(100 + depth)
756 .into_any_element(),
757 )
758}
759
760fn exit_rows(
761 items: &[MenuExitRow],
762 paint: Paint<'_>,
763 preset: MenuColor,
764 palette: Palette,
765 grouped: bool,
766) -> Vec<AnyElement> {
767 items
768 .iter()
769 .enumerate()
770 .map(|(index, item)| {
771 if let Some((style, children)) = &item.section {
772 let palette = preset.palette(true, style.container);
773 return paint
774 .surface(*style, palette, true)
775 .child(menu_heading(
776 item.slots.label(item.label.clone()),
777 paint,
778 palette,
779 ))
780 .children(exit_rows(children, paint, preset, palette, true))
781 .into_any_element();
782 }
783 if item.heading {
784 return menu_heading(item.slots.label(item.label.clone()), paint, palette)
785 .into_any_element();
786 }
787 let style = row_shape(item.style, grouped, index, items.len(), item.selected);
788 let (background, ink, supporting) =
789 row_colors(item.style, paint, palette, item.selected, !item.disabled);
790 row_layout(div().flex().items_center(), item.style, style, paint)
791 .text_color(ink)
792 .when(item.selected || item.style.container.is_some(), |row| {
793 row.bg(background)
794 })
795 .children(item.slots.children(
796 item.label.clone(),
797 item.selected,
798 item.submenu,
799 paint.motion,
800 supporting,
801 ))
802 .into_any_element()
803 })
804 .collect()
805}
806
807fn menu_heading(label: AnyElement, paint: Paint<'_>, palette: Palette) -> gpui::Div {
808 div()
809 .px(paint.motion.px(12.))
810 .py(paint.motion.px(8.))
811 .text_color(paint.color(palette.muted))
812 .child(label)
813}
814
815fn row_shape(
816 style: MenuItemStyle,
817 grouped: bool,
818 index: usize,
819 count: usize,
820 selected: bool,
821) -> CornerShape {
822 if selected {
823 if let Some(shape) = style.selected_shape {
824 return shape;
825 }
826 if grouped {
827 return CornerRole::Medium.shape();
828 }
829 }
830 if let Some(shape) = style.shape {
831 return shape;
832 }
833 if !grouped {
834 return CornerRole::None.shape();
835 }
836 match (index, count) {
837 (0, 2..) => CornerShape::Radii([12., 12., 4., 4.]),
838 (index, 2..) if index + 1 == count => CornerShape::Radii([4., 4., 12., 12.]),
839 _ => CornerRole::ExtraSmall.shape(),
840 }
841}
842
843fn row_layout<E: Styled + FluentBuilder>(
844 element: E,
845 style: MenuItemStyle,
846 shape: CornerShape,
847 paint: Paint<'_>,
848) -> E {
849 let element = element
850 .justify_start()
851 .w_full()
852 .min_h(paint.motion.px(48.))
853 .line_height(paint.motion.px(20.))
854 .gap(paint.length(style.spacing.unwrap_or(px(8.))))
855 .when(paint.direction == Direction::Rtl, Styled::flex_row_reverse);
856 let element = paint.padding(
857 element,
858 style
859 .padding
860 .unwrap_or_else(|| axis_padding(px(12.), px(0.))),
861 );
862 paint.shape(element, shape)
863}
864
865fn row_colors(
866 style: MenuItemStyle,
867 paint: Paint<'_>,
868 palette: Palette,
869 marked: bool,
870 enabled: bool,
871) -> (gpui::Hsla, gpui::Hsla, gpui::Hsla) {
872 let (background, foreground, muted) = if marked {
873 let ink = style.selected_content.unwrap_or(palette.selected_ink);
874 (
875 style.selected_container.unwrap_or(palette.selected),
876 ink,
877 ink,
878 )
879 } else {
880 (
881 style.container.unwrap_or(palette.container),
882 style.content.unwrap_or(palette.ink),
883 style.supporting.unwrap_or(palette.muted),
884 )
885 };
886 let factor = if enabled { 1. } else { 0.38 };
887 (
888 paint.color(background),
889 paint.color(foreground).opacity(factor),
890 paint.color(muted).opacity(factor),
891 )
892}
893
894fn menu_content(
895 items: Vec<MenuItem>,
896 close: Action,
897 close_level: Option<Action>,
898 popup_focus: FocusHandle,
899 (direction, bounds, presentation, motion): (
900 Direction,
901 Rc<PopupBounds>,
902 MenuPresentation,
903 OverlayMotion,
904 ),
905 window: &mut Window,
906 cx: &mut App,
907) -> AnyElement {
908 fn collect_focus(
909 items: &[MenuItem],
910 focus: &mut Vec<(FocusHandle, bool)>,
911 window: &mut Window,
912 cx: &mut App,
913 ) {
914 for item in items {
915 match &item.kind {
916 Kind::Heading => {}
917 Kind::Section { rows, .. } => collect_focus(rows, focus, window, cx),
918 _ => {
919 let handle = window
920 .use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| cx.focus_handle());
921 focus.push((handle.read(cx).clone(), !item.disabled));
922 }
923 }
924 }
925 }
926 let mut focus = Vec::new();
927 collect_focus(&items, &mut focus, window, cx);
928 let handles = focus.clone();
929 if popup_focus.is_focused(window)
930 && let Some((first, _)) = handles.iter().find(|(_, enabled)| *enabled)
931 {
932 let first = first.clone();
933 window.defer(cx, move |window, cx| {
934 if popup_focus.is_focused(window) {
935 first.focus(window, cx);
936 }
937 });
938 }
939 let viewport = window.viewport_size();
940 let limit = (viewport.height * 0.7).min(px(420.)) * motion.scale;
941 let available_width = (viewport.width - px(16.)).max(px(0.)) * motion.scale;
942 let theme = window_material_theme(window, cx).clone();
943 let paint = Paint {
944 theme: &theme,
945 motion,
946 direction,
947 };
948 let palette = presentation
949 .color
950 .palette(false, presentation.appearance.container);
951 let mut rows = ActiveRows {
952 paint,
953 focus: focus.into_iter(),
954 close,
955 bounds,
956 preset: presentation.color,
957 };
958 let menu = div()
959 .id(if close_level.is_some() {
960 "submenu-content"
961 } else {
962 "menu"
963 })
964 .test_support()
965 .role(Role::Menu)
966 .overflow_y_scroll()
967 .track_scroll(&presentation.scroll)
968 .max_h(limit)
969 .on_key_down(move |event, window, cx| {
970 let backward = if direction == Direction::Rtl {
971 "right"
972 } else {
973 "left"
974 };
975 if event.keystroke.key == backward
976 && let Some(close_level) = &close_level
977 {
978 close_level(window, cx);
979 cx.stop_propagation();
980 return;
981 }
982 let items: Vec<_> = handles
983 .iter()
984 .map(|(focus, enabled)| (focus, *enabled))
985 .collect();
986 if move_roving_focus(
987 &items,
988 &event.keystroke.key,
989 Axis::Vertical,
990 direction,
991 window,
992 cx,
993 )
994 .is_some()
995 {
996 cx.stop_propagation();
997 }
998 })
999 .child(
1000 paint
1001 .surface(presentation.appearance, palette, false)
1002 .min_w(motion.px(112.).min(available_width))
1003 .max_w(motion.px(280.).min(available_width))
1004 .children(presentation.decoration.as_ref().map(|build| build()))
1005 .children(rows.render(items, palette, false, window, cx)),
1006 );
1007 super::text_style(menu, TypeRole::LabelLarge, motion.scale, window, cx).into_any_element()
1008}
1009
1010struct ActiveRows<'a> {
1011 paint: Paint<'a>,
1012 focus: std::vec::IntoIter<(FocusHandle, bool)>,
1013 close: Action,
1014 bounds: Rc<PopupBounds>,
1015 preset: MenuColor,
1016}
1017
1018impl ActiveRows<'_> {
1019 fn render(
1020 &mut self,
1021 items: Vec<MenuItem>,
1022 palette: Palette,
1023 grouped: bool,
1024 window: &mut Window,
1025 cx: &mut App,
1026 ) -> Vec<AnyElement> {
1027 let count = items.len();
1028 items
1029 .into_iter()
1030 .enumerate()
1031 .map(|(index, item)| {
1032 if let Kind::Section {
1033 rows,
1034 mut style,
1035 inactive_shape,
1036 } = item.kind
1037 {
1038 let palette = self.preset.palette(true, style.container);
1039 let state = inactive_shape.map(|shape| {
1040 let state = window.use_keyed_state(
1041 (item.id.clone(), "section-hover"),
1042 cx,
1043 |_, _| Cell::new(false),
1044 );
1045 if state.read(cx).get() {
1046 style.shape = Some(shape);
1047 }
1048 state
1049 });
1050 let children = self.render(rows, palette, true, window, cx);
1051 return self
1052 .paint
1053 .surface(style, palette, true)
1054 .id(item.id)
1055 .test_support()
1056 .role(Role::Group)
1057 .aria_label(item.label.clone())
1058 .when_some(state, |section, state| {
1059 section.on_hover(move |hovered, window, cx| {
1060 let state = state.read(cx);
1061 if state.replace(!hovered) != !hovered {
1062 window.refresh();
1063 }
1064 })
1065 })
1066 .child(menu_heading(
1067 item.slots.label(item.label),
1068 self.paint,
1069 palette,
1070 ))
1071 .children(children)
1072 .into_any_element();
1073 }
1074 if matches!(item.kind, Kind::Heading) {
1075 return menu_heading(item.slots.label(item.label), self.paint, palette)
1076 .id(item.id)
1077 .role(Role::Label)
1078 .into_any_element();
1079 }
1080 let shape = row_shape(
1081 item.style,
1082 grouped,
1083 index,
1084 count,
1085 matches!(item.kind, Kind::Check(true, _) | Kind::Select(true, _)),
1086 );
1087 self.row(item, palette, shape)
1088 })
1089 .collect()
1090 }
1091
1092 fn row(&mut self, item: MenuItem, palette: Palette, shape: CornerShape) -> AnyElement {
1093 let (focus, enabled) = self
1094 .focus
1095 .next()
1096 .expect("each menu command has a focus entry");
1097 let action = item.activation();
1098 let (role, marked) = match item.kind {
1099 Kind::Check(checked, _) => (Role::MenuItemCheckBox, checked),
1100 Kind::Select(selected, _) => (Role::MenuItem, selected),
1101 _ => (Role::MenuItem, false),
1102 };
1103 let submenu = matches!(item.kind, Kind::Submenu(_));
1104 let (background, ink, supporting) =
1105 row_colors(item.style, self.paint, palette, marked, enabled);
1106 let row = gpui_base::Button::new(item.id.clone())
1107 .role(role)
1108 .track_focus(&focus)
1109 .disabled(!enabled)
1110 .accessibility_label(item.label.clone())
1111 .flex()
1112 .text_color(ink);
1113 let row = row_layout(row, item.style, shape, self.paint)
1114 .when(marked || item.style.container.is_some(), |row| {
1115 row.bg(background)
1116 })
1117 .when(enabled, |row| {
1118 row.hover(move |style| {
1119 style.bg(background.blend(ink.opacity(StateLayer::Hover.opacity())))
1120 })
1121 .focus_visible(move |style| {
1122 style.bg(background.blend(ink.opacity(StateLayer::Focus.opacity())))
1123 })
1124 .active(move |style| {
1125 style.bg(background.blend(ink.opacity(StateLayer::Pressed.opacity())))
1126 })
1127 })
1128 .when(role == Role::MenuItemCheckBox, |row| {
1129 row.aria_toggled(if marked {
1130 gpui::accesskit::Toggled::True
1131 } else {
1132 gpui::accesskit::Toggled::False
1133 })
1134 })
1135 .when(matches!(item.kind, Kind::Select(..)), |row| {
1136 row.aria_selected(marked)
1137 })
1138 .when(enabled && !submenu, |row| {
1139 let close = self.close.clone();
1140 let activate: Action = Rc::new(move |window, cx| {
1141 close(window, cx);
1142 if let Some(action) = &action {
1143 action(window, cx);
1144 }
1145 });
1146 let keyboard = activate.clone();
1147 let accessibility = activate.clone();
1148 row.capture_key_down(move |event, window, cx| {
1149 if matches!(event.keystroke.key.as_str(), "enter" | "space") {
1150 keyboard(window, cx);
1151 cx.stop_propagation();
1152 }
1153 })
1154 .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| {
1155 accessibility(window, cx)
1156 })
1157 .on_click(move |_, window, cx| activate(window, cx))
1158 })
1159 .children(item.slots.children(
1160 item.label,
1161 marked,
1162 submenu,
1163 self.paint.motion,
1164 supporting,
1165 ));
1166 if let Kind::Submenu(children) = item.kind {
1167 Menu {
1168 close_parent: Some(self.close.clone()),
1169 enabled,
1170 ancestor: Some(self.bounds.clone()),
1171 ..Menu::new((item.id, "submenu"), row, children)
1172 .anchor(Anchor::LeftCenter)
1173 .color(self.preset)
1174 }
1175 .into_any_element()
1176 } else {
1177 row.into_any_element()
1178 }
1179 }
1180}