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
111/// Creates a [`PopoverMenu`]
112pub fn popover_menu<M: ManagedView>(id: impl Into<ElementId>) -> PopoverMenu<M> {
113    PopoverMenu {
114        id: id.into(),
115        child_builder: None,
116        menu_builder: None,
117        anchor: AnchorCorner::TopLeft,
118        attach: None,
119        offset: None,
120    }
121}
122
123pub struct PopoverMenuState<M> {
124    child_layout_id: Option<LayoutId>,
125    child_element: Option<AnyElement>,
126    child_bounds: Option<Bounds<Pixels>>,
127    menu_element: Option<AnyElement>,
128    menu: Rc<RefCell<Option<View<M>>>>,
129}
130
131impl<M: ManagedView> Element for PopoverMenu<M> {
132    type State = PopoverMenuState<M>;
133
134    fn request_layout(
135        &mut self,
136        element_state: Option<Self::State>,
137        cx: &mut WindowContext,
138    ) -> (gpui::LayoutId, Self::State) {
139        let mut menu_layout_id = None;
140
141        let (menu, child_bounds) = if let Some(element_state) = element_state {
142            (element_state.menu, element_state.child_bounds)
143        } else {
144            (Rc::default(), None)
145        };
146
147        let menu_element = menu.borrow_mut().as_mut().map(|menu| {
148            let mut overlay = overlay().snap_to_window().anchor(self.anchor);
149
150            if let Some(child_bounds) = child_bounds {
151                overlay = overlay.position(
152                    self.resolved_attach().corner(child_bounds) + self.resolved_offset(cx),
153                );
154            }
155
156            let mut element = overlay.child(menu.clone()).into_any();
157            menu_layout_id = Some(element.request_layout(cx));
158            element
159        });
160
161        let mut child_element = self
162            .child_builder
163            .take()
164            .map(|child_builder| (child_builder)(menu.clone(), self.menu_builder.clone()));
165
166        let child_layout_id = child_element
167            .as_mut()
168            .map(|child_element| child_element.request_layout(cx));
169
170        let layout_id = cx.request_layout(
171            &gpui::Style::default(),
172            menu_layout_id.into_iter().chain(child_layout_id),
173        );
174
175        (
176            layout_id,
177            PopoverMenuState {
178                menu,
179                child_element,
180                child_layout_id,
181                menu_element,
182                child_bounds,
183            },
184        )
185    }
186
187    fn paint(
188        &mut self,
189        _: Bounds<gpui::Pixels>,
190        element_state: &mut Self::State,
191        cx: &mut WindowContext,
192    ) {
193        if let Some(mut child) = element_state.child_element.take() {
194            child.paint(cx);
195        }
196
197        if let Some(child_layout_id) = element_state.child_layout_id.take() {
198            element_state.child_bounds = Some(cx.layout_bounds(child_layout_id));
199        }
200
201        if let Some(mut menu) = element_state.menu_element.take() {
202            menu.paint(cx);
203
204            if let Some(child_bounds) = element_state.child_bounds {
205                let interactive_bounds = InteractiveBounds {
206                    bounds: child_bounds,
207                    stacking_order: cx.stacking_order().clone(),
208                };
209
210                // Mouse-downing outside the menu dismisses it, so we don't
211                // want a click on the toggle to re-open it.
212                cx.on_mouse_event(move |e: &MouseDownEvent, phase, cx| {
213                    if phase == DispatchPhase::Bubble
214                        && interactive_bounds.visibly_contains(&e.position, cx)
215                    {
216                        cx.stop_propagation()
217                    }
218                })
219            }
220        }
221    }
222}
223
224impl<M: ManagedView> IntoElement for PopoverMenu<M> {
225    type Element = Self;
226
227    fn element_id(&self) -> Option<gpui::ElementId> {
228        Some(self.id.clone())
229    }
230
231    fn into_element(self) -> Self::Element {
232        self
233    }
234}