right_click_menu.rs

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