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