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