Skip to main content

fc_ui/capabilities/overlays/
popover.rs

1//! Popover component with anchored positioning.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::time::Duration;
5use std::{cell::RefCell, rc::Rc};
6
7use crate::capabilities::foundation::theme::use_theme;
8use crate::capabilities::motion::animations::easings;
9
10const POPOVER_MARGIN: Pixels = px(8.0);
11const CONTEXT: &str = "Popover";
12
13actions!(popover, [ClosePopover]);
14
15pub fn init(cx: &mut App) {
16    if !crate::capabilities::foundation::initialization::begin(cx, "popover") {
17        return;
18    }
19    cx.bind_keys([KeyBinding::new("escape", ClosePopover, Some(CONTEXT))]);
20}
21
22pub struct PopoverContent {
23    focus_handle: FocusHandle,
24    content: Rc<dyn Fn(&mut Window, &mut Context<Self>) -> AnyElement>,
25    dismissing: bool,
26}
27
28impl PopoverContent {
29    pub fn new<F>(_window: &mut Window, cx: &mut App, content: F) -> Self
30    where
31        F: Fn(&mut Window, &mut Context<Self>) -> AnyElement + 'static,
32    {
33        Self {
34            focus_handle: cx.focus_handle(),
35            content: Rc::new(content),
36            dismissing: false,
37        }
38    }
39}
40
41impl EventEmitter<DismissEvent> for PopoverContent {}
42
43impl Focusable for PopoverContent {
44    fn focus_handle(&self, _cx: &App) -> FocusHandle {
45        self.focus_handle.clone()
46    }
47}
48
49impl Render for PopoverContent {
50    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
51        let theme = use_theme(cx);
52        let dismissing = self.dismissing;
53
54        div()
55            .p(px(12.0))
56            .min_w(px(200.0))
57            .max_w(px(400.0))
58            .bg(theme.tokens.popover)
59            .text_color(theme.tokens.popover_foreground)
60            .border_1()
61            .border_color(theme.tokens.border)
62            .rounded(theme.tokens.radius_md)
63            .shadow_lg()
64            .overflow_hidden()
65            .track_focus(&self.focus_handle)
66            .key_context(CONTEXT)
67            .on_action(cx.listener(|this, _: &ClosePopover, window, cx| {
68                if this.dismissing {
69                    return;
70                }
71                this.dismissing = true;
72                cx.notify();
73
74                cx.spawn_in(window, async move |entity, cx| {
75                    smol::Timer::after(Duration::from_millis(120)).await;
76                    let _ = entity.update(cx, |_, cx| {
77                        cx.emit(DismissEvent);
78                    });
79                })
80                .detach();
81            }))
82            .child((self.content)(window, cx))
83            .with_animation(
84                if dismissing {
85                    "popover-exit"
86                } else {
87                    "popover-enter"
88                },
89                Animation::new(Duration::from_millis(if dismissing { 120 } else { 150 }))
90                    .with_easing(if dismissing {
91                        easings::ease_in_cubic as fn(f32) -> f32
92                    } else {
93                        easings::ease_out_cubic as fn(f32) -> f32
94                    }),
95                move |el, delta| {
96                    if dismissing {
97                        el.opacity(1.0 - delta).mt(px(4.0 * delta))
98                    } else {
99                        el.opacity(delta).mt(px(4.0 * (1.0 - delta)))
100                    }
101                },
102            )
103    }
104}
105
106pub struct Popover {
107    id: ElementId,
108    anchor: Corner,
109    trigger: Option<Box<dyn FnOnce(bool, &Window, &App) -> AnyElement + 'static>>,
110    content: Option<Rc<dyn Fn(&mut Window, &mut App) -> Entity<PopoverContent> + 'static>>,
111    mouse_button: MouseButton,
112    style: StyleRefinement,
113}
114
115impl Popover {
116    pub fn new(id: impl Into<ElementId>) -> Self {
117        Self {
118            id: id.into(),
119            anchor: Corner::TopLeft,
120            trigger: None,
121            content: None,
122            mouse_button: MouseButton::Left,
123            style: StyleRefinement::default(),
124        }
125    }
126
127    pub fn anchor(mut self, anchor: Corner) -> Self {
128        self.anchor = anchor;
129        self
130    }
131
132    pub fn mouse_button(mut self, mouse_button: MouseButton) -> Self {
133        self.mouse_button = mouse_button;
134        self
135    }
136
137    pub fn trigger<T>(mut self, trigger: T) -> Self
138    where
139        T: IntoElement + 'static,
140    {
141        self.trigger = Some(Box::new(move |_is_open, _, _| trigger.into_any_element()));
142        self
143    }
144
145    pub fn content<F>(mut self, content: F) -> Self
146    where
147        F: Fn(&mut Window, &mut App) -> Entity<PopoverContent> + 'static,
148    {
149        self.content = Some(Rc::new(content));
150        self
151    }
152
153    fn render_trigger(&mut self, open: bool, window: &mut Window, cx: &mut App) -> AnyElement {
154        let Some(trigger) = self.trigger.take() else {
155            return div().child("Trigger").into_any_element();
156        };
157        let user_style = self.style.clone();
158        let trigger_element = (trigger)(open, window, cx);
159
160        div()
161            .map(|mut this| {
162                this.style().refine(&user_style);
163                this
164            })
165            .child(trigger_element)
166            .into_any_element()
167    }
168
169    fn resolved_corner(&self, bounds: Bounds<Pixels>) -> Point<Pixels> {
170        bounds.corner(match self.anchor {
171            Corner::TopLeft => Corner::BottomLeft,
172            Corner::TopRight => Corner::BottomRight,
173            Corner::BottomLeft => Corner::TopLeft,
174            Corner::BottomRight => Corner::TopRight,
175        })
176    }
177
178    fn with_element_state<R>(
179        &mut self,
180        id: &GlobalElementId,
181        window: &mut Window,
182        cx: &mut App,
183        f: impl FnOnce(&mut Self, &mut PopoverElementState, &mut Window, &mut App) -> R,
184    ) -> R {
185        window.with_optional_element_state::<PopoverElementState, _>(
186            Some(id),
187            |element_state, window| {
188                let mut element_state = element_state.unwrap().unwrap_or_default();
189                let result = f(self, &mut element_state, window, cx);
190                (result, Some(element_state))
191            },
192        )
193    }
194}
195
196impl IntoElement for Popover {
197    type Element = Self;
198
199    fn into_element(self) -> Self::Element {
200        self
201    }
202}
203
204impl Styled for Popover {
205    fn style(&mut self) -> &mut StyleRefinement {
206        &mut self.style
207    }
208}
209
210#[derive(Default)]
211pub struct PopoverElementState {
212    trigger_layout_id: Option<LayoutId>,
213    popover_element: Option<AnyElement>,
214    trigger_element: Option<AnyElement>,
215    content_view: Rc<RefCell<Option<Entity<PopoverContent>>>>,
216    dismiss_subscription: Rc<RefCell<Option<Subscription>>>,
217    trigger_bounds: Option<Bounds<Pixels>>,
218}
219
220pub struct PrepaintState {
221    hitbox: Hitbox,
222    trigger_bounds: Option<Bounds<Pixels>>,
223}
224
225impl Element for Popover {
226    type RequestLayoutState = PopoverElementState;
227    type PrepaintState = PrepaintState;
228
229    fn id(&self) -> Option<ElementId> {
230        Some(self.id.clone())
231    }
232
233    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
234        None
235    }
236
237    fn request_layout(
238        &mut self,
239        id: Option<&GlobalElementId>,
240        _inspector_id: Option<&gpui::InspectorElementId>,
241        window: &mut Window,
242        cx: &mut App,
243    ) -> (LayoutId, Self::RequestLayoutState) {
244        let style = Style::default();
245
246        self.with_element_state(
247            id.unwrap(),
248            window,
249            cx,
250            |view, element_state, window, cx| {
251                let mut popover_layout_id = None;
252                let mut popover_element = None;
253                let mut is_open = false;
254
255                if let Some(content_view) = element_state.content_view.borrow_mut().as_mut() {
256                    is_open = true;
257
258                    let mut anchored = anchored()
259                        .snap_to_window_with_margin(POPOVER_MARGIN)
260                        .anchor(view.anchor);
261
262                    if let Some(trigger_bounds) = element_state.trigger_bounds {
263                        anchored = anchored.position(view.resolved_corner(trigger_bounds));
264                    }
265
266                    let mut element = {
267                        let content_view_mut = element_state.content_view.clone();
268                        let dismiss_subscription = element_state.dismiss_subscription.clone();
269                        let anchor = view.anchor;
270
271                        deferred(
272                            anchored.child(
273                                div()
274                                    .occlude()
275                                    .map(|this| match anchor {
276                                        Corner::TopLeft | Corner::TopRight => {
277                                            this.mt(POPOVER_MARGIN)
278                                        }
279                                        Corner::BottomLeft | Corner::BottomRight => {
280                                            this.mb(POPOVER_MARGIN)
281                                        }
282                                    })
283                                    .child(content_view.clone())
284                                    .on_mouse_down_out(move |_, window, _| {
285                                        *content_view_mut.borrow_mut() = None;
286                                        dismiss_subscription.borrow_mut().take();
287                                        window.refresh();
288                                    }),
289                            ),
290                        )
291                        .with_priority(1)
292                        .into_any()
293                    };
294
295                    popover_layout_id = Some(element.request_layout(window, cx));
296                    popover_element = Some(element);
297                }
298
299                let mut trigger_element = view.render_trigger(is_open, window, cx);
300                let trigger_layout_id = trigger_element.request_layout(window, cx);
301
302                let layout_id = window.request_layout(
303                    style,
304                    Some(trigger_layout_id).into_iter().chain(popover_layout_id),
305                    cx,
306                );
307
308                (
309                    layout_id,
310                    PopoverElementState {
311                        trigger_layout_id: Some(trigger_layout_id),
312                        popover_element,
313                        trigger_element: Some(trigger_element),
314                        content_view: element_state.content_view.clone(),
315                        dismiss_subscription: element_state.dismiss_subscription.clone(),
316                        trigger_bounds: element_state.trigger_bounds,
317                    },
318                )
319            },
320        )
321    }
322
323    fn prepaint(
324        &mut self,
325        _id: Option<&GlobalElementId>,
326        _inspector_id: Option<&gpui::InspectorElementId>,
327        _bounds: Bounds<Pixels>,
328        request_layout: &mut Self::RequestLayoutState,
329        window: &mut Window,
330        cx: &mut App,
331    ) -> Self::PrepaintState {
332        if let Some(element) = &mut request_layout.trigger_element {
333            element.prepaint(window, cx);
334        }
335        if let Some(element) = &mut request_layout.popover_element {
336            element.prepaint(window, cx);
337        }
338
339        let trigger_bounds = request_layout
340            .trigger_layout_id
341            .map(|id| window.layout_bounds(id));
342
343        let hitbox =
344            window.insert_hitbox(trigger_bounds.unwrap_or_default(), HitboxBehavior::Normal);
345
346        PrepaintState {
347            trigger_bounds,
348            hitbox,
349        }
350    }
351
352    fn paint(
353        &mut self,
354        id: Option<&GlobalElementId>,
355        _inspector_id: Option<&gpui::InspectorElementId>,
356        _bounds: Bounds<Pixels>,
357        request_layout: &mut Self::RequestLayoutState,
358        prepaint: &mut Self::PrepaintState,
359        window: &mut Window,
360        cx: &mut App,
361    ) {
362        self.with_element_state(
363            id.unwrap(),
364            window,
365            cx,
366            |this, element_state, window, cx| {
367                element_state.trigger_bounds = prepaint.trigger_bounds;
368
369                if let Some(mut element) = request_layout.trigger_element.take() {
370                    element.paint(window, cx);
371                }
372
373                if let Some(mut element) = request_layout.popover_element.take() {
374                    element.paint(window, cx);
375                    return;
376                }
377
378                let Some(content_build) = this.content.take() else {
379                    return;
380                };
381
382                let old_content_view = element_state.content_view.clone();
383                let dismiss_subscription = element_state.dismiss_subscription.clone();
384                let hitbox_id = prepaint.hitbox.id;
385                let mouse_button = this.mouse_button;
386
387                window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
388                    if phase == DispatchPhase::Bubble
389                        && event.button == mouse_button
390                        && hitbox_id.is_hovered(window)
391                    {
392                        cx.stop_propagation();
393                        window.prevent_default();
394
395                        let new_content_view = (content_build)(window, cx);
396                        let old_content_view1 = old_content_view.clone();
397                        let dismiss_subscription1 = dismiss_subscription.clone();
398
399                        let previous_focus_handle = window.focused(cx);
400
401                        let subscription = window.subscribe(
402                            &new_content_view,
403                            cx,
404                            move |modal, _: &DismissEvent, window, cx| {
405                                if modal.focus_handle(cx).contains_focused(window, cx) {
406                                    if let Some(previous_focus_handle) =
407                                        previous_focus_handle.as_ref()
408                                    {
409                                        window.focus(previous_focus_handle);
410                                    }
411                                }
412                                *old_content_view1.borrow_mut() = None;
413                                dismiss_subscription1.borrow_mut().take();
414                                window.refresh();
415                            },
416                        );
417
418                        window.focus(&new_content_view.focus_handle(cx));
419                        *old_content_view.borrow_mut() = Some(new_content_view);
420                        *dismiss_subscription.borrow_mut() = Some(subscription);
421                        window.refresh();
422                    }
423                });
424            },
425        );
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use super::{Popover, PopoverContent};
432    use crate::capabilities::controls::{
433        combobox::{Combobox, ComboboxState},
434        select::{Select, SelectOption},
435    };
436    use gpui::{
437        div, point, prelude::*, px, AppContext, Context, Modifiers, MouseButton, Render,
438        TestAppContext, VisualTestContext, Window,
439    };
440
441    #[derive(Clone, Copy)]
442    enum NestedControl {
443        Select,
444        Combobox,
445    }
446
447    struct NestedPopoverView {
448        control: NestedControl,
449    }
450
451    impl Render for NestedPopoverView {
452        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
453            let control = self.control;
454
455            div().size_full().p(px(24.0)).child(
456                Popover::new("nested-control-popover")
457                    .trigger(
458                        div()
459                            .debug_selector(|| "nested-popover-trigger".into())
460                            .w(px(120.0))
461                            .h(px(40.0)),
462                    )
463                    .content(move |window, cx| match control {
464                        NestedControl::Select => {
465                            let select = cx.new(|cx| {
466                                Select::new(cx)
467                                    .options(vec![SelectOption::new("one", "One")])
468                                    .placeholder("Choose")
469                            });
470                            cx.new(|cx| {
471                                PopoverContent::new(window, cx, move |_, _| {
472                                    div().w(px(240.0)).child(select.clone()).into_any_element()
473                                })
474                            })
475                        }
476                        NestedControl::Combobox => {
477                            let state = cx.new(|_| ComboboxState::new());
478                            let combobox = cx.new(|cx| {
479                                Combobox::new(vec!["One"], &state, cx)
480                                    .render_item(|item| (*item).into())
481                            });
482                            cx.new(|cx| {
483                                PopoverContent::new(window, cx, move |_, _| {
484                                    div()
485                                        .w(px(240.0))
486                                        .child(combobox.clone())
487                                        .into_any_element()
488                                })
489                            })
490                        }
491                    }),
492            )
493        }
494    }
495
496    fn draw(cx: &mut VisualTestContext) {
497        cx.update(|window, cx| window.draw(cx).clear());
498    }
499
500    fn click(selector: &'static str, cx: &mut VisualTestContext) {
501        draw(cx);
502        let bounds = cx
503            .debug_bounds(selector)
504            .unwrap_or_else(|| panic!("missing bounds for {selector}"));
505        let position = point(
506            bounds.origin.x + bounds.size.width / 2.0,
507            bounds.origin.y + bounds.size.height / 2.0,
508        );
509        cx.simulate_mouse_move(position, None, Modifiers::none());
510        cx.simulate_mouse_down(position, MouseButton::Left, Modifiers::none());
511        cx.simulate_mouse_up(position, MouseButton::Left, Modifiers::none());
512        draw(cx);
513    }
514
515    fn assert_nested_dropdown_survives_redraws(
516        control: NestedControl,
517        trigger_selector: &'static str,
518        dropdown_selector: &'static str,
519        cx: &mut TestAppContext,
520    ) {
521        let (_, cx) = cx.add_window_view(move |_, _| NestedPopoverView { control });
522
523        click("nested-popover-trigger", cx);
524        click(trigger_selector, cx);
525
526        for _ in 0..3 {
527            draw(cx);
528            let bounds = cx
529                .debug_bounds(dropdown_selector)
530                .unwrap_or_else(|| panic!("missing bounds for {dropdown_selector}"));
531            assert!(bounds.size.width > px(0.0));
532            assert!(bounds.size.height > px(0.0));
533        }
534    }
535
536    #[gpui::test]
537    fn select_inside_popover_survives_repeated_redraws(cx: &mut TestAppContext) {
538        assert_nested_dropdown_survives_redraws(
539            NestedControl::Select,
540            "select-trigger",
541            "select-dropdown",
542            cx,
543        );
544    }
545
546    #[gpui::test]
547    fn combobox_inside_popover_survives_repeated_redraws(cx: &mut TestAppContext) {
548        assert_nested_dropdown_survives_redraws(
549            NestedControl::Combobox,
550            "combobox-trigger",
551            "combobox-dropdown",
552            cx,
553        );
554    }
555}