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