popover_menu.rs

  1use std::{cell::RefCell, rc::Rc};
  2
  3use gpui::{
  4    anchored, deferred, div, point, prelude::FluentBuilder, px, AnchorCorner, AnyElement, Bounds,
  5    DismissEvent, DispatchPhase, Element, ElementContext, ElementId, HitboxId, InteractiveElement,
  6    IntoElement, LayoutId, ManagedView, MouseDownEvent, ParentElement, Pixels, Point, View,
  7    VisualContext, WindowContext,
  8};
  9
 10use crate::prelude::*;
 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_from_px(5.) * 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 anchored = anchored().snap_to_window().anchor(this.anchor);
180                if let Some(child_bounds) = element_state.child_bounds {
181                    anchored = anchored.position(
182                        this.resolved_attach().corner(child_bounds) + this.resolved_offset(cx),
183                    );
184                }
185                let mut element = deferred(anchored.child(div().occlude().child(menu.clone())))
186                    .with_priority(1)
187                    .into_any();
188
189                menu_layout_id = Some(element.before_layout(cx));
190                element
191            });
192
193            let mut child_element = this.child_builder.take().map(|child_builder| {
194                (child_builder)(element_state.menu.clone(), this.menu_builder.clone())
195            });
196
197            let child_layout_id = child_element
198                .as_mut()
199                .map(|child_element| child_element.before_layout(cx));
200
201            let layout_id = cx.request_layout(
202                &gpui::Style::default(),
203                menu_layout_id.into_iter().chain(child_layout_id),
204            );
205
206            (
207                layout_id,
208                PopoverMenuFrameState {
209                    child_element,
210                    child_layout_id,
211                    menu_element,
212                },
213            )
214        })
215    }
216
217    fn after_layout(
218        &mut self,
219        _bounds: Bounds<Pixels>,
220        before_layout: &mut Self::BeforeLayout,
221        cx: &mut ElementContext,
222    ) -> Option<HitboxId> {
223        self.with_element_state(cx, |_this, element_state, cx| {
224            if let Some(child) = before_layout.child_element.as_mut() {
225                child.after_layout(cx);
226            }
227
228            if let Some(menu) = before_layout.menu_element.as_mut() {
229                menu.after_layout(cx);
230            }
231
232            before_layout.child_layout_id.map(|layout_id| {
233                let bounds = cx.layout_bounds(layout_id);
234                element_state.child_bounds = Some(bounds);
235                cx.insert_hitbox(bounds, false).id
236            })
237        })
238    }
239
240    fn paint(
241        &mut self,
242        _: Bounds<gpui::Pixels>,
243        before_layout: &mut Self::BeforeLayout,
244        child_hitbox: &mut Option<HitboxId>,
245        cx: &mut ElementContext,
246    ) {
247        self.with_element_state(cx, |_this, _element_state, cx| {
248            if let Some(mut child) = before_layout.child_element.take() {
249                child.paint(cx);
250            }
251
252            if let Some(mut menu) = before_layout.menu_element.take() {
253                menu.paint(cx);
254
255                if let Some(child_hitbox) = *child_hitbox {
256                    // Mouse-downing outside the menu dismisses it, so we don't
257                    // want a click on the toggle to re-open it.
258                    cx.on_mouse_event(move |_: &MouseDownEvent, phase, cx| {
259                        if phase == DispatchPhase::Bubble && child_hitbox.is_hovered(cx) {
260                            cx.stop_propagation()
261                        }
262                    })
263                }
264            }
265        })
266    }
267}
268
269impl<M: ManagedView> IntoElement for PopoverMenu<M> {
270    type Element = Self;
271
272    fn into_element(self) -> Self::Element {
273        self
274    }
275}