Skip to main content

gpui_deck/
popup.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    Anchor, AnyElement, App, Bounds, Div, ElementId, InteractiveElement, Interactivity,
5    IntoElement, ParentElement, Pixels, Point, RenderOnce, StatefulInteractiveElement,
6    StyleRefinement, Styled, Window, canvas, deferred, div, point, px,
7};
8
9use crate::{Align, Direction, Placement, Positioner, ResolvedPosition, StyledExt as _};
10
11/// Distance kept between a popup and the window edge.
12const WINDOW_MARGIN: Pixels = px(8.);
13
14/// Deferred paint priority for interactive surfaces that must appear above dialogs.
15pub const POPUP_PRIORITY: usize = 100;
16
17#[derive(Default)]
18struct PopupAnchorState {
19    bounds: Bounds<Pixels>,
20    captured: bool,
21}
22
23/// An unstyled trigger and anchored popup host.
24///
25/// `Popup` owns trigger measurement, anchor-point calculation, first-frame
26/// synchronization, deferred rendering, and window-edge snapping. Callers own
27/// open state, interaction, popup content, appearance, and motion.
28#[derive(IntoElement)]
29pub struct Popup {
30    id: ElementId,
31    base: gpui::Stateful<Div>,
32    style: StyleRefinement,
33    anchor: Anchor,
34    side: Option<Placement>,
35    align: Align,
36    offset: Pixels,
37    position: Option<Point<Pixels>>,
38    on_position: Option<Box<dyn Fn(ResolvedPosition, Bounds<Pixels>)>>,
39    trigger: AnyElement,
40    content: Option<AnyElement>,
41}
42
43impl Popup {
44    pub(crate) fn available_height(window: &Window) -> Pixels {
45        let margin = crate::positioner::window_margins(window, WINDOW_MARGIN);
46        (window.viewport_size().height - margin.top - margin.bottom).max(px(0.))
47    }
48
49    pub fn new(id: impl Into<ElementId>, trigger: impl IntoElement) -> Self {
50        let id = id.into();
51        Self {
52            base: div().id(id.clone()),
53            id,
54            style: StyleRefinement::default(),
55            anchor: Anchor::TopLeft,
56            side: None,
57            align: Align::Center,
58            offset: px(0.),
59            position: None,
60            on_position: None,
61            trigger: trigger.into_any_element(),
62            content: None,
63        }
64    }
65
66    /// Places a popup corner at the opposite trigger edge, without side flipping.
67    pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
68        self.anchor = anchor.into();
69        self.side = None;
70        self
71    }
72
73    /// Places the popup on this side, flipping to the opposite side when needed.
74    /// Alignment defaults to center; this replaces corner or explicit point positioning.
75    pub fn side(mut self, side: Placement) -> Self {
76        self.side = Some(side);
77        self.position = None;
78        self
79    }
80
81    /// Aligns the popup along its side. Without an explicit side, selects Bottom.
82    /// Start and End follow the inherited direction for Top and Bottom placement.
83    pub fn align(mut self, align: Align) -> Self {
84        self.align = align;
85        self.side.get_or_insert(Placement::Bottom);
86        self.position = None;
87        self
88    }
89
90    /// Gap from the trigger along the selected side or corner's outward direction.
91    /// Zero by default.
92    pub fn offset(mut self, offset: Pixels) -> Self {
93        self.offset = offset;
94        self
95    }
96
97    // Context menus use the request's window coordinate while keeping the
98    // same trigger measurement, clipping, and viewport clamping machinery.
99    pub(crate) fn at_position(mut self, position: Point<Pixels>) -> Self {
100        self.position = Some(position);
101        self.side = None;
102        self
103    }
104
105    /// Observe resolved popup and trigger bounds before content prepaint.
106    pub fn on_position(
107        mut self,
108        callback: impl Fn(ResolvedPosition, Bounds<Pixels>) + 'static,
109    ) -> Self {
110        self.on_position = Some(Box::new(callback));
111        self
112    }
113
114    pub fn content(mut self, content: impl IntoElement) -> Self {
115        self.content = Some(content.into_any_element());
116        self
117    }
118}
119
120/// Match the popup's anchor to the opposite edge of the measured trigger.
121fn anchor_position(anchor: Anchor, trigger: Bounds<Pixels>, offset: Pixels) -> Point<Pixels> {
122    match anchor {
123        Anchor::TopLeft => trigger.bottom_left() + point(px(0.), offset),
124        Anchor::TopCenter => trigger.bottom_center() + point(px(0.), offset),
125        Anchor::TopRight => trigger.bottom_right() + point(px(0.), offset),
126        Anchor::BottomLeft => trigger.origin - point(px(0.), offset),
127        Anchor::BottomCenter => trigger.top_center() - point(px(0.), offset),
128        Anchor::BottomRight => trigger.top_right() - point(px(0.), offset),
129        Anchor::LeftCenter => trigger.right_center() + point(offset, px(0.)),
130        Anchor::RightCenter => trigger.left_center() - point(offset, px(0.)),
131    }
132}
133
134impl Styled for Popup {
135    fn style(&mut self) -> &mut StyleRefinement {
136        &mut self.style
137    }
138}
139
140impl InteractiveElement for Popup {
141    fn interactivity(&mut self) -> &mut Interactivity {
142        self.base.interactivity()
143    }
144}
145
146impl StatefulInteractiveElement for Popup {}
147
148impl RenderOnce for Popup {
149    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
150        let state =
151            window.use_keyed_state((self.id, "anchor"), cx, |_, _| PopupAnchorState::default());
152        let anchor = self.anchor;
153        let trigger_bounds = Rc::new(Cell::new(state.read(cx).bounds));
154        let offset = self.offset;
155        let requested_position = self.position;
156        let position =
157            Rc::new(Cell::new(requested_position.unwrap_or_else(|| {
158                anchor_position(anchor, state.read(cx).bounds, offset)
159            })));
160
161        // A closed popup places nothing: it notes its trigger's bounds, for when
162        // it opens, without asking for another frame.
163        let has_content = self.content.is_some();
164        let root = self
165            .base
166            .child(self.trigger)
167            .child(
168                canvas(
169                    {
170                        let state = state.clone();
171                        let position = position.clone();
172                        let trigger_bounds = trigger_bounds.clone();
173                        move |bounds, window, cx| {
174                            trigger_bounds.set(bounds);
175                            position.set(
176                                requested_position
177                                    .unwrap_or_else(|| anchor_position(anchor, bounds, offset)),
178                            );
179                            let first = state.update(cx, |state, _| {
180                                let first = !state.captured;
181                                state.bounds = bounds;
182                                state.captured = true;
183                                first
184                            });
185                            if first && has_content {
186                                window.request_animation_frame();
187                            }
188                        }
189                    },
190                    |_, _, _, _| {},
191                )
192                .absolute()
193                .size_full()
194                .top_0()
195                .left_0(),
196            )
197            .refine_style(&self.style);
198
199        let Some(content) = self.content else {
200            return root;
201        };
202        if !state.read(cx).captured {
203            return root;
204        }
205
206        let positioner = if let Some(side) = self.side {
207            let align = if side.is_vertical() && Direction::current(cx).is_rtl() {
208                match self.align {
209                    Align::Start => Align::End,
210                    Align::End => Align::Start,
211                    Align::Center => Align::Center,
212                }
213            } else {
214                self.align
215            };
216            Positioner::side(trigger_bounds.get())
217                .placement(side)
218                .align(align)
219                .offset(offset)
220                .tracked_trigger_bounds(trigger_bounds.clone())
221        } else {
222            Positioner::corner(anchor, position.get()).tracked_corner_position(position)
223        };
224        let positioner = if let Some(callback) = self.on_position {
225            positioner.on_position(move |position| callback(position, trigger_bounds.get()))
226        } else {
227            positioner
228        };
229        root.child(
230            deferred(
231                positioner
232                    .margin(WINDOW_MARGIN)
233                    // The host blocks the mouse, so no caller has to remember:
234                    // what a popup covers belongs to the popup.
235                    .occlude()
236                    .child(content),
237            )
238            .with_priority(POPUP_PRIORITY),
239        )
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use gpui::{Context, Render, px};
247
248    struct Harness;
249
250    impl Render for Harness {
251        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
252            Popup::new(
253                "popup",
254                div()
255                    .debug_selector(|| "popup-trigger".into())
256                    .size(px(100.)),
257            )
258            .content(
259                div()
260                    .debug_selector(|| "popup-content".into())
261                    .size(px(20.)),
262            )
263        }
264    }
265
266    /// A caller that styles its own surface — a hover card, a dropdown — does
267    /// not have to remember to block the mouse. The host does it, so the panel
268    /// a popup covers stops reacting to a pointer that is over the popup.
269    struct OcclusionHarness {
270        background_hovered: Rc<Cell<bool>>,
271        content_hovered: Rc<Cell<bool>>,
272        resolved: Rc<Cell<Option<ResolvedPosition>>>,
273    }
274
275    impl Render for OcclusionHarness {
276        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
277            let background = self.background_hovered.clone();
278            let content = self.content_hovered.clone();
279            let resolved = self.resolved.clone();
280            div()
281                .relative()
282                .size(px(200.))
283                .child(
284                    div()
285                        .id("background")
286                        .absolute()
287                        .size_full()
288                        .on_mouse_move(move |_, _, _| background.set(true)),
289                )
290                .child(
291                    Popup::new("popup", div().size(px(100.)))
292                        .offset(px(0.25))
293                        .on_position(move |position, _| resolved.set(Some(position)))
294                        .content(
295                            div()
296                                .id("content")
297                                .debug_selector(|| "surface".into())
298                                .m(px(8.5))
299                                .size(px(40.))
300                                .on_mouse_move(move |_, _, _| content.set(true)),
301                        ),
302                )
303        }
304    }
305
306    #[gpui::test]
307    fn the_popup_surface_blocks_the_panel_it_covers(cx: &mut gpui::TestAppContext) {
308        let background_hovered = Rc::new(Cell::new(false));
309        let content_hovered = Rc::new(Cell::new(false));
310        let resolved = Rc::new(Cell::new(None));
311        let (_, window) = cx.add_window_view({
312            let background_hovered = background_hovered.clone();
313            let content_hovered = content_hovered.clone();
314            let resolved = resolved.clone();
315            move |_, _| OcclusionHarness {
316                background_hovered,
317                content_hovered,
318                resolved,
319            }
320        });
321        window.update(|window, cx| window.draw(cx).clear(cx));
322        window.update(|window, cx| window.draw(cx).clear(cx));
323        assert_eq!(
324            resolved.get().unwrap().bounds,
325            window.debug_bounds("surface").unwrap(),
326            "reported and occluding bounds must match the painted surface"
327        );
328
329        window.simulate_mouse_move(
330            gpui::point(px(20.), px(110.)),
331            None,
332            gpui::Modifiers::default(),
333        );
334        assert!(!background_hovered.get());
335        // The surface blocks what is behind it, not its own content: the
336        // hitbox goes in ahead of the children, never over them.
337        assert!(content_hovered.get());
338
339        // The same pointer outside the surface still reaches the panel, so the
340        // assertion above is about occlusion and not a dead listener.
341        window.simulate_mouse_move(
342            gpui::point(px(150.), px(180.)),
343            None,
344            gpui::Modifiers::default(),
345        );
346        assert!(background_hovered.get());
347    }
348
349    /// A popup that may open later.
350    struct ClosedHarness {
351        open: bool,
352    }
353
354    impl Render for ClosedHarness {
355        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
356            let popup = Popup::new(
357                "popup",
358                div()
359                    .debug_selector(|| "popup-trigger".into())
360                    .size(px(100.)),
361            );
362            if self.open {
363                popup.content(
364                    div()
365                        .debug_selector(|| "popup-content".into())
366                        .size(px(20.)),
367                )
368            } else {
369                popup
370            }
371        }
372    }
373
374    /// A closed popup notes its trigger's bounds without asking for another
375    /// frame: a list of rows holding closed popups is not drawn again for
376    /// each row that shows. Opened, it places its content at once.
377    #[gpui::test]
378    fn a_closed_popup_asks_for_no_frame_and_opens_at_once(cx: &mut gpui::TestAppContext) {
379        let (view, window) = cx.add_window_view(|_, _| ClosedHarness { open: false });
380        window.update(|window, cx| {
381            window.draw(cx).clear(cx);
382            assert_eq!(window.simulate_next_frame(cx), 0, "no frame was asked for");
383        });
384
385        view.update(window, |harness, cx| {
386            harness.open = true;
387            cx.notify();
388        });
389        window.update(|window, cx| window.draw(cx).clear(cx));
390        assert_eq!(
391            window.debug_bounds("popup-content").unwrap().size,
392            gpui::Size::new(px(20.), px(20.))
393        );
394    }
395
396    #[gpui::test]
397    fn trigger_capture_enables_deferred_content_on_the_next_frame(cx: &mut gpui::TestAppContext) {
398        let (_, window) = cx.add_window_view(|_, _| Harness);
399        window.update(|window, cx| window.draw(cx).clear(cx));
400        window.update(|window, cx| window.draw(cx).clear(cx));
401
402        assert_eq!(
403            window.debug_bounds("popup-trigger").unwrap().size,
404            gpui::Size::new(px(100.), px(100.))
405        );
406        assert_eq!(
407            window.debug_bounds("popup-content").unwrap().size,
408            gpui::Size::new(px(20.), px(20.))
409        );
410    }
411
412    struct SideHarness {
413        trigger: Bounds<Pixels>,
414        side: Placement,
415        align: Align,
416        direction: Direction,
417        resolved: Rc<Cell<Option<(ResolvedPosition, Bounds<Pixels>)>>>,
418    }
419
420    impl Render for SideHarness {
421        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
422            let resolved = self.resolved.clone();
423            crate::DirectionProvider::new(self.direction)
424                .size_full()
425                .child(
426                    Popup::new(
427                        "side-popup",
428                        div().w(self.trigger.size.width).h(self.trigger.size.height),
429                    )
430                    .absolute()
431                    .left(self.trigger.origin.x)
432                    .top(self.trigger.origin.y)
433                    .side(self.side)
434                    .align(self.align)
435                    .offset(px(8.))
436                    .on_position(move |position, trigger| {
437                        resolved.set(Some((position, trigger)));
438                    })
439                    .content(
440                        div()
441                            .debug_selector(|| "side-content".into())
442                            .w(px(60.))
443                            .h(px(30.)),
444                    ),
445                )
446        }
447    }
448
449    #[gpui::test]
450    fn side_placement_tracks_current_bounds_alignment_direction_and_collisions(
451        cx: &mut gpui::TestAppContext,
452    ) {
453        let resolved = Rc::new(Cell::new(None));
454        let (view, window) = cx.add_window_view({
455            let resolved = resolved.clone();
456            move |_, _| SideHarness {
457                trigger: Bounds::new(point(px(120.), px(100.)), gpui::size(px(100.), px(40.))),
458                side: Placement::Bottom,
459                align: Align::End,
460                direction: Direction::Ltr,
461                resolved,
462            }
463        });
464        window.update(|window, cx| window.draw(cx).clear(cx));
465        window.update(|window, cx| window.draw(cx).clear(cx));
466        let (position, trigger) = resolved.get().unwrap();
467        assert_eq!(position.placement, Some(Placement::Bottom));
468        assert_eq!(position.bounds.right(), trigger.right());
469        assert_eq!(position.bounds.top(), trigger.bottom() + px(8.));
470
471        view.update(window, |harness, cx| {
472            harness.trigger = Bounds::new(point(px(220.), px(170.)), gpui::size(px(100.), px(50.)));
473            harness.side = Placement::Right;
474            cx.notify();
475        });
476        window.update(|window, cx| window.draw(cx).clear(cx));
477        let (position, trigger) = resolved.get().unwrap();
478        assert_eq!(trigger.origin, point(px(220.), px(170.)));
479        assert_eq!(position.placement, Some(Placement::Right));
480        assert_eq!(position.bounds.left(), trigger.right() + px(8.));
481        assert_eq!(position.bounds.bottom(), trigger.bottom());
482        assert_eq!(window.debug_bounds("side-content"), Some(position.bounds));
483
484        view.update(window, |harness, cx| {
485            harness.side = Placement::Bottom;
486            harness.direction = Direction::Rtl;
487            cx.notify();
488        });
489        window.update(|window, cx| window.draw(cx).clear(cx));
490        let (position, trigger) = resolved.get().unwrap();
491        assert_eq!(position.bounds.left(), trigger.left());
492
493        let viewport = window.update(|window, _| window.viewport_size());
494        view.update(window, |harness, cx| {
495            harness.direction = Direction::Ltr;
496            harness.align = Align::Start;
497            harness.trigger.origin = point(viewport.width - px(30.), viewport.height - px(50.));
498            cx.notify();
499        });
500        window.update(|window, cx| window.draw(cx).clear(cx));
501        let (position, trigger) = resolved.get().unwrap();
502        assert_eq!(position.placement, Some(Placement::Top));
503        assert_eq!(position.bounds.bottom(), trigger.top() - px(8.));
504        assert_eq!(position.bounds.right(), viewport.width - WINDOW_MARGIN);
505    }
506}