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