popover_menu.rs

  1use std::{cell::RefCell, rc::Rc};
  2
  3use gpui::{
  4    AnyElement, AnyView, App, Bounds, Corner, DismissEvent, DispatchPhase, Element, ElementId,
  5    Entity, Focusable as _, GlobalElementId, HitboxId, InteractiveElement, IntoElement, LayoutId,
  6    Length, ManagedView, MouseDownEvent, ParentElement, Pixels, Point, Style, Window, anchored,
  7    deferred, div, point, prelude::FluentBuilder, px, size,
  8};
  9
 10use crate::prelude::*;
 11
 12pub trait PopoverTrigger: IntoElement + Clickable + Toggleable + 'static {}
 13
 14impl<T: IntoElement + Clickable + Toggleable + 'static> PopoverTrigger for T {}
 15
 16impl<T: Clickable> Clickable for gpui::AnimationElement<T>
 17where
 18    T: Clickable + 'static,
 19{
 20    fn on_click(
 21        self,
 22        handler: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static,
 23    ) -> Self {
 24        self.map_element(|e| e.on_click(handler))
 25    }
 26
 27    fn cursor_style(self, cursor_style: gpui::CursorStyle) -> Self {
 28        self.map_element(|e| e.cursor_style(cursor_style))
 29    }
 30}
 31
 32impl<T: Toggleable> Toggleable for gpui::AnimationElement<T>
 33where
 34    T: Toggleable + 'static,
 35{
 36    fn toggle_state(self, selected: bool) -> Self {
 37        self.map_element(|e| e.toggle_state(selected))
 38    }
 39}
 40
 41pub struct PopoverMenuHandle<M>(Rc<RefCell<Option<PopoverMenuHandleState<M>>>>);
 42
 43impl<M> Clone for PopoverMenuHandle<M> {
 44    fn clone(&self) -> Self {
 45        Self(self.0.clone())
 46    }
 47}
 48
 49impl<M> Default for PopoverMenuHandle<M> {
 50    fn default() -> Self {
 51        Self(Rc::default())
 52    }
 53}
 54
 55struct PopoverMenuHandleState<M> {
 56    menu_builder: Rc<dyn Fn(&mut Window, &mut App) -> Option<Entity<M>>>,
 57    menu: Rc<RefCell<Option<Entity<M>>>>,
 58    on_open: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
 59}
 60
 61impl<M: ManagedView> PopoverMenuHandle<M> {
 62    pub fn show(&self, window: &mut Window, cx: &mut App) {
 63        if let Some(state) = self.0.borrow().as_ref() {
 64            show_menu(
 65                &state.menu_builder,
 66                &state.menu,
 67                state.on_open.clone(),
 68                window,
 69                cx,
 70            );
 71        }
 72    }
 73
 74    pub fn hide(&self, cx: &mut App) {
 75        if let Some(state) = self.0.borrow().as_ref() {
 76            if let Some(menu) = state.menu.borrow().as_ref() {
 77                menu.update(cx, |_, cx| cx.emit(DismissEvent));
 78            }
 79        }
 80    }
 81
 82    pub fn toggle(&self, window: &mut Window, cx: &mut App) {
 83        if let Some(state) = self.0.borrow().as_ref() {
 84            if state.menu.borrow().is_some() {
 85                self.hide(cx);
 86            } else {
 87                self.show(window, cx);
 88            }
 89        }
 90    }
 91
 92    pub fn is_deployed(&self) -> bool {
 93        self.0
 94            .borrow()
 95            .as_ref()
 96            .map_or(false, |state| state.menu.borrow().as_ref().is_some())
 97    }
 98
 99    pub fn is_focused(&self, window: &Window, cx: &App) -> bool {
100        self.0.borrow().as_ref().map_or(false, |state| {
101            state
102                .menu
103                .borrow()
104                .as_ref()
105                .map_or(false, |model| model.focus_handle(cx).is_focused(window))
106        })
107    }
108}
109
110pub struct PopoverMenu<M: ManagedView> {
111    id: ElementId,
112    child_builder: Option<
113        Box<
114            dyn FnOnce(
115                    Rc<RefCell<Option<Entity<M>>>>,
116                    Option<Rc<dyn Fn(&mut Window, &mut App) -> Option<Entity<M>> + 'static>>,
117                ) -> AnyElement
118                + 'static,
119        >,
120    >,
121    menu_builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> Option<Entity<M>> + 'static>>,
122    anchor: Corner,
123    attach: Option<Corner>,
124    offset: Option<Point<Pixels>>,
125    trigger_handle: Option<PopoverMenuHandle<M>>,
126    on_open: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
127    full_width: bool,
128}
129
130impl<M: ManagedView> PopoverMenu<M> {
131    /// Returns a new [`PopoverMenu`].
132    pub fn new(id: impl Into<ElementId>) -> Self {
133        Self {
134            id: id.into(),
135            child_builder: None,
136            menu_builder: None,
137            anchor: Corner::TopLeft,
138            attach: None,
139            offset: None,
140            trigger_handle: None,
141            on_open: None,
142            full_width: false,
143        }
144    }
145
146    pub fn full_width(mut self, full_width: bool) -> Self {
147        self.full_width = full_width;
148        self
149    }
150
151    pub fn menu(
152        mut self,
153        f: impl Fn(&mut Window, &mut App) -> Option<Entity<M>> + 'static,
154    ) -> Self {
155        self.menu_builder = Some(Rc::new(f));
156        self
157    }
158
159    pub fn with_handle(mut self, handle: PopoverMenuHandle<M>) -> Self {
160        self.trigger_handle = Some(handle);
161        self
162    }
163
164    pub fn trigger<T: PopoverTrigger>(mut self, t: T) -> Self {
165        let on_open = self.on_open.clone();
166        self.child_builder = Some(Box::new(move |menu, builder| {
167            let open = menu.borrow().is_some();
168            t.toggle_state(open)
169                .when_some(builder, |el, builder| {
170                    el.on_click(move |_event, window, cx| {
171                        show_menu(&builder, &menu, on_open.clone(), window, cx)
172                    })
173                })
174                .into_any_element()
175        }));
176        self
177    }
178
179    /// This method prevents the trigger button tooltip from being seen when the menu is open.
180    pub fn trigger_with_tooltip<T: PopoverTrigger + ButtonCommon>(
181        mut self,
182        t: T,
183        tooltip_builder: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
184    ) -> Self {
185        let on_open = self.on_open.clone();
186        self.child_builder = Some(Box::new(move |menu, builder| {
187            let open = menu.borrow().is_some();
188            t.toggle_state(open)
189                .when_some(builder, |el, builder| {
190                    el.on_click(move |_, window, cx| {
191                        show_menu(&builder, &menu, on_open.clone(), window, cx)
192                    })
193                    .when(!open, |t| {
194                        t.tooltip(move |window, cx| tooltip_builder(window, cx))
195                    })
196                })
197                .into_any_element()
198        }));
199        self
200    }
201
202    /// Defines which corner of the menu to anchor to the attachment point.
203    /// By default, it uses the cursor position. Also see the `attach` method.
204    pub fn anchor(mut self, anchor: Corner) -> Self {
205        self.anchor = anchor;
206        self
207    }
208
209    /// Defines which corner of the handle to attach the menu's anchor to.
210    pub fn attach(mut self, attach: Corner) -> Self {
211        self.attach = Some(attach);
212        self
213    }
214
215    /// Offsets the position of the content by that many pixels.
216    pub fn offset(mut self, offset: Point<Pixels>) -> Self {
217        self.offset = Some(offset);
218        self
219    }
220
221    /// Attaches something upon opening the menu.
222    pub fn on_open(mut self, on_open: Rc<dyn Fn(&mut Window, &mut App)>) -> Self {
223        self.on_open = Some(on_open);
224        self
225    }
226
227    fn resolved_attach(&self) -> Corner {
228        self.attach.unwrap_or(match self.anchor {
229            Corner::TopLeft => Corner::BottomLeft,
230            Corner::TopRight => Corner::BottomRight,
231            Corner::BottomLeft => Corner::TopLeft,
232            Corner::BottomRight => Corner::TopRight,
233        })
234    }
235
236    fn resolved_offset(&self, window: &mut Window) -> Point<Pixels> {
237        self.offset.unwrap_or_else(|| {
238            // Default offset = 4px padding + 1px border
239            let offset = rems_from_px(5.) * window.rem_size();
240            match self.anchor {
241                Corner::TopRight | Corner::BottomRight => point(offset, px(0.)),
242                Corner::TopLeft | Corner::BottomLeft => point(-offset, px(0.)),
243            }
244        })
245    }
246}
247
248fn show_menu<M: ManagedView>(
249    builder: &Rc<dyn Fn(&mut Window, &mut App) -> Option<Entity<M>>>,
250    menu: &Rc<RefCell<Option<Entity<M>>>>,
251    on_open: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
252    window: &mut Window,
253    cx: &mut App,
254) {
255    let Some(new_menu) = (builder)(window, cx) else {
256        return;
257    };
258    let menu2 = menu.clone();
259    let previous_focus_handle = window.focused(cx);
260
261    window
262        .subscribe(&new_menu, cx, move |modal, _: &DismissEvent, window, cx| {
263            if modal.focus_handle(cx).contains_focused(window, cx) {
264                if let Some(previous_focus_handle) = previous_focus_handle.as_ref() {
265                    window.focus(previous_focus_handle);
266                }
267            }
268            *menu2.borrow_mut() = None;
269            window.refresh();
270        })
271        .detach();
272    window.focus(&new_menu.focus_handle(cx));
273    *menu.borrow_mut() = Some(new_menu);
274    window.refresh();
275
276    if let Some(on_open) = on_open {
277        on_open(window, cx);
278    }
279}
280
281pub struct PopoverMenuElementState<M> {
282    menu: Rc<RefCell<Option<Entity<M>>>>,
283    child_bounds: Option<Bounds<Pixels>>,
284}
285
286impl<M> Clone for PopoverMenuElementState<M> {
287    fn clone(&self) -> Self {
288        Self {
289            menu: Rc::clone(&self.menu),
290            child_bounds: self.child_bounds,
291        }
292    }
293}
294
295impl<M> Default for PopoverMenuElementState<M> {
296    fn default() -> Self {
297        Self {
298            menu: Rc::default(),
299            child_bounds: None,
300        }
301    }
302}
303
304pub struct PopoverMenuFrameState<M: ManagedView> {
305    child_layout_id: Option<LayoutId>,
306    child_element: Option<AnyElement>,
307    menu_element: Option<AnyElement>,
308    menu_handle: Rc<RefCell<Option<Entity<M>>>>,
309}
310
311impl<M: ManagedView> Element for PopoverMenu<M> {
312    type RequestLayoutState = PopoverMenuFrameState<M>;
313    type PrepaintState = Option<HitboxId>;
314
315    fn id(&self) -> Option<ElementId> {
316        Some(self.id.clone())
317    }
318
319    fn request_layout(
320        &mut self,
321        global_id: Option<&GlobalElementId>,
322        window: &mut Window,
323        cx: &mut App,
324    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
325        window.with_element_state(
326            global_id.unwrap(),
327            |element_state: Option<PopoverMenuElementState<M>>, window| {
328                let element_state = element_state.unwrap_or_default();
329                let mut menu_layout_id = None;
330
331                let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
332                    let offset = self.resolved_offset(window);
333                    let mut anchored = anchored()
334                        .snap_to_window_with_margin(px(8.))
335                        .anchor(self.anchor)
336                        .offset(offset);
337                    if let Some(child_bounds) = element_state.child_bounds {
338                        anchored =
339                            anchored.position(child_bounds.corner(self.resolved_attach()) + offset);
340                    }
341                    let mut element = deferred(anchored.child(div().occlude().child(menu.clone())))
342                        .with_priority(1)
343                        .into_any();
344
345                    menu_layout_id = Some(element.request_layout(window, cx));
346                    element
347                });
348
349                let mut child_element = self.child_builder.take().map(|child_builder| {
350                    (child_builder)(element_state.menu.clone(), self.menu_builder.clone())
351                });
352
353                if let Some(trigger_handle) = self.trigger_handle.take() {
354                    if let Some(menu_builder) = self.menu_builder.clone() {
355                        *trigger_handle.0.borrow_mut() = Some(PopoverMenuHandleState {
356                            menu_builder,
357                            menu: element_state.menu.clone(),
358                            on_open: self.on_open.clone(),
359                        });
360                    }
361                }
362
363                let child_layout_id = child_element
364                    .as_mut()
365                    .map(|child_element| child_element.request_layout(window, cx));
366
367                let mut style = Style::default();
368                if self.full_width {
369                    style.size = size(relative(1.).into(), Length::Auto);
370                }
371
372                let layout_id = window.request_layout(
373                    style,
374                    menu_layout_id.into_iter().chain(child_layout_id),
375                    cx,
376                );
377
378                (
379                    (
380                        layout_id,
381                        PopoverMenuFrameState {
382                            child_element,
383                            child_layout_id,
384                            menu_element,
385                            menu_handle: element_state.menu.clone(),
386                        },
387                    ),
388                    element_state,
389                )
390            },
391        )
392    }
393
394    fn prepaint(
395        &mut self,
396        global_id: Option<&GlobalElementId>,
397        _bounds: Bounds<Pixels>,
398        request_layout: &mut Self::RequestLayoutState,
399        window: &mut Window,
400        cx: &mut App,
401    ) -> Option<HitboxId> {
402        if let Some(child) = request_layout.child_element.as_mut() {
403            child.prepaint(window, cx);
404        }
405
406        if let Some(menu) = request_layout.menu_element.as_mut() {
407            menu.prepaint(window, cx);
408        }
409
410        request_layout.child_layout_id.map(|layout_id| {
411            let bounds = window.layout_bounds(layout_id);
412            window.with_element_state(global_id.unwrap(), |element_state, _cx| {
413                let mut element_state: PopoverMenuElementState<M> = element_state.unwrap();
414                element_state.child_bounds = Some(bounds);
415                ((), element_state)
416            });
417
418            window.insert_hitbox(bounds, false).id
419        })
420    }
421
422    fn paint(
423        &mut self,
424        _id: Option<&GlobalElementId>,
425        _: Bounds<gpui::Pixels>,
426        request_layout: &mut Self::RequestLayoutState,
427        child_hitbox: &mut Option<HitboxId>,
428        window: &mut Window,
429        cx: &mut App,
430    ) {
431        if let Some(mut child) = request_layout.child_element.take() {
432            child.paint(window, cx);
433        }
434
435        if let Some(mut menu) = request_layout.menu_element.take() {
436            menu.paint(window, cx);
437
438            if let Some(child_hitbox) = *child_hitbox {
439                let menu_handle = request_layout.menu_handle.clone();
440                // Mouse-downing outside the menu dismisses it, so we don't
441                // want a click on the toggle to re-open it.
442                window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
443                    if phase == DispatchPhase::Bubble && child_hitbox.is_hovered(window) {
444                        if let Some(menu) = menu_handle.borrow().as_ref() {
445                            menu.update(cx, |_, cx| {
446                                cx.emit(DismissEvent);
447                            });
448                        }
449                        cx.stop_propagation();
450                    }
451                })
452            }
453        }
454    }
455}
456
457impl<M: ManagedView> IntoElement for PopoverMenu<M> {
458    type Element = Self;
459
460    fn into_element(self) -> Self::Element {
461        self
462    }
463}