1use 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#[inline]
19#[allow(clippy::panic)] fn invariant<T>(value: Option<T>, message: &str) -> T {
21 match value {
22 Some(value) => value,
23 None => panic!("{message}"),
24 }
25}
26
27pub trait ContextMenuExt: InteractiveElement + ParentElement + Styled {
29 #[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 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
55pub 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 _ignore_style: StyleRefinement,
62 anchor: Anchor,
63}
64
65impl<E: ParentElement + Styled> ContextMenu<E> {
66 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 #[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 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
133struct ContextMenuSharedState {
135 menu_view: Option<Entity<PopupMenu>>,
136 open: bool,
137 position: Point<Pixels>,
138 _subscription: Option<Subscription>,
139}
140
141pub 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 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 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 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 let builder = self.menu.clone();
287
288 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 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 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 shared_state.menu_view = None;
320 shared_state._subscription = None;
321 shared_state.position = event.position;
322 shared_state.open = true;
323 }
324
325 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 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 {
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 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 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 cx.run_until_parked();
445 cx.update(|window, cx| {
446 _ = window.draw(cx);
447 });
448
449 cx.simulate_keystrokes("down enter");
451 cx.run_until_parked();
452
453 assert!(received.get());
455 cx.update(|window, cx| {
457 assert_eq!(window.focused(cx).as_ref(), Some(&content_focus));
458 });
459 }
460}