1use std::{
2 cell::{Cell, RefCell},
3 rc::Rc,
4};
5
6use wgpui::{
7 Anchor, AnyElement, App, Bounds, Context, DismissEvent, Element, ElementId, Entity,
8 FocusHandle, Focusable, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId,
9 InteractiveElement, IntoElement, LayoutId, LongPressEvent, MouseButton, MouseDownEvent,
10 ParentElement, Pixels, Point, Position, Style, StyleRefinement, Styled, Subscription,
11 TouchPhase, Window, anchored, deferred, div, px,
12};
13
14use crate::{input::AnyInputState, menu::PopupMenu, root::WindowState};
15
16pub trait ContextMenuExt: InteractiveElement + ParentElement + Styled {
18 #[track_caller]
23 fn context_menu(
24 mut self,
25 f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
26 ) -> ContextMenu<Self>
27 where
28 Self: Sized,
29 {
30 let caller = std::panic::Location::caller();
33 let id = self
34 .interactivity()
35 .element_id
36 .clone()
37 .map(|id| ElementId::Name(format!("context-menu-{:?}", id).into()))
38 .unwrap_or_else(|| ElementId::CodeLocation(*caller));
39 ContextMenu::new(id, self).menu(f)
40 }
41}
42
43impl<E: InteractiveElement + ParentElement + Styled> ContextMenuExt for E {}
44
45pub struct ContextMenu<E: ParentElement + Styled + Sized> {
47 id: ElementId,
48 element: Option<E>,
49 menu: Option<Rc<MenuBuilder>>,
50 _ignore_style: StyleRefinement,
52 anchor: Anchor,
53}
54
55impl<E: ParentElement + Styled> ContextMenu<E> {
56 pub fn new(id: impl Into<ElementId>, element: E) -> Self {
58 Self {
59 id: id.into(),
60 element: Some(element),
61 menu: None,
62 anchor: Anchor::TopLeft,
63 _ignore_style: StyleRefinement::default(),
64 }
65 }
66
67 #[must_use]
69 fn menu<F>(mut self, builder: F) -> Self
70 where
71 F: Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
72 {
73 self.menu = Some(Rc::new(builder));
74 self
75 }
76
77 fn with_element_state<R>(
78 &mut self,
79 id: &GlobalElementId,
80 window: &mut Window,
81 cx: &mut App,
82 f: impl FnOnce(&mut Self, &mut ContextMenuState, &mut Window, &mut App) -> R,
83 ) -> R {
84 window.with_optional_element_state::<ContextMenuState, _>(
85 Some(id),
86 |element_state, window| {
87 let mut element_state = element_state.unwrap().unwrap_or_default();
88 let result = f(self, &mut element_state, window, cx);
89 (result, Some(element_state))
90 },
91 )
92 }
93}
94
95impl<E: ParentElement + Styled> ParentElement for ContextMenu<E> {
96 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
97 if let Some(element) = &mut self.element {
98 element.extend(elements);
99 }
100 }
101}
102
103impl<E: ParentElement + Styled> Styled for ContextMenu<E> {
104 fn style(&mut self) -> &mut StyleRefinement {
105 if let Some(element) = &mut self.element {
106 element.style()
107 } else {
108 &mut self._ignore_style
109 }
110 }
111}
112
113impl<E: ParentElement + Styled + IntoElement + 'static> IntoElement for ContextMenu<E> {
114 type Element = Self;
115
116 fn into_element(self) -> Self::Element {
117 self
118 }
119}
120
121struct ContextMenuSharedState {
122 menu_view: Option<Entity<PopupMenu>>,
123 selection_input: Option<AnyInputState>,
126 open: bool,
127 position: Point<Pixels>,
128 trigger_focus_handle: Option<FocusHandle>,
133 _subscription: Option<Subscription>,
134}
135
136pub struct ContextMenuState {
137 element: Option<AnyElement>,
138 draws_menu: Rc<Cell<bool>>,
146 shared_state: Rc<RefCell<ContextMenuSharedState>>,
147}
148
149impl Default for ContextMenuState {
150 fn default() -> Self {
151 Self {
152 element: None,
153 draws_menu: Rc::default(),
154 shared_state: Rc::new(RefCell::new(ContextMenuSharedState {
155 menu_view: None,
156 selection_input: None,
157 open: false,
158 position: Default::default(),
159 trigger_focus_handle: None,
160 _subscription: None,
161 })),
162 }
163 }
164}
165
166struct DeferredMenu {
172 draws: Rc<Cell<bool>>,
173 menu_view: Entity<PopupMenu>,
174 position: Point<Pixels>,
175 anchor: Anchor,
176 menu: Option<AnyElement>,
177}
178
179impl DeferredMenu {
180 fn build_menu(&self, window: &mut Window) -> AnyElement {
181 deferred(
182 anchored().child(
183 div()
184 .w(window.bounds().size.width)
185 .h(window.bounds().size.height)
186 .on_scroll(|_, _, cx| {
187 cx.stop_propagation();
188 })
189 .child(
190 anchored()
191 .position(self.position)
192 .snap_to_window_with_margin(px(8.))
193 .anchor(self.anchor)
194 .child(self.menu_view.clone()),
195 ),
196 ),
197 )
198 .with_priority(wgpui_base::POPUP_PRIORITY)
199 .into_any()
200 }
201}
202
203impl IntoElement for DeferredMenu {
204 type Element = Self;
205
206 fn into_element(self) -> Self::Element {
207 self
208 }
209}
210
211impl Element for DeferredMenu {
212 type RequestLayoutState = ();
213 type PrepaintState = ();
214
215 fn id(&self) -> Option<ElementId> {
216 None
217 }
218
219 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
220 None
221 }
222
223 fn request_layout(
224 &mut self,
225 _: Option<&GlobalElementId>,
226 _: Option<&InspectorElementId>,
227 window: &mut Window,
228 cx: &mut App,
229 ) -> (LayoutId, ()) {
230 let style = Style {
233 position: Position::Absolute,
234 ..Style::default()
235 };
236 (window.request_layout(style, None, cx), ())
237 }
238
239 fn prepaint(
240 &mut self,
241 _: Option<&GlobalElementId>,
242 _: Option<&InspectorElementId>,
243 bounds: Bounds<Pixels>,
244 _: &mut (),
245 window: &mut Window,
246 cx: &mut App,
247 ) {
248 if !self.draws.get() {
249 return;
250 }
251 let mut menu = self.build_menu(window);
252 menu.prepaint_as_root(bounds.origin, window.viewport_size().into(), window, cx);
253 self.menu = Some(menu);
254 }
255
256 fn paint(
257 &mut self,
258 _: Option<&GlobalElementId>,
259 _: Option<&InspectorElementId>,
260 _: Bounds<Pixels>,
261 _: &mut (),
262 _: &mut (),
263 window: &mut Window,
264 cx: &mut App,
265 ) {
266 if let Some(menu) = &mut self.menu {
267 menu.paint(window, cx);
268 }
269 }
270}
271
272impl<E: ParentElement + Styled + IntoElement + 'static> Element for ContextMenu<E> {
273 type RequestLayoutState = ContextMenuState;
274 type PrepaintState = Hitbox;
275
276 fn id(&self) -> Option<ElementId> {
277 Some(self.id.clone())
278 }
279
280 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
281 None
282 }
283
284 fn request_layout(
285 &mut self,
286 id: Option<&wgpui::GlobalElementId>,
287 _: Option<&wgpui::InspectorElementId>,
288 window: &mut Window,
289 cx: &mut App,
290 ) -> (wgpui::LayoutId, Self::RequestLayoutState) {
291 let anchor = self.anchor;
292
293 self.with_element_state(
294 id.unwrap(),
295 window,
296 cx,
297 |this, state: &mut ContextMenuState, window, cx| {
298 let (position, open) = {
299 let shared_state = state.shared_state.borrow();
300 (shared_state.position, shared_state.open)
301 };
302 state
303 .shared_state
304 .borrow_mut()
305 .trigger_focus_handle
306 .get_or_insert_with(|| cx.focus_handle());
307 let menu_view = state.shared_state.borrow().menu_view.clone();
308 let draws_menu = Rc::new(Cell::new(false));
309 let menu_element = menu_view
310 .filter(|menu| open && !menu.read(cx).is_empty())
311 .map(|menu_view| DeferredMenu {
312 draws: draws_menu.clone(),
313 menu_view,
314 position,
315 anchor,
316 menu: None,
317 });
318
319 let mut element = this
320 .element
321 .take()
322 .expect("Element should exists.")
323 .children(menu_element)
324 .into_any_element();
325
326 let layout_id = element.request_layout(window, cx);
327
328 (
329 layout_id,
330 ContextMenuState {
331 element: Some(element),
332 draws_menu,
333 shared_state: state.shared_state.clone(),
334 },
335 )
336 },
337 )
338 }
339
340 fn prepaint(
341 &mut self,
342 _: Option<&wgpui::GlobalElementId>,
343 _: Option<&InspectorElementId>,
344 bounds: wgpui::Bounds<wgpui::Pixels>,
345 request_layout: &mut Self::RequestLayoutState,
346 window: &mut Window,
347 cx: &mut App,
348 ) -> Self::PrepaintState {
349 if let Some(trigger_focus) = request_layout
350 .shared_state
351 .borrow()
352 .trigger_focus_handle
353 .as_ref()
354 {
355 window.set_focus_handle(trigger_focus, cx);
356 }
357 let position = request_layout.shared_state.borrow().position;
358 request_layout.draws_menu.set(bounds.contains(&position));
359 if let Some(element) = &mut request_layout.element {
360 element.prepaint(window, cx);
361 }
362 window.insert_hitbox(bounds, HitboxBehavior::Normal)
363 }
364
365 fn paint(
366 &mut self,
367 _: Option<&wgpui::GlobalElementId>,
368 _: Option<&InspectorElementId>,
369 _: wgpui::Bounds<wgpui::Pixels>,
370 request_layout: &mut Self::RequestLayoutState,
371 hitbox: &mut Self::PrepaintState,
372 window: &mut Window,
373 cx: &mut App,
374 ) {
375 let builder = self.menu.clone();
376 let shared_state = request_layout.shared_state.clone();
377
378 window.on_mouse_event({
383 let shared_state = shared_state.clone();
384 let builder = builder.clone();
385 let hitbox = hitbox.clone();
386 move |event: &LongPressEvent, phase, window, cx| {
387 if phase.bubble()
388 && event.phase == TouchPhase::Started
389 && !window.default_prevented()
390 && hitbox.is_hovered(window)
391 && !wgpui_base::TextSelection::is_selectable_at(
392 event.start_position,
393 window,
394 cx,
395 )
396 {
397 window.prevent_default();
398 open_menu(&shared_state, &builder, event.start_position, window, cx);
399 }
400 }
401 });
402
403 let hitbox = hitbox.clone();
406 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
407 if phase.bubble() && event.button == MouseButton::Right && hitbox.is_hovered(window) {
408 cx.stop_propagation();
409 open_menu(&shared_state, &builder, event.position, window, cx);
410 }
411 });
412
413 if let Some(element) = &mut request_layout.element {
414 element.paint(window, cx);
415 }
416 }
417}
418
419type MenuBuilder = dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu;
420
421fn open_menu(
423 shared_state: &Rc<RefCell<ContextMenuSharedState>>,
424 builder: &Option<Rc<MenuBuilder>>,
425 position: Point<Pixels>,
426 window: &mut Window,
427 cx: &mut App,
428) {
429 let previous_focus_handle = window.focused(cx).and_then(|focused| {
432 let shared_state = shared_state.borrow();
433 match shared_state.menu_view.as_ref() {
434 Some(menu) if menu.read(cx).focus_handle == focused => {
435 menu.read(cx).previous_focus_handle.clone()
436 }
437 _ => Some(focused),
438 }
439 });
440
441 let previous_selection_input = {
443 let state = shared_state.borrow();
444 let menu_focused = state.menu_view.as_ref().is_some_and(|menu| {
445 let focus = menu.focus_handle(cx);
446 focus.is_focused(window) || focus.contains_focused(window, cx)
447 });
448 state
449 .selection_input
450 .as_ref()
451 .filter(|input| menu_focused || input.focus_handle(cx).is_focused(window))
452 .cloned()
453 };
454 {
455 let mut shared_state = shared_state.borrow_mut();
456 shared_state.menu_view = None;
459 shared_state.selection_input = None;
460 shared_state._subscription = None;
461 shared_state.position = position;
462 shared_state.open = true;
463 }
464
465 window.defer(cx, {
467 let shared_state = shared_state.clone();
468 let builder = builder.clone();
469 move |window, cx| {
470 let selection_input =
474 WindowState::try_update(window, cx, |state, _, _| state.focused_input.clone())
475 .flatten()
476 .filter(|input| input.focus_handle(cx).is_focused(window))
477 .or(previous_selection_input);
478 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
479 let Some(build) = &builder else {
480 return menu;
481 };
482 build(menu, window, cx)
483 });
484 let trigger_focus_handle = shared_state.borrow().trigger_focus_handle.clone();
485 menu.update(cx, |menu, cx| {
486 menu.set_trigger_focus(trigger_focus_handle, cx);
487 menu.set_previous_focus(previous_focus_handle, cx);
488 });
489
490 let selection_input = selection_input.filter(|input| {
494 let Some(bounds) = input.input_bounds(cx) else {
495 return false;
496 };
497 match menu.read(cx).action_context.as_ref() {
498 Some(target) => target == &input.focus_handle(cx),
499 None => bounds.contains(&position),
500 }
501 });
502 if let Some(input) = selection_input.as_ref() {
503 input.set_selection_focus(Some(menu.focus_handle(cx)), cx);
504 }
505
506 menu.focus_handle(cx).focus(window, cx);
510
511 let _subscription = window.subscribe(&menu, cx, {
518 let shared_state = Rc::downgrade(&shared_state);
519 move |_, _: &DismissEvent, window, _cx| {
520 if let Some(shared_state) = shared_state.upgrade() {
521 let mut state = shared_state.borrow_mut();
522 state.open = false;
523 state.selection_input = None;
524 window.refresh();
525 }
526 }
527 });
528
529 {
531 let mut state = shared_state.borrow_mut();
532 state.menu_view = Some(menu.clone());
533 state.selection_input = selection_input;
534 state._subscription = Some(_subscription);
535 window.refresh();
536 }
537 }
538 });
539}
540
541#[cfg(test)]
542mod tests {
543 use super::*;
544 use crate::menu::PopupMenuItem;
545 use crate::theme::Theme;
546 use std::cell::Cell;
547 use wgpui::{
548 Context, FocusHandle, IntoElement, KeyBinding, Render, TestAppContext, VisualTestContext,
549 actions, point, px,
550 };
551
552 actions!(context_menu_test, [RemoveTab, CopyText]);
553
554 struct TestRoot {
558 content_focus: FocusHandle,
559 received: Rc<Cell<bool>>,
560 }
561
562 impl Render for TestRoot {
563 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
564 let received = self.received.clone();
565 div()
566 .size_full()
567 .child(
568 div()
569 .id("content")
570 .h(px(40.))
571 .track_focus(&self.content_focus),
572 )
573 .child(
574 div()
575 .id("action-bar")
576 .h(px(60.))
577 .on_action(move |_: &RemoveTab, _, _| received.set(true))
578 .child(
579 div()
580 .id("tab")
581 .size_full()
582 .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
583 ),
584 )
585 }
586 }
587
588 #[wgpui::test]
589 fn action_bubbles_from_trigger_and_focus_restores_on_dismiss(cx: &mut TestAppContext) {
590 cx.update(|cx| {
591 cx.set_global(Theme::default());
592 super::super::popup_menu::init(cx);
593 });
594
595 let received = Rc::new(Cell::new(false));
596 let (root, cx) = cx.add_window_view({
597 let received = received.clone();
598 move |window, cx| {
599 let content_focus = cx.focus_handle();
600 content_focus.focus(window, cx);
601 TestRoot {
602 content_focus,
603 received,
604 }
605 }
606 });
607 let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
608 let cx: &mut VisualTestContext = cx;
609 cx.run_until_parked();
610 cx.update(|window, cx| {
611 _ = window.draw(cx);
612 });
613
614 cx.simulate_event(MouseDownEvent {
616 button: MouseButton::Right,
617 position: point(px(50.), px(70.)),
618 modifiers: Default::default(),
619 click_count: 1,
620 first_mouse: false,
621 });
622 cx.run_until_parked();
625 cx.update(|window, cx| {
626 _ = window.draw(cx);
627 });
628
629 cx.simulate_keystrokes("down enter");
632 cx.run_until_parked();
633
634 assert!(received.get());
637 cx.update(|window, cx| {
640 assert_eq!(window.focused(cx).as_ref(), Some(&content_focus));
641 });
642 }
643
644 const CONTEXT: &str = "context_menu_test";
645
646 struct UnfocusedRoot {
650 frames: Rc<Cell<usize>>,
651 }
652
653 impl Render for UnfocusedRoot {
654 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
655 self.frames.set(self.frames.get() + 1);
656 div()
657 .size_full()
658 .child(
659 div()
660 .key_context(CONTEXT)
661 .on_action(|_: &CopyText, _, _| {})
662 .child(
663 div()
664 .id("tab")
665 .w(px(100.))
666 .h(px(30.))
667 .context_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))),
668 ),
669 )
670 .child(div().child("Status"))
671 }
672 }
673
674 struct RowsRoot {
677 clicked: Rc<Cell<usize>>,
678 }
679
680 impl Render for RowsRoot {
681 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
682 div().size_full().children((0..3).map(|_| {
683 let clicked = self.clicked.clone();
684 div()
685 .w(px(100.))
686 .h(px(30.))
687 .context_menu(move |menu, _, _| {
688 let clicked = clicked.clone();
689 menu.item(
690 PopupMenuItem::new("Favorite")
691 .on_click(move |_, _, _| clicked.set(clicked.get() + 1)),
692 )
693 })
694 }))
695 }
696 }
697
698 #[wgpui::test]
699 fn item_click_fires_once_from_rows_without_an_id(cx: &mut TestAppContext) {
700 cx.update(|cx| crate::init(cx));
701 let clicked = Rc::new(Cell::new(0));
702 let (_, cx) = cx.add_window_view({
703 let clicked = clicked.clone();
704 move |_, _| RowsRoot { clicked }
705 });
706 cx.update(|window, cx| {
707 window.draw(cx).clear();
708 });
709
710 let press = point(px(10.), px(40.));
712 cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
713 cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
714 cx.run_until_parked();
715 cx.update(|window, cx| {
716 window.draw(cx).clear();
717 });
718
719 let item = point(press.x + px(30.), press.y + px(17.));
721 cx.simulate_mouse_move(item, None, Default::default());
722 cx.simulate_click(item, Default::default());
723 cx.run_until_parked();
724
725 assert_eq!(
726 clicked.get(),
727 1,
728 "the item's on_click must fire exactly once"
729 );
730 }
731
732 #[wgpui::test]
739 fn open_without_dismiss_releases_the_menu_entity(cx: &mut TestAppContext) {
740 cx.update(|cx| crate::init(cx));
741 let before = cx.update(|cx| cx.leak_detector_snapshot());
742
743 {
744 let (_, cx) = cx.add_window_view(|_, _| RowsRoot {
745 clicked: Rc::new(Cell::new(0)),
746 });
747 cx.update(|window, cx| {
748 window.draw(cx).clear();
749 });
750
751 let press = point(px(10.), px(10.));
753 cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
754 cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
755 cx.run_until_parked();
756 cx.update(|window, cx| {
757 window.draw(cx).clear();
758 });
759
760 cx.update(|window, _| window.remove_window());
762 cx.run_until_parked();
763 }
764
765 cx.update(|cx| cx.assert_no_new_leaks(&before));
769 }
770
771 struct FocusRecordingRoot {
773 content_focus: FocusHandle,
774 content_focused_at_render: Rc<Cell<bool>>,
775 }
776
777 impl Render for FocusRecordingRoot {
778 fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
779 self.content_focused_at_render
780 .set(self.content_focus.is_focused(window));
781 div()
782 .size_full()
783 .child(
784 div()
785 .id("content")
786 .h(px(40.))
787 .track_focus(&self.content_focus),
788 )
789 .child(
790 div()
791 .id("tab")
792 .h(px(60.))
793 .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
794 )
795 }
796 }
797
798 #[wgpui::test]
803 fn menu_takes_focus_before_its_first_frame(cx: &mut TestAppContext) {
804 cx.update(|cx| crate::init(cx));
805 let content_focused_at_render = Rc::new(Cell::new(false));
806 let (root, cx) = cx.add_window_view({
807 let content_focused_at_render = content_focused_at_render.clone();
808 move |window, cx| {
809 let content_focus = cx.focus_handle();
810 content_focus.focus(window, cx);
811 FocusRecordingRoot {
812 content_focus,
813 content_focused_at_render,
814 }
815 }
816 });
817 let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
818 cx.update(|window, cx| {
819 window.draw(cx).clear();
820 });
821 assert!(content_focused_at_render.get());
822
823 cx.simulate_mouse_down(
824 point(px(50.), px(70.)),
825 MouseButton::Right,
826 Default::default(),
827 );
828
829 assert!(
830 !content_focused_at_render.get(),
831 "focus must leave the content before the frame that draws the menu"
832 );
833 cx.update(|window, cx| {
834 let focused = window.focused(cx);
835 assert!(focused.is_some() && focused.as_ref() != Some(&content_focus));
836 });
837 }
838
839 #[wgpui::test]
840 fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) {
841 cx.update(|cx| {
842 crate::init(cx);
843 cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]);
844 });
845 let frames = Rc::new(Cell::new(0));
846 let (_, cx) = cx.add_window_view({
847 let frames = frames.clone();
848 move |_, _| UnfocusedRoot { frames }
849 });
850 cx.update(|window, cx| {
851 window.draw(cx).clear();
852 assert!(window.focused(cx).is_none());
853 });
854 let frames_before_open = frames.get();
855
856 cx.simulate_mouse_down(
859 point(px(10.), px(10.)),
860 MouseButton::Right,
861 Default::default(),
862 );
863
864 assert_eq!(
865 frames.get(),
866 frames_before_open + 1,
867 "the press must be followed by exactly one frame for this to test the first one"
868 );
869 assert!(
870 cx.debug_bounds("kbd:ctrl-c").is_some(),
871 "the shortcut hint must be painted on the same frame as its item"
872 );
873 }
874}