right_click_menu.rs

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