Skip to main content

gpui_component/
popover.rs

1use gpui::{
2    Anchor, Animation, AnimationExt as _, AnyElement, App, Bounds, Context, Div, ElementId,
3    FocusHandle, InteractiveElement as _, IntoElement, MouseButton, ParentElement, PathBuilder,
4    Pixels, Point, RenderOnce, Stateful, StyleRefinement, Styled, Window, canvas, point,
5    prelude::FluentBuilder as _, px,
6};
7use std::{cell::Cell, rc::Rc, time::Duration};
8
9use crate::{ActiveTheme as _, ThemeStyled as _};
10use crate::{
11    Selectable, StyledExt as _,
12    animation::ease_out_cubic,
13    styled::{popover_ring, popover_shadow},
14    v_flex,
15};
16use gpui_base::Placement;
17use gpui_base::Popover as BasePopover;
18pub use gpui_base::PopoverState;
19
20pub(crate) fn init(_: &mut App) {}
21
22/// How long a dropdown takes to settle into place after it opens.
23///
24/// This is shadcn/ui's figure: its popup surfaces carry `animate-in`, whose
25/// duration is 150ms.
26const DROPDOWN_ENTER_DURATION: Duration = Duration::from_millis(150);
27
28/// Where a dropdown starts out, relative to where it comes to rest.
29///
30/// Negative is above, so the surface slides *down* out of the trigger's edge —
31/// what shadcn/ui expresses as `data-[side=bottom]:slide-in-from-top-2`. Its
32/// `2` is `0.5rem`, which is 8px at the default root size.
33const DROPDOWN_ENTER_OFFSET: Pixels = px(-8.);
34
35fn dropdown_positioner(bounds: Bounds<Pixels>) -> gpui_base::Positioner {
36    gpui_base::Positioner::side(bounds)
37        .placement(gpui_base::Placement::Bottom)
38        .align(gpui_base::Align::Start)
39        .offset(px(6.))
40        .margin(px(8.))
41}
42
43/// Positions a dropdown surface under its trigger and animates it in.
44///
45/// This is the shared open motion for Select, Combobox and DatePicker, modelled
46/// on shadcn/ui: over 150ms the surface fades up from nothing while sliding the
47/// last 8px out of the trigger's edge, on an ease-out curve so it decelerates
48/// into place.
49///
50/// `surface` must be the panel itself — the element carrying
51/// [`ThemeStyled::popover_style`] — and not a wrapper around it. GPUI takes a
52/// shadow's shape from the element it is set on, so a wrapper of a different
53/// size would throw the shadow out of register with the panel.
54///
55/// # Why the shadow is animated too
56///
57/// GPUI has no group compositing: `opacity` multiplies into each primitive's
58/// alpha separately rather than fading a composited subtree. A drop shadow is
59/// painted as a full blurred rect *under* the element — the shader only cuts the
60/// element out of `inset` shadows — so a translucent panel does not hide its own
61/// shadow, and mid-fade the shadow shows straight through the panel as a dark
62/// slab. Ramping the ink by the cube of the fade keeps it out of sight until the
63/// panel is opaque enough to cover it, and still lands on the resting shadow
64/// [`popover_shadow`] gives every other popup.
65///
66/// # Departures from shadcn
67///
68/// - shadcn also scales the surface up from 95% (`zoom-in-95`). GPUI has no
69///   element transform — only images and SVGs take a `TransformationMatrix` —
70///   so there is nothing to scale a subtree with, and the fade and slide carry
71///   the motion on their own.
72/// - There is no exit motion. A closing dropdown stops being rendered in the
73///   same frame its state flips, so playing one would mean keeping the surface
74///   mounted past the close, which is a change to how each of these components
75///   tracks `open`.
76/// - The slide always comes from above. [`gpui_base::Positioner`] resolves the
77///   side the surface actually lands on during layout and does not report it
78///   back, so a dropdown that flips above its trigger for want of room below
79///   slides the opposite way — 8px over 150ms, in the rare case where it
80///   happens.
81///
82/// Reduced motion needs no handling here: GPUI's animation element adopts the
83/// final value on the first frame when the system asks for it.
84pub(crate) fn dropdown_popup(
85    id: impl Into<ElementId>,
86    bounds: Bounds<Pixels>,
87    surface: impl IntoElement + Styled + 'static,
88    cx: &App,
89) -> gpui_base::Positioner {
90    let travel: f32 = DROPDOWN_ENTER_OFFSET.into();
91    // Read out here: the animation runs long after `cx` is gone.
92    let ring = popover_ring(cx);
93
94    dropdown_positioner(bounds).child(surface.with_animation(
95        id,
96        Animation::new(DROPDOWN_ENTER_DURATION).with_easing(ease_out_cubic),
97        move |surface, delta| {
98            surface
99                .top(px(travel * (1. - delta)))
100                .opacity(delta)
101                .shadow(popover_shadow(ring, delta * delta * delta))
102        },
103    ))
104}
105
106/// A popover element that can be triggered by a button or any other element.
107#[derive(IntoElement)]
108pub struct Popover {
109    id: ElementId,
110    style: StyleRefinement,
111    anchor: Anchor,
112    offset: Option<Pixels>,
113    arrow: bool,
114    default_open: bool,
115    open: Option<bool>,
116    tracked_focus_handle: Option<FocusHandle>,
117    trigger: Option<Box<dyn FnOnce(bool, &Window, &App) -> AnyElement + 'static>>,
118    content: Option<
119        Rc<
120            dyn Fn(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> AnyElement
121                + 'static,
122        >,
123    >,
124    children: Vec<AnyElement>,
125    /// Style for the trigger container, the element laid out in the parent
126    /// and measured to anchor the popup.
127    trigger_style: Option<StyleRefinement>,
128    mouse_button: MouseButton,
129    appearance: bool,
130    overlay_closable: bool,
131    on_open_change: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
132}
133
134impl Popover {
135    /// Create a new Popover with `view` mode.
136    pub fn new(id: impl Into<ElementId>) -> Self {
137        Self {
138            id: id.into(),
139            style: StyleRefinement::default(),
140            anchor: Anchor::TopLeft,
141            offset: None,
142            arrow: false,
143            trigger: None,
144            trigger_style: None,
145            content: None,
146            tracked_focus_handle: None,
147            children: vec![],
148            mouse_button: MouseButton::Left,
149            appearance: true,
150            overlay_closable: true,
151            default_open: false,
152            open: None,
153            on_open_change: None,
154        }
155    }
156
157    /// Set the anchor corner of the popover, default is [`Anchor::TopLeft`].
158    ///
159    /// This names the popover's own anchor, not a corner of the trigger.
160    /// `TopLeft` opens below the trigger, left-aligned; `BottomRight` opens
161    /// above it, right-aligned. Legacy anchoring clamps without flipping.
162    pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
163        self.anchor = anchor.into();
164        self
165    }
166
167    /// Gap from the trigger to the surface (or arrow tip), default 0.25rem.
168    /// Preserves the anchor and does not enable automatic flipping.
169    pub fn offset(mut self, offset: impl Into<Pixels>) -> Self {
170        self.offset = Some(offset.into());
171        self
172    }
173
174    /// Show an arrow pointing toward the trigger. Default is `false`.
175    /// Follows the anchor, with its base inset to avoid rounded corners.
176    /// Uses the surface background, falling back to the theme's popover color.
177    pub fn arrow(mut self, arrow: bool) -> Self {
178        self.arrow = arrow;
179        self
180    }
181
182    /// Set the mouse button to trigger the popover, default is `MouseButton::Left`.
183    pub fn mouse_button(mut self, mouse_button: MouseButton) -> Self {
184        self.mouse_button = mouse_button;
185        self
186    }
187
188    /// Set the trigger element of the popover.
189    pub fn trigger<T>(mut self, trigger: T) -> Self
190    where
191        T: Selectable + IntoElement + 'static,
192    {
193        self.trigger = Some(Box::new(|is_open, _, _| {
194            let open = trigger.is_open();
195            trigger.open(open || is_open).into_any_element()
196        }));
197        self
198    }
199
200    /// Set the default open state of the popover, default is `false`.
201    ///
202    /// This is only used to initialize the open state of the popover.
203    ///
204    /// And please note that if you use the `open` method, this value will be ignored.
205    pub fn default_open(mut self, open: bool) -> Self {
206        self.default_open = open;
207        self
208    }
209
210    /// Force set the open state of the popover.
211    ///
212    /// If this is set, the popover will be controlled by this value.
213    ///
214    /// NOTE: You must be used in conjunction with `on_open_change` to handle state changes.
215    pub fn open(mut self, open: bool) -> Self {
216        self.open = Some(open);
217        self
218    }
219
220    /// Add a callback to be called when the open state changes.
221    ///
222    /// The first `&bool` parameter is the **new open state**.
223    ///
224    /// This is useful when using the `open` method to control the popover state.
225    pub fn on_open_change<F>(mut self, callback: F) -> Self
226    where
227        F: Fn(&bool, &mut Window, &mut App) + 'static,
228    {
229        self.on_open_change = Some(Rc::new(callback));
230        self
231    }
232
233    /// Set the style for the trigger container.
234    ///
235    /// The container is the element laid out in the parent and measured to
236    /// anchor the popup, so this is where `w_full` or `flex_1` must go for the
237    /// trigger to fill its slot.
238    pub fn trigger_style(mut self, style: StyleRefinement) -> Self {
239        self.trigger_style = Some(style);
240        self
241    }
242
243    /// Set whether clicking outside the popover will dismiss it, default is `true`.
244    pub fn overlay_closable(mut self, closable: bool) -> Self {
245        self.overlay_closable = closable;
246        self
247    }
248
249    /// Set the content builder for content of the Popover.
250    ///
251    /// This callback will called every time on render the popover.
252    /// So, you should avoid creating new elements or entities in the content closure.
253    pub fn content<F, E>(mut self, content: F) -> Self
254    where
255        E: IntoElement,
256        F: Fn(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> E + 'static,
257    {
258        self.content = Some(Rc::new(move |state, window, cx| {
259            content(state, window, cx).into_any_element()
260        }));
261        self
262    }
263
264    /// Set whether the popover no style, default is `false`.
265    ///
266    /// If no style:
267    ///
268    /// - The popover will not have a bg, border, shadow, or padding.
269    /// - The click out of the popover will not dismiss it.
270    pub fn appearance(mut self, appearance: bool) -> Self {
271        self.appearance = appearance;
272        self
273    }
274
275    /// Bind the focus handle to receive focus when the popover is opened.
276    /// If you not set this, a new focus handle will be created for the popover to
277    ///
278    /// If popover is opened, the focus will be moved to the focus handle.
279    pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
280        self.tracked_focus_handle = Some(handle.clone());
281        self
282    }
283}
284
285impl ParentElement for Popover {
286    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
287        self.children.extend(elements);
288    }
289}
290
291impl Styled for Popover {
292    fn style(&mut self) -> &mut StyleRefinement {
293        &mut self.style
294    }
295}
296
297impl Popover {
298    pub(crate) fn render_popover_content(
299        anchor: Anchor,
300        appearance: bool,
301        _: &mut Window,
302        cx: &mut App,
303    ) -> Stateful<Div> {
304        v_flex()
305            .id("content")
306            .occlude()
307            .tab_group()
308            .when(appearance, |this| this.popover_style(cx).p_3())
309            .map(|this| match anchor {
310                Anchor::TopLeft | Anchor::TopCenter | Anchor::TopRight => this.top_1(),
311                Anchor::BottomLeft | Anchor::BottomCenter | Anchor::BottomRight => this.bottom_1(),
312                Anchor::LeftCenter | Anchor::RightCenter => this.top_1(), // Fallback for centered
313            })
314    }
315}
316
317impl RenderOnce for Popover {
318    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
319        // The arrow points at the physical corner the popup resolved to.
320        let anchor = gpui_base::logical_anchor(self.anchor, gpui_base::LayoutDirection::global(cx));
321        let arrow_size = if self.arrow {
322            window.rem_size() * 0.375
323        } else {
324            px(0.)
325        };
326        let offset = self.offset.unwrap_or(window.rem_size() * 0.25) + arrow_size;
327        let resolved = Rc::new(Cell::new(None));
328        let arrow_position = resolved.clone();
329        let arrow = self.arrow;
330        let background = self
331            .style
332            .background
333            .as_ref()
334            .and_then(gpui::Fill::color)
335            .unwrap_or_else(|| cx.theme().popover.into());
336        let ring = popover_ring(cx);
337        let radius = cx.theme().radius;
338        let appearance = self.appearance;
339        let style = self.style;
340        let children = self.children;
341        let content = self.content;
342        let trigger_style = self.trigger_style;
343
344        BasePopover::new(self.id)
345            .anchor(self.anchor)
346            .offset(offset)
347            .on_position(move |position, trigger| resolved.set(Some((position, trigger))))
348            .mouse_button(self.mouse_button)
349            .default_open(self.default_open)
350            .overlay_closable(self.overlay_closable)
351            .content(move |state, window, cx| {
352                v_flex()
353                    .id("content")
354                    .occlude()
355                    .tab_group()
356                    .when(appearance, |this| this.popover_style(cx).p_3())
357                    .when_some(content, |this, content| {
358                        this.child((content)(state, window, cx))
359                    })
360                    .children(children)
361                    .refine_style(&style)
362                    .when(arrow, |this| {
363                        this.child(
364                            canvas(
365                                |_, _, _| {},
366                                move |bounds, _, window, _| {
367                                    let Some((_, trigger)) = arrow_position.get() else {
368                                        return;
369                                    };
370                                    let (side, target) = arrow_anchor(anchor, trigger);
371                                    let trigger = Bounds::new(target, gpui::size(px(0.), px(0.)));
372                                    let points =
373                                        arrow_points(bounds, trigger, side, arrow_size, radius);
374                                    let mut fill = PathBuilder::fill();
375                                    fill.move_to(points[0]);
376                                    fill.line_to(points[1]);
377                                    fill.line_to(points[2]);
378                                    fill.close();
379                                    if let Ok(path) = fill.build() {
380                                        window.paint_path(path, background);
381                                    }
382                                    // The triangle ends exactly at the surface edge.
383                                    // Cover the ring and the antialiased base on both
384                                    // sides of that edge before drawing its two slopes.
385                                    window.paint_quad(gpui::fill(
386                                        arrow_join_bounds(points, side, px(1.)),
387                                        background,
388                                    ));
389                                    if appearance {
390                                        let mut outline = PathBuilder::stroke(px(1.));
391                                        outline.move_to(points[0]);
392                                        outline.line_to(points[1]);
393                                        outline.line_to(points[2]);
394                                        if let Ok(path) = outline.build() {
395                                            window.paint_path(path, ring);
396                                        }
397                                    }
398                                },
399                            )
400                            .absolute()
401                            .inset_0()
402                            .size_full(),
403                        )
404                    })
405            })
406            .when_some(self.trigger, |this, trigger| this.trigger_with(trigger))
407            .when_some(trigger_style, |this, style| this.refine_style(&style))
408            .when_some(self.open, |this, open| this.open(open))
409            .when_some(self.tracked_focus_handle, |this, handle| {
410                this.track_focus(&handle)
411            })
412            .when_some(self.on_open_change, |this, callback| {
413                this.on_open_change(move |open, window, cx| callback(open, window, cx))
414            })
415            .into_any_element()
416    }
417}
418
419/// The arrow follows the named anchor instead of always aiming at trigger center.
420fn arrow_anchor(anchor: Anchor, trigger: Bounds<Pixels>) -> (Placement, Point<Pixels>) {
421    match anchor {
422        Anchor::TopLeft => (Placement::Bottom, trigger.bottom_left()),
423        Anchor::TopCenter => (Placement::Bottom, trigger.bottom_center()),
424        Anchor::TopRight => (Placement::Bottom, trigger.bottom_right()),
425        Anchor::BottomLeft => (Placement::Top, trigger.origin),
426        Anchor::BottomCenter => (Placement::Top, trigger.top_center()),
427        Anchor::BottomRight => (Placement::Top, trigger.top_right()),
428        Anchor::LeftCenter => (Placement::Right, trigger.right_center()),
429        Anchor::RightCenter => (Placement::Left, trigger.left_center()),
430    }
431}
432
433/// Clamp the arrow base clear of rounded corners while aiming at the trigger.
434fn arrow_points(
435    surface: Bounds<Pixels>,
436    trigger: Bounds<Pixels>,
437    side: Placement,
438    depth: Pixels,
439    radius: Pixels,
440) -> [Point<Pixels>; 3] {
441    let horizontal = side.is_horizontal();
442    let (start, end, target) = if horizontal {
443        (surface.top(), surface.bottom(), trigger.center().y)
444    } else {
445        (surface.left(), surface.right(), trigger.center().x)
446    };
447    let half = depth.min((end - start) * 0.5);
448    let inset = (radius + half).min((end - start) * 0.5);
449    let center = target.clamp(start + inset, end - inset);
450    match side {
451        Placement::Bottom => [
452            point(center - half, surface.top()),
453            point(center, surface.top() - depth),
454            point(center + half, surface.top()),
455        ],
456        Placement::Top => [
457            point(center - half, surface.bottom()),
458            point(center, surface.bottom() + depth),
459            point(center + half, surface.bottom()),
460        ],
461        Placement::Right => [
462            point(surface.left(), center - half),
463            point(surface.left() - depth, center),
464            point(surface.left(), center + half),
465        ],
466        Placement::Left => [
467            point(surface.right(), center - half),
468            point(surface.right() + depth, center),
469            point(surface.right(), center + half),
470        ],
471    }
472}
473
474fn arrow_join_bounds(
475    points: [Point<Pixels>; 3],
476    side: Placement,
477    stroke: Pixels,
478) -> Bounds<Pixels> {
479    // Inset by the stroke width so the patch remains inside the triangle's
480    // slopes at the outer edge of the ring, including on very small surfaces.
481    if side.is_horizontal() {
482        let inset = stroke.min((points[2].y - points[0].y) * 0.5);
483        Bounds::from_corners(
484            point(points[0].x - stroke, points[0].y + inset),
485            point(points[2].x + stroke, points[2].y - inset),
486        )
487    } else {
488        let inset = stroke.min((points[2].x - points[0].x) * 0.5);
489        Bounds::from_corners(
490            point(points[0].x + inset, points[0].y - stroke),
491            point(points[2].x - inset, points[2].y + stroke),
492        )
493    }
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499    use crate::{button::Button, h_flex, theme::Theme};
500    use gpui::{Bounds, Context, MouseButton, Point, Render, div, point, px, size};
501    use gpui_base::Popup as BasePopup;
502    use std::{cell::RefCell, rc::Rc};
503
504    #[test]
505    fn test_popover_builder_chaining() {
506        let popover = Popover::new("test")
507            .anchor(Anchor::BottomCenter)
508            .mouse_button(MouseButton::Right)
509            .default_open(true)
510            .appearance(false)
511            .overlay_closable(false);
512
513        assert_eq!(popover.anchor, Anchor::BottomCenter);
514        assert_eq!(popover.mouse_button, MouseButton::Right);
515        assert!(popover.default_open);
516        assert!(!popover.appearance);
517        assert!(!popover.overlay_closable);
518    }
519
520    #[test]
521    fn test_resolved_corner_top_positions() {
522        use gpui::px;
523
524        let bounds = Bounds {
525            origin: Point {
526                x: px(100.),
527                y: px(100.),
528            },
529            size: gpui::Size {
530                width: px(200.),
531                height: px(50.),
532            },
533        };
534
535        let pos = BasePopup::resolved_corner(Anchor::TopLeft, bounds);
536        assert_eq!(pos.x, px(100.));
537        assert_eq!(pos.y, px(100.));
538
539        let pos = BasePopup::resolved_corner(Anchor::TopCenter, bounds);
540        assert_eq!(pos.x, px(200.));
541        assert_eq!(pos.y, px(100.));
542
543        let pos = BasePopup::resolved_corner(Anchor::TopRight, bounds);
544        assert_eq!(pos.x, px(300.));
545        assert_eq!(pos.y, px(100.));
546
547        let pos = BasePopup::resolved_corner(Anchor::BottomLeft, bounds);
548        assert_eq!(pos.x, px(100.));
549        assert_eq!(pos.y, px(50.));
550
551        let pos = BasePopup::resolved_corner(Anchor::BottomCenter, bounds);
552        assert_eq!(pos.x, px(200.));
553        assert_eq!(pos.y, px(50.));
554
555        let pos = BasePopup::resolved_corner(Anchor::BottomRight, bounds);
556        assert_eq!(pos.x, px(300.));
557        assert_eq!(pos.y, px(50.));
558    }
559
560    struct PopoverHarness {
561        changes: Rc<RefCell<Vec<bool>>>,
562    }
563
564    struct AnchorHarness {
565        anchor: Anchor,
566        offset: Option<Pixels>,
567        origin: Point<Pixels>,
568        arrow: bool,
569    }
570
571    impl Render for AnchorHarness {
572        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
573            div().size_full().child(
574                div()
575                    .absolute()
576                    .left(self.origin.x)
577                    .top(self.origin.y)
578                    .child(
579                        Popover::new("positioned-popover")
580                            .default_open(true)
581                            .appearance(false)
582                            .arrow(self.arrow)
583                            .anchor(self.anchor)
584                            .when_some(self.offset, |this, gap| this.offset(gap))
585                            .trigger(Button::new("positioned-trigger").size(px(40.)))
586                            .child(
587                                div()
588                                    .debug_selector(|| "positioned-content".into())
589                                    .size(px(60.)),
590                            ),
591                    ),
592            )
593        }
594    }
595
596    #[gpui::test]
597    fn anchor_and_offset_position_the_surface_on_each_trigger_edge(cx: &mut gpui::TestAppContext) {
598        cx.update(crate::init);
599        let (view, window) = cx.add_window_view(|_, _| AnchorHarness {
600            anchor: Anchor::TopLeft,
601            offset: None,
602            origin: point(px(200.), px(200.)),
603            arrow: false,
604        });
605        window.update(|window, cx| crate::test_redraw(window, cx));
606        window.update(|window, cx| crate::test_redraw(window, cx));
607        // Legacy TopLeft means below the trigger, including the default 0.25rem gap.
608        let legacy = window.debug_bounds("positioned-content").unwrap();
609        assert_eq!(legacy.left(), px(200.));
610        assert_eq!(legacy.top(), px(244.));
611
612        for (side, x, y) in [
613            (Anchor::BottomLeft, 200., 128.),
614            (Anchor::BottomCenter, 190., 128.),
615            (Anchor::BottomRight, 180., 128.),
616            (Anchor::TopLeft, 200., 252.),
617            (Anchor::TopCenter, 190., 252.),
618            (Anchor::TopRight, 180., 252.),
619            (Anchor::RightCenter, 128., 190.),
620            (Anchor::LeftCenter, 252., 190.),
621        ] {
622            window.update(|window, cx| {
623                view.update(cx, |view, cx| {
624                    view.anchor = side;
625                    view.offset = Some(px(12.));
626                    cx.notify();
627                });
628                crate::test_redraw(window, cx);
629            });
630            assert_eq!(
631                window.debug_bounds("positioned-content").unwrap().origin,
632                point(px(x), px(y)),
633                "{side:?}"
634            );
635        }
636        // Current-frame trigger bounds must be used after the owner moves.
637        window.update(|window, cx| {
638            view.update(cx, |view, cx| {
639                view.origin = point(px(260.), px(240.));
640                cx.notify();
641            });
642            crate::test_redraw(window, cx);
643        });
644        assert_eq!(
645            window.debug_bounds("positioned-content").unwrap().origin,
646            point(px(312.), px(230.))
647        );
648    }
649
650    struct TriggerStyleHarness {
651        styled: bool,
652    }
653
654    impl Render for TriggerStyleHarness {
655        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
656            // Keep the trigger clear of the popup's window margin so the
657            // content origin reflects only the trigger container's bounds.
658            div().size_full().child(
659                h_flex()
660                    .absolute()
661                    .left(px(100.))
662                    .top(px(100.))
663                    .w(px(200.))
664                    .child(
665                        Popover::new("trigger-style-popover")
666                            .default_open(true)
667                            .appearance(false)
668                            .offset(px(0.))
669                            .anchor(Anchor::TopRight)
670                            .when(self.styled, |this| {
671                                this.trigger_style(StyleRefinement::default().w_full())
672                            })
673                            .trigger(Button::new("styled-trigger").size(px(40.)))
674                            .child(
675                                div()
676                                    .debug_selector(|| "styled-content".into())
677                                    .size(px(20.)),
678                            ),
679                    ),
680            )
681        }
682    }
683
684    /// `trigger_style` styles the container the parent lays out and the popup
685    /// is anchored to. Applied to anything nested inside it, `w_full` would
686    /// resolve against a container that only wraps its content.
687    #[gpui::test]
688    fn trigger_style_is_applied_to_the_trigger_container(cx: &mut gpui::TestAppContext) {
689        cx.update(crate::init);
690        let (view, window) = cx.add_window_view(|_, _| TriggerStyleHarness { styled: false });
691        window.update(|window, cx| crate::test_redraw(window, cx));
692        window.update(|window, cx| crate::test_redraw(window, cx));
693        // Unstyled: the container wraps the 40px trigger, so the content's right
694        // edge meets the trigger's right edge at 140px.
695        assert_eq!(
696            window.debug_bounds("styled-content").unwrap().origin,
697            point(px(120.), px(140.))
698        );
699
700        window.update(|window, cx| {
701            view.update(cx, |view, cx| {
702                view.styled = true;
703                cx.notify();
704            });
705            crate::test_redraw(window, cx);
706        });
707        window.update(|window, cx| crate::test_redraw(window, cx));
708        // `w_full` stretches the container across the 200px row, and the popup
709        // follows the container's right edge at 300px.
710        assert_eq!(
711            window.debug_bounds("styled-content").unwrap().origin,
712            point(px(280.), px(140.))
713        );
714    }
715
716    #[gpui::test]
717    fn arrow_reserves_space_without_changing_anchor_alignment(cx: &mut gpui::TestAppContext) {
718        cx.update(crate::init);
719        let (view, window) = cx.add_window_view(|_, _| AnchorHarness {
720            anchor: Anchor::TopLeft,
721            offset: Some(px(12.)),
722            origin: point(px(200.), px(8.)),
723            arrow: true,
724        });
725        window.update(|window, cx| crate::test_redraw(window, cx));
726        window.update(|window, cx| crate::test_redraw(window, cx));
727        // Bottom edge 48 + tip gap 12 + arrow depth 6.
728        assert_eq!(
729            window.debug_bounds("positioned-content").unwrap().origin,
730            point(px(200.), px(66.))
731        );
732        window.update(|window, cx| {
733            view.update(cx, |view, cx| {
734                view.anchor = Anchor::TopRight;
735                view.arrow = false;
736                cx.notify();
737            });
738            crate::test_redraw(window, cx);
739        });
740        assert_eq!(
741            window.debug_bounds("positioned-content").unwrap().origin,
742            point(px(180.), px(60.))
743        );
744    }
745
746    #[gpui::test]
747    fn anchor_does_not_flip_when_offset_or_arrow_is_enabled(cx: &mut gpui::TestAppContext) {
748        cx.update(crate::init);
749        let (_, window) = cx.add_window_view(|_, _| AnchorHarness {
750            anchor: Anchor::BottomCenter,
751            offset: Some(px(12.)),
752            origin: point(px(200.), px(8.)),
753            arrow: true,
754        });
755        window.update(|window, cx| crate::test_redraw(window, cx));
756        window.update(|window, cx| crate::test_redraw(window, cx));
757        // Clamp to the window margin instead of flipping below the trigger.
758        assert_eq!(
759            window.debug_bounds("positioned-content").unwrap().top(),
760            px(8.)
761        );
762    }
763
764    #[test]
765    fn arrow_alignment_uses_the_anchor_instead_of_trigger_center() {
766        let trigger = Bounds::new(point(px(120.), px(120.)), size(px(40.), px(20.)));
767        for (anchor, side, target) in [
768            (
769                Anchor::TopLeft,
770                Placement::Bottom,
771                point(px(120.), px(140.)),
772            ),
773            (
774                Anchor::TopCenter,
775                Placement::Bottom,
776                point(px(140.), px(140.)),
777            ),
778            (
779                Anchor::TopRight,
780                Placement::Bottom,
781                point(px(160.), px(140.)),
782            ),
783            (
784                Anchor::BottomLeft,
785                Placement::Top,
786                point(px(120.), px(120.)),
787            ),
788            (
789                Anchor::BottomCenter,
790                Placement::Top,
791                point(px(140.), px(120.)),
792            ),
793            (
794                Anchor::BottomRight,
795                Placement::Top,
796                point(px(160.), px(120.)),
797            ),
798            (
799                Anchor::LeftCenter,
800                Placement::Right,
801                point(px(160.), px(130.)),
802            ),
803            (
804                Anchor::RightCenter,
805                Placement::Left,
806                point(px(120.), px(130.)),
807            ),
808        ] {
809            assert_eq!(arrow_anchor(anchor, trigger), (side, target));
810        }
811    }
812
813    #[test]
814    fn arrows_point_toward_the_trigger_on_every_resolved_side() {
815        let surface = Bounds::new(point(px(100.), px(100.)), size(px(80.), px(60.)));
816        for (side, trigger, tip) in [
817            (
818                Placement::Bottom,
819                Bounds::new(point(px(120.), px(50.)), size(px(40.), px(20.))),
820                point(px(140.), px(94.)),
821            ),
822            (
823                Placement::Top,
824                Bounds::new(point(px(120.), px(180.)), size(px(40.), px(20.))),
825                point(px(140.), px(166.)),
826            ),
827            (
828                Placement::Right,
829                Bounds::new(point(px(40.), px(120.)), size(px(40.), px(20.))),
830                point(px(94.), px(130.)),
831            ),
832            (
833                Placement::Left,
834                Bounds::new(point(px(200.), px(120.)), size(px(40.), px(20.))),
835                point(px(186.), px(130.)),
836            ),
837        ] {
838            assert_eq!(arrow_points(surface, trigger, side, px(6.), px(4.))[1], tip);
839        }
840        let clamped = arrow_points(
841            surface,
842            Bounds::new(point(px(0.), px(50.)), size(px(20.), px(20.))),
843            Placement::Bottom,
844            px(6.),
845            px(4.),
846        );
847        assert_eq!(clamped[0], point(px(104.), px(100.)));
848        assert_eq!(clamped[1], point(px(110.), px(94.)));
849    }
850
851    #[test]
852    fn arrow_join_covers_both_sides_of_the_surface_edge() {
853        let surface = Bounds::new(point(px(100.), px(100.)), size(px(80.), px(60.)));
854        let trigger = Bounds::new(point(px(120.), px(120.)), size(px(40.), px(20.)));
855        for (side, expected) in [
856            (
857                Placement::Bottom,
858                Bounds::new(point(px(135.), px(99.)), size(px(10.), px(2.))),
859            ),
860            (
861                Placement::Top,
862                Bounds::new(point(px(135.), px(159.)), size(px(10.), px(2.))),
863            ),
864            (
865                Placement::Right,
866                Bounds::new(point(px(99.), px(125.)), size(px(2.), px(10.))),
867            ),
868            (
869                Placement::Left,
870                Bounds::new(point(px(179.), px(125.)), size(px(2.), px(10.))),
871            ),
872        ] {
873            let points = arrow_points(surface, trigger, side, px(6.), px(4.));
874            assert_eq!(arrow_join_bounds(points, side, px(1.)), expected);
875        }
876    }
877
878    impl Render for PopoverHarness {
879        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
880            let changes = self.changes.clone();
881            Popover::new("runtime-popover")
882                .trigger(Button::new("runtime-trigger").label("Open").size(px(100.)))
883                .content(|_, _, _| {
884                    div()
885                        .debug_selector(|| "runtime-popover-content".into())
886                        .size(px(40.))
887                })
888                .on_open_change(move |open, _, _| changes.borrow_mut().push(*open))
889        }
890    }
891
892    #[gpui::test]
893    fn pointer_open_and_outside_dismiss_use_the_base_popup_host(cx: &mut gpui::TestAppContext) {
894        cx.update(|cx| {
895            gpui_base::GlobalState::init(cx);
896            cx.set_global(Theme::default());
897            init(cx);
898        });
899
900        let changes = Rc::new(RefCell::new(Vec::new()));
901        let (_, cx) = cx.add_window_view({
902            let changes = changes.clone();
903            move |_, _| PopoverHarness { changes }
904        });
905        cx.update(|window, cx| crate::test_redraw(window, cx));
906
907        cx.simulate_click(point(px(20.), px(20.)), Default::default());
908        cx.update(|window, cx| crate::test_redraw(window, cx));
909        assert!(cx.debug_bounds("runtime-popover-content").is_some());
910
911        cx.simulate_click(point(px(300.), px(300.)), Default::default());
912        cx.update(|window, cx| crate::test_redraw(window, cx));
913        assert!(cx.debug_bounds("runtime-popover-content").is_none());
914        // A change callback reports state transitions, not redundant dismissal
915        // requests. The base host may see both paths, but only the first closes.
916        assert_eq!(&*changes.borrow(), &[true, false]);
917    }
918
919    struct DefaultOpenHarness;
920
921    impl Render for DefaultOpenHarness {
922        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
923            Popover::new("default-open-popover")
924                .default_open(true)
925                .trigger(Button::new("default-open-trigger").label("Open"))
926                .child(
927                    div()
928                        .debug_selector(|| "default-open-content".into())
929                        .size(px(40.)),
930                )
931        }
932    }
933
934    #[gpui::test]
935    fn default_open_is_forwarded_to_the_base_popover(cx: &mut gpui::TestAppContext) {
936        cx.update(|cx| {
937            gpui_base::GlobalState::init(cx);
938            cx.set_global(Theme::default());
939            init(cx);
940        });
941        let (_, cx) = cx.add_window_view(|_, _| DefaultOpenHarness);
942        cx.update(|window, cx| crate::test_redraw(window, cx));
943        cx.update(|window, cx| crate::test_redraw(window, cx));
944        assert!(cx.debug_bounds("default-open-content").is_some());
945    }
946
947    struct Harness {
948        open: bool,
949    }
950
951    impl Render for Harness {
952        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
953            div().size_full().when(self.open, |this| {
954                this.child(dropdown_popup(
955                    "dropdown",
956                    Bounds::new(point(px(0.), px(100.)), size(px(120.), px(30.))),
957                    div().debug_selector(|| "surface".into()).size(px(50.)),
958                    cx,
959                ))
960            })
961        }
962    }
963
964    /// A dropdown that reused one animation key across opens would play its
965    /// enter motion the first time and then appear already settled on every
966    /// open after that. That is invisible in any single frame and easy to
967    /// reintroduce by giving the animation a constant id, so it is pinned here.
968    #[gpui::test]
969    fn the_enter_motion_starts_over_every_time_the_dropdown_opens(cx: &mut gpui::TestAppContext) {
970        cx.update(crate::init);
971        let executor = cx.executor();
972        let (view, window) = cx.add_window_view(|_, _| Harness { open: true });
973
974        window.update(|window, cx| crate::test_redraw(window, cx));
975        let opening = window.debug_bounds("surface").unwrap().origin;
976
977        // The animation runs on the test clock, so settling is stepped.
978        executor.advance_clock(DROPDOWN_ENTER_DURATION * 4);
979        window.update(|window, cx| crate::test_redraw(window, cx));
980        let settled = window.debug_bounds("surface").unwrap().origin;
981
982        assert!(
983            opening.y < settled.y,
984            "the surface should slide down into place, from {opening:?} to {settled:?}",
985        );
986
987        for open in [false, true] {
988            window.update(|window, cx| {
989                view.update(cx, |this, cx| {
990                    this.open = open;
991                    cx.notify();
992                });
993                crate::test_redraw(window, cx);
994            });
995        }
996
997        let reopening = window.debug_bounds("surface").unwrap().origin;
998        assert!(
999            reopening.y < settled.y,
1000            "reopening should start the motion over at {opening:?} rather than showing a \
1001             settled surface, but the first frame was already at {reopening:?}",
1002        );
1003    }
1004}