Skip to main content

gpui_deck/
context_menu.rs

1//! A focusable context target for the shared command menu.
2
3use gpui::{
4    AccessibleAction, AnyElement, App, ElementId, Entity, InteractiveElement, Interactivity,
5    IntoElement, KeyBinding, MouseButton, ParentElement as _, RenderOnce, Role, SharedString,
6    StatefulInteractiveElement, StyleRefinement, Styled, Window, actions, div,
7    prelude::FluentBuilder as _,
8};
9
10use crate::{MenuState, Popover, TestSupportExt as _, a11y_disabled::A11yDisabledExt as _};
11
12const CONTEXT: &str = "ContextMenuTarget";
13
14actions!(ui, [OpenContextMenu]);
15
16pub(crate) fn init(cx: &mut App) {
17    cx.bind_keys([
18        KeyBinding::new("shift-f10", OpenContextMenu, Some(CONTEXT)),
19        KeyBinding::new("menu", OpenContextMenu, Some(CONTEXT)),
20    ]);
21}
22
23/// A focusable region that opens a command menu on a native secondary click.
24///
25/// Right-click positions the popup at that window coordinate. Shift-F10, the
26/// Menu key, the native ShowContextMenu accessibility action, and imperative
27/// [`MenuState::open`] position it below the target. Left-click only focuses the
28/// target; it never opens the menu. Commands, active-descendant navigation,
29/// disabled state, dismissal, and return focus use the same MenuState and
30/// Popover lifecycle as DropdownMenu.
31///
32/// Supply non-interactive target content and [`crate::MenuOption`]
33/// children in collection order. `target_label` names the focusable region;
34/// `accessibility_label` names its menu. Styles and interactive style builders
35/// apply to the target. Keep this component mounted while closed and use a
36/// distinct MenuState for each mounted target. Use [`crate::MenuSubmenu`] for
37/// nested commands, and [`crate::MenuOption::check_state`] or
38/// [`crate::MenuOption::radio_checked`] for application-controlled selections.
39/// A touch long press opens the menu at the press position, like a secondary
40/// click, and claims the gesture so it neither pans nor reaches the content.
41#[derive(IntoElement)]
42pub struct ContextMenu {
43    id: ElementId,
44    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
45    state: Entity<MenuState>,
46    target_label: Option<SharedString>,
47    label: Option<SharedString>,
48    content: Option<AnyElement>,
49}
50
51impl ContextMenu {
52    pub fn new(id: impl Into<ElementId>, state: &Entity<MenuState>) -> Self {
53        let id = id.into();
54        Self {
55            base: div().id(id.clone()).test_support(),
56            id,
57            state: state.clone(),
58            target_label: None,
59            label: None,
60            content: None,
61        }
62    }
63
64    pub fn target(mut self, content: impl IntoElement) -> Self {
65        self.base = self.base.child(content);
66        self
67    }
68
69    /// Names the focusable region whose commands are being shown.
70    pub fn target_label(mut self, label: impl Into<SharedString>) -> Self {
71        self.target_label = Some(label.into());
72        self
73    }
74
75    /// Names the menu itself.
76    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
77        self.label = Some(label.into());
78        self
79    }
80
81    pub fn content(mut self, content: impl IntoElement) -> Self {
82        self.content = Some(content.into_any_element());
83        self
84    }
85}
86
87impl Styled for ContextMenu {
88    fn style(&mut self) -> &mut StyleRefinement {
89        self.base.style()
90    }
91}
92
93impl InteractiveElement for ContextMenu {
94    fn interactivity(&mut self) -> &mut Interactivity {
95        self.base.interactivity()
96    }
97}
98
99impl StatefulInteractiveElement for ContextMenu {}
100
101impl RenderOnce for ContextMenu {
102    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
103        let state = self.state.read(cx);
104        let open = state.is_open(cx);
105        let disabled = state.is_disabled(cx);
106        let focus = state.focus_handle().clone();
107        let popover = state.popover.clone();
108        let position = state.position();
109        let left = self.state.clone();
110        let right = self.state.clone();
111        let keyboard = self.state.clone();
112        let accessible = self.state.clone();
113        let touch = self.state.clone();
114        let content = crate::menu::menu_content(&self.state, self.label, self.content, window, cx);
115        let target = self
116            .base
117            .role(Role::Region)
118            .aria_expanded(open)
119            .aria_keyshortcuts("Shift+F10")
120            .when_some(self.target_label, |this, label| this.aria_label(label))
121            .key_context(CONTEXT)
122            .when(!disabled || focus.is_focused(window), |this| {
123                this.track_focus(&focus.tab_stop(!disabled))
124            })
125            .when(!disabled, |this| {
126                this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
127                    let state = left.read(cx);
128                    if !state.is_disabled(cx) {
129                        let focus = state.focus_handle().clone();
130                        focus.focus(window, cx);
131                    }
132                })
133                .on_mouse_down(MouseButton::Right, move |event, window, cx| {
134                    right.update(cx, |state, cx| {
135                        if !state.is_disabled(cx) {
136                            state.open_at_position(event.position, window, cx);
137                            cx.stop_propagation();
138                        }
139                    });
140                })
141                .on_action(move |_: &OpenContextMenu, window, cx| {
142                    keyboard.update(cx, |state, cx| state.open(window, cx));
143                })
144                .on_a11y_action(AccessibleAction::ShowContextMenu, move |_, window, cx| {
145                    accessible.update(cx, |state, cx| state.open(window, cx));
146                })
147                .relative()
148                .child(crate::long_press::long_press_region(
149                    touch.clone(),
150                    move |position, window, cx| {
151                        touch.update(cx, |state, cx| {
152                            if state.is_disabled(cx) {
153                                return false;
154                            }
155                            let focus = state.focus_handle().clone();
156                            focus.focus(window, cx);
157                            state.open_at_position(position, window, cx);
158                            true
159                        })
160                    },
161                ))
162            })
163            .a11y_disabled(disabled);
164
165        Popover::new((self.id, "context-menu-host"), &popover)
166            .supplied_trigger(target)
167            .content_role(None)
168            .when_some(position, |popover, position| popover.at_position(position))
169            .content(content)
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use gpui::{
177        AppContext as _, Context, FocusHandle, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
178        Render, Subscription, TestAppContext, VisualTestContext, point, px, size,
179    };
180
181    use crate::{Button, MenuEvent, MenuItem, MenuOption, MenuSubmenu, Root};
182
183    struct Harness {
184        menu: Entity<MenuState>,
185        before: FocusHandle,
186        after: FocusHandle,
187        shown: bool,
188        commands: Vec<SharedString>,
189        _subscriptions: Vec<Subscription>,
190    }
191
192    impl Render for Harness {
193        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
194            let options =
195                self.menu
196                    .read(cx)
197                    .items()
198                    .iter()
199                    .enumerate()
200                    .map(|(index, item)| {
201                        let label = div()
202                            .debug_selector(move || format!("context-command-{index}"))
203                            .size_full()
204                            .child(item.label().clone());
205                        if let Some(submenu) = item.submenu_state() {
206                            MenuSubmenu::new(&self.menu, index)
207                                .trigger(|option| option.h(px(28.)).child(label))
208                                .content(div().w(px(180.)).child(
209                                    MenuOption::new(submenu, 0).h(px(28.)).child("Copy link"),
210                                ))
211                                .into_any_element()
212                        } else {
213                            MenuOption::new(&self.menu, index)
214                                .h(px(28.))
215                                .child(label)
216                                .into_any_element()
217                        }
218                    });
219            div()
220                .size_full()
221                .p(px(16.))
222                .flex()
223                .flex_col()
224                .gap(px(8.))
225                .child(
226                    Button::new("before")
227                        .debug_selector(|| "before".into())
228                        .track_focus(&self.before)
229                        .h(px(28.))
230                        .child("Before"),
231                )
232                .when(self.shown, |this| {
233                    this.child(
234                        ContextMenu::new("context-target", &self.menu)
235                            .debug_selector(|| "context-target".into())
236                            .target_label("Recording summary")
237                            .accessibility_label("Recording actions")
238                            .h(px(220.))
239                            .w_full()
240                            .target("Recording summary")
241                            .content(
242                                div()
243                                    .debug_selector(|| "context-surface".into())
244                                    .w(px(180.))
245                                    .flex()
246                                    .flex_col()
247                                    .children(options),
248                            ),
249                    )
250                })
251                .child(
252                    Button::new("after")
253                        .track_focus(&self.after)
254                        .h(px(28.))
255                        .child("After"),
256                )
257        }
258    }
259
260    fn settle(cx: &mut VisualTestContext) {
261        cx.update(|window, cx| window.draw(cx).clear(cx));
262        cx.run_until_parked();
263        cx.update(|window, cx| window.draw(cx).clear(cx));
264    }
265
266    fn press(cx: &mut VisualTestContext, key: &str) {
267        let keystroke =
268            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
269        cx.simulate_event(KeyDownEvent {
270            keystroke: keystroke.clone(),
271            is_held: false,
272            prefer_character_input: false,
273        });
274        cx.simulate_event(KeyUpEvent { keystroke });
275        settle(cx);
276    }
277
278    fn harness(cx: &mut TestAppContext) -> (&mut VisualTestContext, Entity<Harness>) {
279        cx.update(crate::init);
280        let (root, cx) = cx.add_window_view(|window, cx| {
281            let content = cx.new(|cx| {
282                let submenu =
283                    cx.new(|cx| MenuState::new([MenuItem::new("copy-link", "Copy link")], cx));
284                let menu = cx.new(|cx| {
285                    MenuState::new(
286                        [
287                            MenuItem::new("disabled", "Disabled").disabled(true),
288                            MenuItem::new("open", "Open"),
289                            MenuItem::new("share", "Share").submenu(&submenu),
290                        ],
291                        cx,
292                    )
293                });
294                let subscriptions = vec![
295                    cx.observe(&menu, |_, _, cx| cx.notify()),
296                    cx.subscribe_in(
297                        &menu,
298                        window,
299                        |this: &mut Harness, menu, event, window, cx| {
300                            let MenuEvent::Action(value) = event;
301                            assert!(!menu.read(cx).is_open(cx));
302                            assert!(menu.read(cx).focus_handle().is_focused(window));
303                            this.commands.push(value.clone());
304                        },
305                    ),
306                ];
307                Harness {
308                    menu,
309                    before: cx.focus_handle(),
310                    after: cx.focus_handle(),
311                    shown: true,
312                    commands: Vec::new(),
313                    _subscriptions: subscriptions,
314                }
315            });
316            Root::new(content, window, cx)
317        });
318        let view = root
319            .read_with(cx, |root, _| root.view().clone())
320            .downcast::<Harness>()
321            .unwrap();
322        cx.simulate_resize(size(px(460.), px(360.)));
323        cx.update(|window, cx| {
324            window.activate_window();
325            let focus = view.read(cx).before.clone();
326            focus.focus(window, cx);
327        });
328        settle(cx);
329        (cx, view)
330    }
331
332    fn secondary_click(cx: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
333        cx.simulate_mouse_down(position, MouseButton::Right, Modifiers::default());
334        cx.simulate_mouse_up(position, MouseButton::Right, Modifiers::default());
335        settle(cx);
336    }
337
338    #[gpui::test]
339    fn secondary_click_places_repositions_and_clamps_the_shared_menu(cx: &mut TestAppContext) {
340        let (cx, view) = harness(cx);
341        let target = cx.debug_bounds("context-target").unwrap();
342        let first = target.origin + point(px(20.), px(24.));
343        cx.simulate_click(first, Modifiers::default());
344        settle(cx);
345        cx.update(|window, cx| {
346            let state = view.read(cx).menu.read(cx);
347            assert!(!state.is_open(cx), "left-click focuses without opening");
348            assert!(state.focus_handle().is_focused(window));
349        });
350        secondary_click(cx, first);
351        assert_eq!(cx.debug_bounds("context-surface").unwrap().origin, first);
352        cx.update(|window, cx| {
353            let state = view.read(cx).menu.read(cx);
354            assert!(state.is_open(cx));
355            assert_eq!(state.highlighted_index(), Some(1));
356            assert!(state.content_focus_handle().is_focused(window));
357            assert!(view.read(cx).commands.is_empty());
358        });
359
360        press(cx, "end");
361        press(cx, "right");
362        cx.update(|_, cx| {
363            assert!(
364                view.read(cx).menu.read(cx).items()[2]
365                    .submenu_state()
366                    .unwrap()
367                    .read(cx)
368                    .is_open(cx)
369            );
370        });
371        // A second request on the target moves the same menu; near the window
372        // edge the existing Positioner keeps the whole command surface inside.
373        secondary_click(cx, target.bottom_right() - point(px(2.), px(2.)));
374        cx.update(|window, cx| {
375            let state = view.read(cx).menu.read(cx);
376            assert!(
377                !state.items()[2]
378                    .submenu_state()
379                    .unwrap()
380                    .read(cx)
381                    .is_open(cx)
382            );
383            assert_eq!(state.highlighted_index(), Some(1));
384            assert!(state.content_focus_handle().is_focused(window));
385        });
386        let popup = cx.debug_bounds("context-surface").unwrap();
387        assert!(popup.origin.x > first.x);
388        cx.update(|window, _| {
389            assert!(popup.right() <= window.viewport_size().width - px(8.));
390            assert!(popup.bottom() <= window.viewport_size().height - px(8.));
391        });
392        let command = cx.debug_bounds("context-command-1").unwrap().center();
393        cx.simulate_click(command, Modifiers::default());
394        settle(cx);
395        cx.update(|window, cx| {
396            let view = view.read(cx);
397            assert!(!view.menu.read(cx).is_open(cx));
398            assert_eq!(view.commands, [SharedString::from("open")]);
399            assert!(view.menu.read(cx).focus_handle().is_focused(window));
400        });
401    }
402
403    #[gpui::test]
404    fn keyboard_target_dismissal_disabled_and_unmount_keep_the_shared_lifecycle(
405        cx: &mut TestAppContext,
406    ) {
407        let (cx, view) = harness(cx);
408        press(cx, "tab");
409        press(cx, "shift-f10");
410        let target = cx.debug_bounds("context-target").unwrap();
411        let popup = cx.debug_bounds("context-surface").unwrap();
412        assert_eq!(popup.origin.x, target.origin.x);
413        cx.update(|window, cx| {
414            let state = view.read(cx).menu.read(cx);
415            assert!(state.content_focus_handle().is_focused(window));
416            assert_eq!(
417                popup.top(),
418                target
419                    .bottom()
420                    .min(window.viewport_size().height - px(8.) - popup.size.height)
421            );
422        });
423        press(cx, "escape");
424        cx.update(|window, cx| {
425            let state = view.read(cx).menu.read(cx);
426            assert!(!state.is_open(cx));
427            assert!(state.focus_handle().is_focused(window));
428        });
429        press(cx, "menu");
430        press(cx, "tab");
431        cx.update(|window, cx| {
432            assert!(!view.read(cx).menu.read(cx).is_open(cx));
433            assert!(view.read(cx).after.is_focused(window));
434        });
435        press(cx, "shift-tab");
436        press(cx, "shift-f10");
437        let before = cx.debug_bounds("before").unwrap().center();
438        cx.simulate_click(before, Modifiers::default());
439        settle(cx);
440        cx.update(|window, cx| {
441            assert!(!view.read(cx).menu.read(cx).is_open(cx));
442            assert!(view.read(cx).before.is_focused(window));
443        });
444        press(cx, "tab");
445        press(cx, "shift-f10");
446        cx.update(|window, cx| {
447            let menu = view.read(cx).menu.clone();
448            menu.update(cx, |state, cx| state.set_disabled(true, window, cx));
449            assert!(menu.read(cx).focus_handle().is_focused(window));
450        });
451        settle(cx);
452        press(cx, "shift-f10");
453        secondary_click(cx, target.center());
454        press(cx, "tab");
455        cx.update(|window, cx| {
456            assert!(!view.read(cx).menu.read(cx).is_open(cx));
457            assert!(view.read(cx).after.is_focused(window));
458            let menu = view.read(cx).menu.clone();
459            menu.update(cx, |state, cx| {
460                state.set_disabled(false, window, cx);
461                state.open(window, cx);
462            });
463        });
464        settle(cx);
465        view.update(cx, |view, cx| {
466            view.shown = false;
467            cx.notify();
468        });
469        settle(cx);
470        cx.update(|_, cx| {
471            assert!(!view.read(cx).menu.read(cx).is_open(cx));
472            assert!(view.read(cx).commands.is_empty());
473        });
474    }
475
476    fn long_press(cx: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
477        use gpui::{TouchEvent, TouchId, TouchPhase};
478        let touch = |phase| TouchEvent {
479            id: TouchId(7),
480            phase,
481            position,
482            predicted_position: None,
483            force: None,
484        };
485        cx.simulate_event(touch(TouchPhase::Started));
486        cx.executor().advance_clock(
487            gpui::GestureTuning::default().long_press_duration
488                + std::time::Duration::from_millis(1),
489        );
490        settle(cx);
491        cx.simulate_event(touch(TouchPhase::Ended));
492        settle(cx);
493    }
494
495    #[gpui::test]
496    fn touch_long_press_opens_at_the_press_and_survives_release(cx: &mut TestAppContext) {
497        let (cx, view) = harness(cx);
498        let target = cx.debug_bounds("context-target").unwrap();
499        let position = target.origin + point(px(40.), px(30.));
500        long_press(cx, position);
501        cx.update(|window, cx| {
502            let view = view.read(cx);
503            let menu = view.menu.read(cx);
504            assert!(
505                menu.is_open(cx),
506                "release after a long press keeps the menu"
507            );
508            assert_eq!(menu.position(), Some(position));
509            assert!(!view.before.is_focused(window));
510            assert!(view.commands.is_empty());
511        });
512        press(cx, "escape");
513        cx.update(|window, cx| {
514            let menu = view.read(cx).menu.read(cx);
515            assert!(!menu.is_open(cx));
516            assert!(
517                menu.focus_handle().is_focused(window),
518                "focus returns to the target"
519            );
520        });
521        // A disabled target ignores the gesture.
522        cx.update(|window, cx| {
523            view.read(cx)
524                .menu
525                .clone()
526                .update(cx, |menu, cx| menu.set_disabled(true, window, cx));
527        });
528        settle(cx);
529        long_press(cx, position);
530        cx.update(|_, cx| assert!(!view.read(cx).menu.read(cx).is_open(cx)));
531    }
532}