1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 div, overlay, AnchorCorner, AnyElement, Bounds, DismissEvent, DispatchPhase, Element,
5 ElementContext, 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 ElementContext,
44 f: impl FnOnce(&mut Self, &mut MenuHandleElementState<M>, &mut ElementContext) -> 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 MenuHandleFrameState {
92 child_layout_id: Option<LayoutId>,
93 child_element: Option<AnyElement>,
94 menu_element: Option<AnyElement>,
95}
96
97impl<M: ManagedView> Element for RightClickMenu<M> {
98 type BeforeLayout = MenuHandleFrameState;
99 type AfterLayout = Hitbox;
100
101 fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, Self::BeforeLayout) {
102 self.with_element_state(cx, |this, element_state, cx| {
103 let mut menu_layout_id = None;
104
105 let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
106 let mut overlay = overlay().snap_to_window();
107 if let Some(anchor) = this.anchor {
108 overlay = overlay.anchor(anchor);
109 }
110 overlay = overlay.position(*element_state.position.borrow());
111
112 let mut element = overlay
113 .child(div().occlude().child(menu.clone()))
114 .into_any();
115 menu_layout_id = Some(element.before_layout(cx));
116 element
117 });
118
119 let mut child_element = this
120 .child_builder
121 .take()
122 .map(|child_builder| (child_builder)(element_state.menu.borrow().is_some()));
123
124 let child_layout_id = child_element
125 .as_mut()
126 .map(|child_element| child_element.before_layout(cx));
127
128 let layout_id = cx.request_layout(
129 &gpui::Style::default(),
130 menu_layout_id.into_iter().chain(child_layout_id),
131 );
132
133 (
134 layout_id,
135 MenuHandleFrameState {
136 child_element,
137 child_layout_id,
138 menu_element,
139 },
140 )
141 })
142 }
143
144 fn after_layout(
145 &mut self,
146 bounds: Bounds<Pixels>,
147 before_layout: &mut Self::BeforeLayout,
148 cx: &mut ElementContext,
149 ) -> Hitbox {
150 cx.with_element_id(Some(self.id.clone()), |cx| {
151 let hitbox = cx.insert_hitbox(bounds, false);
152
153 if let Some(child) = before_layout.child_element.as_mut() {
154 child.after_layout(cx);
155 }
156
157 if let Some(menu) = before_layout.menu_element.as_mut() {
158 menu.after_layout(cx);
159 }
160
161 hitbox
162 })
163 }
164
165 fn paint(
166 &mut self,
167 _bounds: Bounds<gpui::Pixels>,
168 before_layout: &mut Self::BeforeLayout,
169 hitbox: &mut Self::AfterLayout,
170 cx: &mut ElementContext,
171 ) {
172 self.with_element_state(cx, |this, element_state, cx| {
173 if let Some(mut child) = before_layout.child_element.take() {
174 child.paint(cx);
175 }
176
177 if let Some(mut menu) = before_layout.menu_element.take() {
178 menu.paint(cx);
179 return;
180 }
181
182 let Some(builder) = this.menu_builder.take() else {
183 return;
184 };
185
186 let attach = this.attach;
187 let menu = element_state.menu.clone();
188 let position = element_state.position.clone();
189 let child_layout_id = before_layout.child_layout_id;
190 let child_bounds = cx.layout_bounds(child_layout_id.unwrap());
191
192 let hitbox_id = hitbox.id;
193 cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
194 if phase == DispatchPhase::Bubble
195 && event.button == MouseButton::Right
196 && hitbox_id.is_hovered(cx)
197 {
198 cx.stop_propagation();
199 cx.prevent_default();
200
201 let new_menu = (builder)(cx);
202 let menu2 = menu.clone();
203 let previous_focus_handle = cx.focused();
204
205 cx.subscribe(&new_menu, move |modal, _: &DismissEvent, cx| {
206 if modal.focus_handle(cx).contains_focused(cx) {
207 if let Some(previous_focus_handle) = previous_focus_handle.as_ref() {
208 cx.focus(previous_focus_handle);
209 }
210 }
211 *menu2.borrow_mut() = None;
212 cx.refresh();
213 })
214 .detach();
215 cx.focus_view(&new_menu);
216 *menu.borrow_mut() = Some(new_menu);
217 *position.borrow_mut() = if child_layout_id.is_some() {
218 if let Some(attach) = attach {
219 attach.corner(child_bounds)
220 } else {
221 cx.mouse_position()
222 }
223 } else {
224 cx.mouse_position()
225 };
226 cx.refresh();
227 }
228 });
229 })
230 }
231}
232
233impl<M: ManagedView> IntoElement for RightClickMenu<M> {
234 type Element = Self;
235
236 fn into_element(self) -> Self::Element {
237 self
238 }
239}