popover_menu.rs

  1use std::{cell::RefCell, rc::Rc};
  2
  3use gpui::{
  4    overlay, point, px, rems, AnchorCorner, AnyElement, Bounds, DismissEvent, DispatchPhase,
  5    Element, ElementId, InteractiveBounds, IntoElement, LayoutId, ManagedView, MouseDownEvent,
  6    ParentElement, Pixels, Point, View, VisualContext, WindowContext,
  7};
  8
  9use crate::{Clickable, Selectable};
 10
 11pub trait PopoverTrigger: IntoElement + Clickable + Selectable + 'static {}
 12
 13impl<T: IntoElement + Clickable + Selectable + 'static> PopoverTrigger for T {}
 14
 15pub struct PopoverMenu<M: ManagedView> {
 16    id: ElementId,
 17    child_builder: Option<
 18        Box<
 19            dyn FnOnce(
 20                    Rc<RefCell<Option<View<M>>>>,
 21                    Option<Rc<dyn Fn(&mut WindowContext) -> Option<View<M>> + 'static>>,
 22                ) -> AnyElement
 23                + 'static,
 24        >,
 25    >,
 26    menu_builder: Option<Rc<dyn Fn(&mut WindowContext) -> Option<View<M>> + 'static>>,
 27    anchor: AnchorCorner,
 28    attach: Option<AnchorCorner>,
 29    offset: Option<Point<Pixels>>,
 30}
 31
 32impl<M: ManagedView> PopoverMenu<M> {
 33    pub fn menu(mut self, f: impl Fn(&mut WindowContext) -> Option<View<M>> + 'static) -> Self {
 34        self.menu_builder = Some(Rc::new(f));
 35        self
 36    }
 37
 38    pub fn trigger<T: PopoverTrigger>(mut self, t: T) -> Self {
 39        self.child_builder = Some(Box::new(|menu, builder| {
 40            let open = menu.borrow().is_some();
 41            t.selected(open)
 42                .when_some(builder, |el, builder| {
 43                    el.on_click({
 44                        move |_, cx| {
 45                            let Some(new_menu) = (builder)(cx) else {
 46                                return;
 47                            };
 48                            let menu2 = menu.clone();
 49                            let previous_focus_handle = cx.focused();
 50
 51                            cx.subscribe(&new_menu, move |modal, _: &DismissEvent, cx| {
 52                                if modal.focus_handle(cx).contains_focused(cx) {
 53                                    if previous_focus_handle.is_some() {
 54                                        cx.focus(&previous_focus_handle.as_ref().unwrap())
 55                                    }
 56                                }
 57                                *menu2.borrow_mut() = None;
 58                                cx.notify();
 59                            })
 60                            .detach();
 61                            cx.focus_view(&new_menu);
 62                            *menu.borrow_mut() = Some(new_menu);
 63                        }
 64                    })
 65                })
 66                .into_any_element()
 67        }));
 68        self
 69    }
 70
 71    /// anchor defines which corner of the menu to anchor to the attachment point
 72    /// (by default the cursor position, but see attach)
 73    pub fn anchor(mut self, anchor: AnchorCorner) -> Self {
 74        self.anchor = anchor;
 75        self
 76    }
 77
 78    /// attach defines which corner of the handle to attach the menu's anchor to
 79    pub fn attach(mut self, attach: AnchorCorner) -> Self {
 80        self.attach = Some(attach);
 81        self
 82    }
 83
 84    /// offset offsets the position of the content by that many pixels.
 85    pub fn offset(mut self, offset: Point<Pixels>) -> Self {
 86        self.offset = Some(offset);
 87        self
 88    }
 89
 90    fn resolved_attach(&self) -> AnchorCorner {
 91        self.attach.unwrap_or_else(|| match self.anchor {
 92            AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
 93            AnchorCorner::TopRight => AnchorCorner::BottomRight,
 94            AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
 95            AnchorCorner::BottomRight => AnchorCorner::TopRight,
 96        })
 97    }
 98
 99    fn resolved_offset(&self, cx: &WindowContext) -> Point<Pixels> {
100        self.offset.unwrap_or_else(|| {
101            // Default offset = 4px padding + 1px border
102            let offset = rems(5. / 16.) * cx.rem_size();
103            match self.anchor {
104                AnchorCorner::TopRight | AnchorCorner::BottomRight => point(offset, px(0.)),
105                AnchorCorner::TopLeft | AnchorCorner::BottomLeft => point(-offset, px(0.)),
106            }
107        })
108    }
109}
110
111pub fn popover_menu<M: ManagedView>(id: impl Into<ElementId>) -> PopoverMenu<M> {
112    PopoverMenu {
113        id: id.into(),
114        child_builder: None,
115        menu_builder: None,
116        anchor: AnchorCorner::TopLeft,
117        attach: None,
118        offset: None,
119    }
120}
121
122pub struct PopoverMenuState<M> {
123    child_layout_id: Option<LayoutId>,
124    child_element: Option<AnyElement>,
125    child_bounds: Option<Bounds<Pixels>>,
126    menu_element: Option<AnyElement>,
127    menu: Rc<RefCell<Option<View<M>>>>,
128}
129
130impl<M: ManagedView> Element for PopoverMenu<M> {
131    type State = PopoverMenuState<M>;
132
133    fn request_layout(
134        &mut self,
135        element_state: Option<Self::State>,
136        cx: &mut WindowContext,
137    ) -> (gpui::LayoutId, Self::State) {
138        let mut menu_layout_id = None;
139
140        let (menu, child_bounds) = if let Some(element_state) = element_state {
141            (element_state.menu, element_state.child_bounds)
142        } else {
143            (Rc::default(), None)
144        };
145
146        let menu_element = menu.borrow_mut().as_mut().map(|menu| {
147            let mut overlay = overlay().snap_to_window().anchor(self.anchor);
148
149            if let Some(child_bounds) = child_bounds {
150                overlay = overlay.position(
151                    self.resolved_attach().corner(child_bounds) + self.resolved_offset(cx),
152                );
153            }
154
155            let mut element = overlay.child(menu.clone()).into_any();
156            menu_layout_id = Some(element.request_layout(cx));
157            element
158        });
159
160        let mut child_element = self
161            .child_builder
162            .take()
163            .map(|child_builder| (child_builder)(menu.clone(), self.menu_builder.clone()));
164
165        let child_layout_id = child_element
166            .as_mut()
167            .map(|child_element| child_element.request_layout(cx));
168
169        let layout_id = cx.request_layout(
170            &gpui::Style::default(),
171            menu_layout_id.into_iter().chain(child_layout_id),
172        );
173
174        (
175            layout_id,
176            PopoverMenuState {
177                menu,
178                child_element,
179                child_layout_id,
180                menu_element,
181                child_bounds,
182            },
183        )
184    }
185
186    fn paint(
187        &mut self,
188        _: Bounds<gpui::Pixels>,
189        element_state: &mut Self::State,
190        cx: &mut WindowContext,
191    ) {
192        if let Some(mut child) = element_state.child_element.take() {
193            child.paint(cx);
194        }
195
196        if let Some(child_layout_id) = element_state.child_layout_id.take() {
197            element_state.child_bounds = Some(cx.layout_bounds(child_layout_id));
198        }
199
200        if let Some(mut menu) = element_state.menu_element.take() {
201            menu.paint(cx);
202
203            if let Some(child_bounds) = element_state.child_bounds {
204                let interactive_bounds = InteractiveBounds {
205                    bounds: child_bounds,
206                    stacking_order: cx.stacking_order().clone(),
207                };
208
209                // Mouse-downing outside the menu dismisses it, so we don't
210                // want a click on the toggle to re-open it.
211                cx.on_mouse_event(move |e: &MouseDownEvent, phase, cx| {
212                    if phase == DispatchPhase::Bubble
213                        && interactive_bounds.visibly_contains(&e.position, cx)
214                    {
215                        cx.stop_propagation()
216                    }
217                })
218            }
219        }
220    }
221}
222
223impl<M: ManagedView> IntoElement for PopoverMenu<M> {
224    type Element = Self;
225
226    fn element_id(&self) -> Option<gpui::ElementId> {
227        Some(self.id.clone())
228    }
229
230    fn into_element(self) -> Self::Element {
231        self
232    }
233}