Skip to main content

rgpui/menu/
context_menu.rs

1//! 上下文菜单,为元素添加右键菜单支持的扩展 trait 和实现。
2
3use std::{cell::RefCell, rc::Rc};
4
5use crate::{
6    Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, Focusable,
7    GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, InteractiveElement, IntoElement,
8    MouseButton, MouseDownEvent, ParentElement, Pixels, Point, StyleRefinement, Styled,
9    Subscription, Window, anchored, deferred, div, prelude::FluentBuilder, px,
10};
11
12use crate::menu::PopupMenu;
13
14/// 内部不变量:值为 `None` 说明前提被破坏(元素缺 id、状态缺失等),必须立刻暴露。
15///
16/// 统一走这里而不是散落的 `unwrap`:语义与原先一致(同样 panic),但把「这是不变量
17/// 断言」的意图写进调用点,模块级 `deny` 仍能拦住随手写的 unwrap。
18#[inline]
19#[allow(clippy::panic)] // 不变量断言:前提被破坏必须立刻暴露
20fn invariant<T>(value: Option<T>, message: &str) -> T {
21    match value {
22        Some(value) => value,
23        None => panic!("{message}"),
24    }
25}
26
27/// 为元素添加右键菜单的扩展 trait
28pub trait ContextMenuExt: InteractiveElement + ParentElement + Styled {
29    /// 为元素添加右键菜单
30    ///
31    /// 这将把元素改为 `relative` 定位,并添加一个子 `ContextMenu` 元素。
32    /// 因为 `ContextMenu` 元素是 `absolute` 定位,所以不会影响父元素的布局。
33    #[track_caller]
34    fn context_menu(
35        mut self,
36        f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
37    ) -> ContextMenu<Self>
38    where
39        Self: Sized,
40    {
41        // ID 必须跨渲染保持稳定,否则元素状态(打开的菜单)会在每次重新渲染时丢失。
42        let caller = std::panic::Location::caller();
43        let id = self
44            .interactivity()
45            .element_id
46            .clone()
47            .map(|id| ElementId::Name(format!("context-menu-{:?}", id).into()))
48            .unwrap_or_else(|| ElementId::CodeLocation(*caller));
49        ContextMenu::new(id, self).menu(f)
50    }
51}
52
53impl<E: InteractiveElement + ParentElement + Styled> ContextMenuExt for E {}
54
55/// 可在右键时显示的右键菜单
56pub struct ContextMenu<E: ParentElement + Styled + Sized> {
57    id: ElementId,
58    element: Option<E>,
59    menu: Option<Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>>,
60    // 未使用,仅用于样式细化转发
61    _ignore_style: StyleRefinement,
62    anchor: Anchor,
63}
64
65impl<E: ParentElement + Styled> ContextMenu<E> {
66    /// 使用给定的 ID 创建新的右键菜单
67    pub fn new(id: impl Into<ElementId>, element: E) -> Self {
68        Self {
69            id: id.into(),
70            element: Some(element),
71            menu: None,
72            anchor: Anchor::TopLeft,
73            _ignore_style: StyleRefinement::default(),
74        }
75    }
76
77    /// 使用给定的构建器构建右键菜单
78    #[must_use]
79    fn menu<F>(mut self, builder: F) -> Self
80    where
81        F: Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
82    {
83        self.menu = Some(Rc::new(builder));
84        self
85    }
86
87    fn with_element_state<R>(
88        &mut self,
89        id: &GlobalElementId,
90        window: &mut Window,
91        cx: &mut App,
92        f: impl FnOnce(&mut Self, &mut ContextMenuState, &mut Window, &mut App) -> R,
93    ) -> R {
94        window.with_optional_element_state::<ContextMenuState, _>(
95            Some(id),
96            |element_state, window| {
97                // 传入了 Some(id),外层必为 Some;内层 None 表示首帧未初始化
98                let mut element_state =
99                    invariant(element_state, "上下文菜单:已传入元素 id").unwrap_or_default();
100                let result = f(self, &mut element_state, window, cx);
101                (result, Some(element_state))
102            },
103        )
104    }
105}
106
107impl<E: ParentElement + Styled> ParentElement for ContextMenu<E> {
108    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
109        if let Some(element) = &mut self.element {
110            element.extend(elements);
111        }
112    }
113}
114
115impl<E: ParentElement + Styled> Styled for ContextMenu<E> {
116    fn style(&mut self) -> &mut StyleRefinement {
117        if let Some(element) = &mut self.element {
118            element.style()
119        } else {
120            &mut self._ignore_style
121        }
122    }
123}
124
125impl<E: ParentElement + Styled + IntoElement + 'static> IntoElement for ContextMenu<E> {
126    type Element = Self;
127
128    fn into_element(self) -> Self::Element {
129        self
130    }
131}
132
133/// 右键菜单共享状态
134struct ContextMenuSharedState {
135    menu_view: Option<Entity<PopupMenu>>,
136    open: bool,
137    position: Point<Pixels>,
138    _subscription: Option<Subscription>,
139}
140
141/// 右键菜单元素状态
142pub struct ContextMenuState {
143    element: Option<AnyElement>,
144    shared_state: Rc<RefCell<ContextMenuSharedState>>,
145}
146
147impl Default for ContextMenuState {
148    fn default() -> Self {
149        Self {
150            element: None,
151            shared_state: Rc::new(RefCell::new(ContextMenuSharedState {
152                menu_view: None,
153                open: false,
154                position: Default::default(),
155                _subscription: None,
156            })),
157        }
158    }
159}
160
161impl<E: ParentElement + Styled + IntoElement + 'static> Element for ContextMenu<E> {
162    type RequestLayoutState = ContextMenuState;
163    type PrepaintState = Hitbox;
164
165    fn id(&self) -> Option<ElementId> {
166        Some(self.id.clone())
167    }
168
169    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
170        None
171    }
172
173    fn request_layout(
174        &mut self,
175        id: Option<&crate::GlobalElementId>,
176        _: Option<&crate::InspectorElementId>,
177        window: &mut Window,
178        cx: &mut App,
179    ) -> (crate::LayoutId, Self::RequestLayoutState) {
180        let anchor = self.anchor;
181
182        // ContextMenu::id() 恒返回 Some,框架必带元素 id
183        self.with_element_state(
184            invariant(id, "上下文菜单:元素必有 id"),
185            window,
186            cx,
187            |this, state: &mut ContextMenuState, window, cx| {
188                let (position, open) = {
189                    let shared_state = state.shared_state.borrow();
190                    (shared_state.position, shared_state.open)
191                };
192                let menu_view = state.shared_state.borrow().menu_view.clone();
193                let mut menu_element = None;
194                if open {
195                    let has_menu_item = menu_view
196                        .as_ref()
197                        .map(|menu| !menu.read(cx).is_empty())
198                        .unwrap_or(false);
199
200                    if has_menu_item {
201                        menu_element = Some(
202                            deferred(
203                                anchored().child(
204                                    div()
205                                        .w(window.bounds().size.width)
206                                        .h(window.bounds().size.height)
207                                        .on_scroll_wheel(|_, _, cx| {
208                                            cx.stop_propagation();
209                                        })
210                                        .child(
211                                            anchored()
212                                                .position(position)
213                                                .snap_to_window_with_margin(px(8.))
214                                                .anchor(anchor)
215                                                .when_some(menu_view, |this, menu| {
216                                                    // 聚焦菜单,以便其处理动作
217                                                    if !menu
218                                                        .focus_handle(cx)
219                                                        .contains_focused(window, cx)
220                                                    {
221                                                        menu.focus_handle(cx).focus(window, cx);
222                                                    }
223
224                                                    this.child(menu)
225                                                }),
226                                        ),
227                                ),
228                            )
229                            .with_priority(1)
230                            .into_any(),
231                        );
232                    }
233                }
234
235                // 构造时必有 element,request_layout 每帧只 take 一次
236                let mut element = invariant(
237                    this.element.take(),
238                    "上下文菜单:request_layout 时元素必存在",
239                )
240                .children(menu_element)
241                .into_any_element();
242
243                let layout_id = element.request_layout(window, cx);
244
245                (
246                    layout_id,
247                    ContextMenuState {
248                        element: Some(element),
249                        ..Default::default()
250                    },
251                )
252            },
253        )
254    }
255
256    fn prepaint(
257        &mut self,
258        _: Option<&crate::GlobalElementId>,
259        _: Option<&InspectorElementId>,
260        bounds: crate::Bounds<crate::Pixels>,
261        request_layout: &mut Self::RequestLayoutState,
262        window: &mut Window,
263        cx: &mut App,
264    ) -> Self::PrepaintState {
265        if let Some(element) = &mut request_layout.element {
266            element.prepaint(window, cx);
267        }
268        window.insert_hitbox(bounds, HitboxBehavior::Normal)
269    }
270
271    fn paint(
272        &mut self,
273        id: Option<&crate::GlobalElementId>,
274        _: Option<&InspectorElementId>,
275        _: crate::Bounds<crate::Pixels>,
276        request_layout: &mut Self::RequestLayoutState,
277        hitbox: &mut Self::PrepaintState,
278        window: &mut Window,
279        cx: &mut App,
280    ) {
281        if let Some(element) = &mut request_layout.element {
282            element.paint(window, cx);
283        }
284
285        // 在设置元素状态之前取出构建器以避免借用问题
286        let builder = self.menu.clone();
287
288        // ContextMenu::id() 恒返回 Some,框架必带元素 id
289        self.with_element_state(
290            invariant(id, "上下文菜单:元素必有 id"),
291            window,
292            cx,
293            |_view, state: &mut ContextMenuState, window, _| {
294                let shared_state = state.shared_state.clone();
295
296                let hitbox = hitbox.clone();
297                // 当右键点击时,构建内容菜单并在鼠标位置显示
298                window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
299                    if phase.bubble()
300                        && event.button == MouseButton::Right
301                        && hitbox.is_hovered(window)
302                    {
303                        // 捕获聚焦元素以在关闭时恢复焦点。
304                        // 如果焦点仍在之前的菜单上,则保留其捕获的焦点。
305                        let previous_focus_handle = window.focused(cx).and_then(|focused| {
306                            let shared_state = shared_state.borrow();
307                            match shared_state.menu_view.as_ref() {
308                                Some(menu) if menu.read(cx).focus_handle == focused => {
309                                    menu.read(cx).previous_focus_handle.clone()
310                                }
311                                _ => Some(focused),
312                            }
313                        });
314
315                        {
316                            let mut shared_state = shared_state.borrow_mut();
317                            // 清除现有菜单视图以允许立即替换
318                            // 设置新位置并打开菜单
319                            shared_state.menu_view = None;
320                            shared_state._subscription = None;
321                            shared_state.position = event.position;
322                            shared_state.open = true;
323                        }
324
325                        // 使用 defer 在下一帧构建菜单,避免竞态条件
326                        window.defer(cx, {
327                            let shared_state = shared_state.clone();
328                            let builder = builder.clone();
329                            move |window, cx| {
330                                let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
331                                    let Some(build) = &builder else {
332                                        return menu;
333                                    };
334                                    build(menu, window, cx)
335                                });
336                                menu.update(cx, |menu, cx| {
337                                    menu.set_previous_focus(previous_focus_handle, cx);
338                                });
339
340                                // 设置关闭处理的订阅
341                                let _subscription = window.subscribe(&menu, cx, {
342                                    let shared_state = shared_state.clone();
343                                    move |_, _: &DismissEvent, window, _cx| {
344                                        shared_state.borrow_mut().open = false;
345                                        window.refresh();
346                                    }
347                                });
348
349                                // 使用构建的菜单和订阅更新共享状态
350                                {
351                                    let mut state = shared_state.borrow_mut();
352                                    state.menu_view = Some(menu.clone());
353                                    state._subscription = Some(_subscription);
354                                    window.refresh();
355                                }
356                            }
357                        });
358                    }
359                });
360            },
361        );
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use crate::theme::Theme;
369    use crate::{
370        Context, FocusHandle, IntoElement, Render, TestAppContext, VisualTestContext, point, px,
371    };
372    use std::cell::Cell;
373
374    actions!(context_menu_test, [RemoveTab]);
375
376    /// 回归测试形态:动作处理器位于触发器的祖先(如动作栏)上,
377    /// 当焦点位于内容区时,该祖先不在焦点路径上。
378    struct TestRoot {
379        content_focus: FocusHandle,
380        received: Rc<Cell<bool>>,
381    }
382
383    impl Render for TestRoot {
384        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
385            let received = self.received.clone();
386            div()
387                .size_full()
388                .child(
389                    div()
390                        .id("content")
391                        .h(px(40.))
392                        .track_focus(&self.content_focus),
393                )
394                .child(
395                    div()
396                        .id("action-bar")
397                        .h(px(60.))
398                        .on_action(move |_: &RemoveTab, _, _| received.set(true))
399                        .child(
400                            div()
401                                .id("tab")
402                                .size_full()
403                                .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
404                        ),
405                )
406        }
407    }
408
409    #[rgpui::test]
410    fn action_bubbles_from_trigger_and_focus_restores_on_dismiss(cx: &mut TestAppContext) {
411        cx.update(|cx| {
412            cx.set_global(Theme::default());
413            super::super::popup_menu::init(cx);
414        });
415
416        let received = Rc::new(Cell::new(false));
417        let (root, cx) = cx.add_window_view({
418            let received = received.clone();
419            move |window, cx| {
420                let content_focus = cx.focus_handle();
421                content_focus.focus(window, cx);
422                TestRoot {
423                    content_focus,
424                    received,
425                }
426            }
427        });
428        let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
429        let cx: &mut VisualTestContext = cx;
430        cx.run_until_parked();
431        cx.update(|window, cx| {
432            _ = window.draw(cx);
433        });
434
435        // 在标签页内右键打开上下文菜单。
436        cx.simulate_event(MouseDownEvent {
437            button: MouseButton::Right,
438            position: point(px(50.), px(70.)),
439            modifiers: Default::default(),
440            click_count: 1,
441            first_mouse: false,
442        });
443        // 菜单实体在延迟回调中构建,然后在下次绘制时渲染(并聚焦)。
444        cx.run_until_parked();
445        cx.update(|window, cx| {
446            _ = window.draw(cx);
447        });
448
449        // 选择 "Close" 并确认。键盘确认和鼠标点击共享相同的 `confirm` 路径。
450        cx.simulate_keystrokes("down enter");
451        cx.run_until_parked();
452
453        // 动作必须到达触发器祖先链上的处理器,即使动作栏从未在焦点路径上。
454        assert!(received.get());
455        // 关闭时必须将焦点恢复到菜单打开前的位置。
456        cx.update(|window, cx| {
457            assert_eq!(window.focused(cx).as_ref(), Some(&content_focus));
458        });
459    }
460}