1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 AnyElement, App, Bounds, Corner, DismissEvent, DispatchPhase, Element, ElementId, Entity,
5 Focusable as _, GlobalElementId, Hitbox, HitboxBehavior, InteractiveElement, IntoElement,
6 LayoutId, ManagedView, MouseButton, MouseDownEvent, ParentElement, Pixels, Point, Window,
7 anchored, deferred, div, px,
8};
9
10pub struct RightClickMenu<M: ManagedView> {
11 id: ElementId,
12 child_builder: Option<Box<dyn FnOnce(bool, &mut Window, &mut App) -> AnyElement + 'static>>,
13 menu_builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> Entity<M> + 'static>>,
14 anchor: Option<Corner>,
15 attach: Option<Corner>,
16}
17
18impl<M: ManagedView> RightClickMenu<M> {
19 pub fn menu(mut self, f: impl Fn(&mut Window, &mut App) -> Entity<M> + 'static) -> Self {
20 self.menu_builder = Some(Rc::new(f));
21 self
22 }
23
24 pub fn trigger<F, E>(mut self, e: F) -> Self
25 where
26 F: FnOnce(bool, &mut Window, &mut App) -> E + 'static,
27 E: IntoElement + 'static,
28 {
29 self.child_builder = Some(Box::new(move |is_menu_active, window, cx| {
30 e(is_menu_active, window, cx).into_any_element()
31 }));
32 self
33 }
34
35 /// anchor defines which corner of the menu to anchor to the attachment point
36 /// (by default the cursor position, but see attach)
37 pub fn anchor(mut self, anchor: Corner) -> Self {
38 self.anchor = Some(anchor);
39 self
40 }
41
42 /// attach defines which corner of the handle to attach the menu's anchor to
43 pub fn attach(mut self, attach: Corner) -> Self {
44 self.attach = Some(attach);
45 self
46 }
47
48 fn with_element_state<R>(
49 &mut self,
50 global_id: &GlobalElementId,
51 window: &mut Window,
52 cx: &mut App,
53 f: impl FnOnce(&mut Self, &mut MenuHandleElementState<M>, &mut Window, &mut App) -> R,
54 ) -> R {
55 window.with_optional_element_state::<MenuHandleElementState<M>, _>(
56 Some(global_id),
57 |element_state, window| {
58 let mut element_state = element_state.unwrap().unwrap_or_default();
59 let result = f(self, &mut element_state, window, cx);
60 (result, Some(element_state))
61 },
62 )
63 }
64}
65
66/// Creates a [`RightClickMenu`]
67pub fn right_click_menu<M: ManagedView>(id: impl Into<ElementId>) -> RightClickMenu<M> {
68 RightClickMenu {
69 id: id.into(),
70 child_builder: None,
71 menu_builder: None,
72 anchor: None,
73 attach: None,
74 }
75}
76
77pub struct MenuHandleElementState<M> {
78 menu: Rc<RefCell<Option<Entity<M>>>>,
79 position: Rc<RefCell<Point<Pixels>>>,
80}
81
82impl<M> Clone for MenuHandleElementState<M> {
83 fn clone(&self) -> Self {
84 Self {
85 menu: Rc::clone(&self.menu),
86 position: Rc::clone(&self.position),
87 }
88 }
89}
90
91impl<M> Default for MenuHandleElementState<M> {
92 fn default() -> Self {
93 Self {
94 menu: Rc::default(),
95 position: Rc::default(),
96 }
97 }
98}
99
100pub struct RequestLayoutState {
101 child_layout_id: Option<LayoutId>,
102 child_element: Option<AnyElement>,
103 menu_element: Option<AnyElement>,
104}
105
106pub struct PrepaintState {
107 hitbox: Hitbox,
108 child_bounds: Option<Bounds<Pixels>>,
109}
110
111impl<M: ManagedView> Element for RightClickMenu<M> {
112 type RequestLayoutState = RequestLayoutState;
113 type PrepaintState = PrepaintState;
114
115 fn id(&self) -> Option<ElementId> {
116 Some(self.id.clone())
117 }
118
119 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
120 None
121 }
122
123 fn request_layout(
124 &mut self,
125 id: Option<&GlobalElementId>,
126 _inspector_id: Option<&gpui::InspectorElementId>,
127 window: &mut Window,
128 cx: &mut App,
129 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
130 self.with_element_state(
131 id.unwrap(),
132 window,
133 cx,
134 |this, element_state, window, cx| {
135 let mut menu_layout_id = None;
136
137 let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
138 let mut anchored = anchored().snap_to_window_with_margin(px(8.));
139 if let Some(anchor) = this.anchor {
140 anchored = anchored.anchor(anchor);
141 }
142 anchored = anchored.position(*element_state.position.borrow());
143
144 let mut element = deferred(anchored.child(div().occlude().child(menu.clone())))
145 .with_priority(1)
146 .into_any();
147
148 menu_layout_id = Some(element.request_layout(window, cx));
149 element
150 });
151
152 let mut child_element = this.child_builder.take().map(|child_builder| {
153 (child_builder)(element_state.menu.borrow().is_some(), window, cx)
154 });
155
156 let child_layout_id = child_element
157 .as_mut()
158 .map(|child_element| child_element.request_layout(window, cx));
159
160 let layout_id = window.request_layout(
161 gpui::Style::default(),
162 menu_layout_id.into_iter().chain(child_layout_id),
163 cx,
164 );
165
166 (
167 layout_id,
168 RequestLayoutState {
169 child_element,
170 child_layout_id,
171 menu_element,
172 },
173 )
174 },
175 )
176 }
177
178 fn prepaint(
179 &mut self,
180 _id: Option<&GlobalElementId>,
181 _inspector_id: Option<&gpui::InspectorElementId>,
182 bounds: Bounds<Pixels>,
183 request_layout: &mut Self::RequestLayoutState,
184 window: &mut Window,
185 cx: &mut App,
186 ) -> PrepaintState {
187 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
188
189 if let Some(child) = request_layout.child_element.as_mut() {
190 child.prepaint(window, cx);
191 }
192
193 if let Some(menu) = request_layout.menu_element.as_mut() {
194 menu.prepaint(window, cx);
195 }
196
197 PrepaintState {
198 hitbox,
199 child_bounds: request_layout
200 .child_layout_id
201 .map(|layout_id| window.layout_bounds(layout_id)),
202 }
203 }
204
205 fn paint(
206 &mut self,
207 id: Option<&GlobalElementId>,
208 _inspector_id: Option<&gpui::InspectorElementId>,
209 _bounds: Bounds<gpui::Pixels>,
210 request_layout: &mut Self::RequestLayoutState,
211 prepaint_state: &mut Self::PrepaintState,
212 window: &mut Window,
213 cx: &mut App,
214 ) {
215 self.with_element_state(
216 id.unwrap(),
217 window,
218 cx,
219 |this, element_state, window, cx| {
220 if let Some(mut child) = request_layout.child_element.take() {
221 child.paint(window, cx);
222 }
223
224 if let Some(mut menu) = request_layout.menu_element.take() {
225 menu.paint(window, cx);
226 return;
227 }
228
229 let Some(builder) = this.menu_builder.take() else {
230 return;
231 };
232
233 let attach = this.attach;
234 let menu = element_state.menu.clone();
235 let position = element_state.position.clone();
236 let child_bounds = prepaint_state.child_bounds;
237
238 let hitbox_id = prepaint_state.hitbox.id;
239 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
240 if phase == DispatchPhase::Bubble
241 && event.button == MouseButton::Right
242 && hitbox_id.is_hovered(window)
243 {
244 cx.stop_propagation();
245 window.prevent_default();
246
247 let new_menu = (builder)(window, cx);
248 let menu2 = menu.clone();
249 let previous_focus_handle = window.focused(cx);
250
251 window
252 .subscribe(&new_menu, cx, move |modal, _: &DismissEvent, window, cx| {
253 if modal.focus_handle(cx).contains_focused(window, cx)
254 && let Some(previous_focus_handle) =
255 previous_focus_handle.as_ref()
256 {
257 window.focus(previous_focus_handle);
258 }
259 *menu2.borrow_mut() = None;
260 window.refresh();
261 })
262 .detach();
263 window.focus(&new_menu.focus_handle(cx));
264 *menu.borrow_mut() = Some(new_menu);
265 *position.borrow_mut() = if let Some(child_bounds) = child_bounds {
266 if let Some(attach) = attach {
267 child_bounds.corner(attach)
268 } else {
269 window.mouse_position()
270 }
271 } else {
272 window.mouse_position()
273 };
274 window.refresh();
275 }
276 });
277 },
278 )
279 }
280}
281
282impl<M: ManagedView> IntoElement for RightClickMenu<M> {
283 type Element = Self;
284
285 fn into_element(self) -> Self::Element {
286 self
287 }
288}