popover_menu.rs

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