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