right_click_menu.rs

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