1use std::rc::Rc;
2
3use gpui::{
4 Anchor, AnyElement, App, Context, DismissEvent, ElementId, EventEmitter, FocusHandle,
5 Focusable, InteractiveElement as _, IntoElement, KeyBinding, MouseButton, ParentElement as _,
6 Render, RenderOnce, Role, StatefulInteractiveElement as _, StyleRefinement, Styled,
7 Subscription, Window, div, prelude::FluentBuilder as _,
8};
9
10use crate::{
11 DeferredPopover, GlobalState, Popup, ResolvedPosition, Selectable, StyledExt as _,
12 actions::{Cancel, Confirm},
13};
14
15const CONTEXT: &str = "Popover";
16const CONTENT_CONTEXT: &str = "PopoverContent";
17
18pub(crate) fn init(cx: &mut App) {
19 cx.bind_keys([
20 KeyBinding::new("escape", Cancel, Some(CONTEXT)),
21 KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
22 KeyBinding::new("space", Confirm { secondary: false }, Some(CONTEXT)),
23 KeyBinding::new("escape", Cancel, Some(CONTENT_CONTEXT)),
24 KeyBinding::new("enter", gpui::NoAction, Some(CONTENT_CONTEXT)),
28 KeyBinding::new("space", gpui::NoAction, Some(CONTENT_CONTEXT)),
29 ]);
30}
31
32type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
33
34pub struct PopoverState {
40 focus_handle: FocusHandle,
41 tracked_focus_handle: Option<FocusHandle>,
42 previous_focus_handle: Option<FocusHandle>,
43 open: bool,
44 on_open_change: Option<OpenChangeHandler>,
45 dismiss_subscription: Option<Subscription>,
46 deferred_context: Option<DeferredPopover>,
49}
50
51impl PopoverState {
52 pub fn new(default_open: bool, cx: &mut App) -> Self {
53 Self {
54 focus_handle: cx.focus_handle(),
55 tracked_focus_handle: None,
56 previous_focus_handle: None,
57 open: default_open,
58 on_open_change: None,
59 dismiss_subscription: None,
60 deferred_context: None,
61 }
62 }
63
64 pub fn is_open(&self) -> bool {
65 self.open
66 }
67
68 pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
69 if self.open {
70 self.toggle_open(window, cx);
71 }
72 }
73
74 fn has_nested_popup(&self, cx: &App) -> bool {
77 self.deferred_context
78 .as_ref()
79 .is_some_and(|context| GlobalState::has_deferred_popover_after(context, cx))
80 }
81
82 pub fn show(&mut self, window: &mut Window, cx: &mut Context<Self>) {
83 if !self.open {
84 self.toggle_open(window, cx);
85 }
86 }
87
88 #[doc(hidden)]
89 pub fn set_open(&mut self, open: bool, cx: &mut Context<Self>) {
90 self.open = open;
91 self.deferred_context = open.then(|| GlobalState::register_deferred_popover(cx));
92 }
93
94 #[doc(hidden)]
95 pub fn sync_open(&mut self, open: bool, window: &mut Window, cx: &mut Context<Self>) {
96 self.transition_to(open, false, window, cx);
97 }
98
99 #[doc(hidden)]
100 pub fn toggle_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
101 self.transition_to(!self.open, true, window, cx);
102 }
103
104 fn transition_to(
105 &mut self,
106 opening: bool,
107 announce: bool,
108 window: &mut Window,
109 cx: &mut Context<Self>,
110 ) {
111 if self.open == opening {
112 return;
113 }
114 if opening {
115 self.previous_focus_handle = window.focused(cx);
116 }
117 self.set_open(opening, cx);
118
119 if self.open {
120 let state = cx.entity().downgrade();
124 self.tracked_focus_handle
125 .clone()
126 .unwrap_or_else(|| self.focus_handle.clone())
127 .focus(window, cx);
128
129 self.dismiss_subscription =
130 Some(
131 window.subscribe(&cx.entity(), cx, move |_, _: &DismissEvent, window, cx| {
132 _ = state.update(cx, |state, cx| state.dismiss(window, cx));
133 window.refresh();
134 }),
135 );
136 } else {
137 self.dismiss_subscription = None;
138 let previous = self.previous_focus_handle.take();
139 if self.focus_handle.contains_focused(window, cx) {
140 match previous {
141 Some(previous) => previous.focus(window, cx),
142 None => window.blur(cx),
146 }
147 }
148 }
149
150 if announce && let Some(callback) = self.on_open_change.as_ref() {
151 callback(&opening, window, cx);
152 }
153 cx.notify();
154 }
155
156 #[doc(hidden)]
157 pub fn track_focus(&mut self, focus_handle: Option<FocusHandle>) {
158 self.tracked_focus_handle = focus_handle;
159 }
160
161 #[doc(hidden)]
162 pub fn set_on_open_change(&mut self, handler: Option<OpenChangeHandler>) {
163 self.on_open_change = handler;
164 }
165
166 #[doc(hidden)]
167 pub fn on_action_cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
168 self.dismiss(window, cx);
169 }
170}
171
172impl Focusable for PopoverState {
173 fn focus_handle(&self, _: &App) -> FocusHandle {
174 self.focus_handle.clone()
175 }
176}
177
178impl Render for PopoverState {
179 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
180 div()
181 }
182}
183
184impl EventEmitter<DismissEvent> for PopoverState {}
185
186type TriggerBuilder = Box<dyn FnOnce(bool, &Window, &App) -> AnyElement>;
187type ContentBuilder =
188 Box<dyn FnOnce(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> AnyElement>;
189
190#[derive(IntoElement)]
196pub struct Popover {
197 id: ElementId,
198 style: StyleRefinement,
199 anchor: Anchor,
200 offset: gpui::Pixels,
201 on_position: Option<Box<dyn Fn(ResolvedPosition, gpui::Bounds<gpui::Pixels>)>>,
202 default_open: bool,
203 open: Option<bool>,
204 tracked_focus_handle: Option<FocusHandle>,
205 trigger: Option<TriggerBuilder>,
206 content: Option<ContentBuilder>,
207 mouse_button: MouseButton,
208 overlay_closable: bool,
209 on_open_change: Option<OpenChangeHandler>,
210}
211
212impl Popover {
213 pub fn new(id: impl Into<ElementId>) -> Self {
214 Self {
215 id: id.into(),
216 style: StyleRefinement::default(),
217 anchor: Anchor::TopLeft,
218 offset: gpui::px(0.),
219 on_position: None,
220 default_open: false,
221 open: None,
222 tracked_focus_handle: None,
223 trigger: None,
224 content: None,
225 mouse_button: MouseButton::Left,
226 overlay_closable: true,
227 on_open_change: None,
228 }
229 }
230
231 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
232 self.anchor = anchor.into();
233 self
234 }
235
236 pub fn offset(mut self, offset: gpui::Pixels) -> Self {
238 self.offset = offset;
239 self
240 }
241
242 pub fn on_position(
244 mut self,
245 callback: impl Fn(ResolvedPosition, gpui::Bounds<gpui::Pixels>) + 'static,
246 ) -> Self {
247 self.on_position = Some(Box::new(callback));
248 self
249 }
250
251 pub fn mouse_button(mut self, mouse_button: MouseButton) -> Self {
252 self.mouse_button = mouse_button;
253 self
254 }
255
256 pub fn trigger<T>(mut self, trigger: T) -> Self
257 where
258 T: Selectable + IntoElement + 'static,
259 {
260 self.trigger = Some(Box::new(|is_open, _, _| {
261 let open = trigger.is_open();
262 trigger.open(open || is_open).into_any_element()
263 }));
264 self
265 }
266
267 #[doc(hidden)]
269 pub fn trigger_with(
270 mut self,
271 trigger: impl FnOnce(bool, &Window, &App) -> AnyElement + 'static,
272 ) -> Self {
273 self.trigger = Some(Box::new(trigger));
274 self
275 }
276
277 pub fn default_open(mut self, open: bool) -> Self {
278 self.default_open = open;
279 self
280 }
281
282 pub fn open(mut self, open: bool) -> Self {
283 self.open = Some(open);
284 self
285 }
286
287 pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
288 self.tracked_focus_handle = Some(handle.clone());
289 self
290 }
291
292 pub fn overlay_closable(mut self, closable: bool) -> Self {
293 self.overlay_closable = closable;
294 self
295 }
296
297 pub fn on_open_change(
298 mut self,
299 callback: impl Fn(&bool, &mut Window, &mut App) + 'static,
300 ) -> Self {
301 self.on_open_change = Some(Rc::new(callback));
302 self
303 }
304
305 pub fn content<F, E>(mut self, content: F) -> Self
306 where
307 E: IntoElement,
308 F: FnOnce(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> E + 'static,
309 {
310 self.content = Some(Box::new(move |state, window, cx| {
311 content(state, window, cx).into_any_element()
312 }));
313 self
314 }
315}
316
317impl Styled for Popover {
320 fn style(&mut self) -> &mut StyleRefinement {
321 &mut self.style
322 }
323}
324
325impl RenderOnce for Popover {
326 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
327 let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| {
328 PopoverState::new(self.default_open, cx)
329 });
330 state.update(cx, |state, cx| {
331 state.track_focus(self.tracked_focus_handle);
332 state.set_on_open_change(self.on_open_change);
333 if let Some(open) = self.open {
334 state.sync_open(open, window, cx);
335 }
336 });
337
338 let open = state.read(cx).is_open();
339 let focus_handle = state.read(cx).focus_handle(cx);
340 let Some(trigger) = self.trigger else {
341 return div().id("empty").into_any_element();
342 };
343 let parent_view_id = window.current_view();
344 let popup = Popup::new(self.id, trigger(open, window, cx))
345 .refine_style(&self.style)
346 .anchor(self.anchor)
347 .offset(self.offset)
348 .when_some(self.on_position, |this, callback| {
349 this.on_position(callback)
350 })
351 .key_context(CONTEXT)
352 .on_action({
353 let state = state.clone();
354 move |_: &Confirm, window, cx| {
355 state.update(cx, |state, cx| state.toggle_open(window, cx));
356 cx.notify(parent_view_id);
357 }
358 })
359 .on_mouse_down(self.mouse_button, {
360 let state = state.clone();
361 move |_, window, cx| {
362 cx.stop_propagation();
363 state.update(cx, |state, cx| {
364 if state.is_open() == open {
365 state.toggle_open(window, cx);
366 }
367 });
368 cx.notify(parent_view_id);
369 }
370 });
371 if !open {
372 return popup.into_any_element();
373 }
374
375 let content = div()
376 .id("content")
377 .role(Role::Dialog)
381 .occlude()
382 .tab_group()
383 .track_focus(&focus_handle)
384 .key_context(CONTENT_CONTEXT)
385 .on_action(window.listener_for(&state, PopoverState::on_action_cancel))
386 .when_some(self.content, |this, content| {
387 this.child(state.update(cx, |state, cx| (content)(state, window, cx)))
388 })
389 .when(self.overlay_closable, |this| {
390 this.on_mouse_down_out({
391 let state = state.clone();
392 move |_, window, cx| {
393 if !state.read(cx).has_nested_popup(cx) {
394 state.update(cx, |state, cx| state.dismiss(window, cx));
395 cx.notify(parent_view_id);
396 return;
397 }
398 let state = state.clone();
403 window.defer(cx, move |window, cx| {
404 if !state.read(cx).has_nested_popup(cx) {
405 state.update(cx, |state, cx| state.dismiss(window, cx));
406 cx.notify(parent_view_id);
407 }
408 });
409 }
410 })
411 });
412 popup.content(content).into_any_element()
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419 use gpui::{AppContext as _, Context, Render, point, px};
420 use std::{cell::RefCell, rc::Rc};
421
422 #[gpui::test]
427 fn a_state_dropped_while_open_closes_the_deferred_context(cx: &mut gpui::TestAppContext) {
428 let state = cx.update(|cx| {
429 GlobalState::init(cx);
430 let state = cx.new(|cx| PopoverState::new(false, cx));
431 state.update(cx, |state, cx| state.set_open(true, cx));
432 assert!(GlobalState::is_in_deferred_context(cx));
433 state
434 });
435
436 cx.update(|_| drop(state));
437 cx.update(|cx| assert!(!GlobalState::is_in_deferred_context(cx)));
438 }
439
440 #[gpui::test]
441 fn open_state_registers_and_unregisters_deferred_context(cx: &mut gpui::TestAppContext) {
442 cx.update(|cx| {
443 GlobalState::init(cx);
444 let state = cx.new(|cx| PopoverState::new(false, cx));
445
446 state.update(cx, |state, cx| state.set_open(true, cx));
447 assert!(state.read(cx).is_open());
448 assert!(GlobalState::is_in_deferred_context(cx));
449
450 state.update(cx, |state, cx| state.set_open(false, cx));
451 assert!(!state.read(cx).is_open());
452 assert!(!GlobalState::is_in_deferred_context(cx));
453 });
454 }
455
456 struct PopoverHarness {
457 changes: Rc<RefCell<Vec<bool>>>,
458 default_open: bool,
459 }
460
461 struct KeyboardPopoverHarness {
462 trigger_focus: FocusHandle,
463 }
464
465 impl Render for KeyboardPopoverHarness {
466 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
467 Popover::new("keyboard-popover")
468 .trigger(
469 crate::Button::new("keyboard-trigger")
470 .track_focus(&self.trigger_focus)
471 .child("Open"),
472 )
473 .content(|_, _, _| {
474 div()
475 .debug_selector(|| "keyboard-popover-content".into())
476 .size(px(40.))
477 })
478 }
479 }
480
481 impl Render for PopoverHarness {
482 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
483 let changes = self.changes.clone();
484 Popover::new("base-popover")
485 .default_open(self.default_open)
486 .trigger_with(|_, _, _| div().child("Open").into_any_element())
487 .content(|_, _, _| {
488 div()
489 .debug_selector(|| "base-popover-content".into())
490 .size(px(40.))
491 })
492 .on_open_change(move |open, _, _| changes.borrow_mut().push(*open))
493 }
494 }
495
496 #[gpui::test]
497 fn unstyled_popover_owns_pointer_open_and_outside_dismiss(cx: &mut gpui::TestAppContext) {
498 cx.update(crate::init);
499 let changes = Rc::new(RefCell::new(Vec::new()));
500 let (_, cx) = cx.add_window_view({
501 let changes = changes.clone();
502 move |_, _| PopoverHarness {
503 changes,
504 default_open: false,
505 }
506 });
507 cx.update(|window, cx| window.draw(cx).clear(cx));
508 cx.update(|window, cx| assert!(window.focused(cx).is_none(), "nothing has focus yet"));
509
510 cx.simulate_click(point(px(20.), px(10.)), Default::default());
511 cx.update(|window, cx| window.draw(cx).clear(cx));
512 assert!(cx.debug_bounds("base-popover-content").is_some());
513 cx.update(|window, cx| assert!(window.focused(cx).is_some(), "the popover takes focus"));
514
515 cx.simulate_click(point(px(300.), px(300.)), Default::default());
516 cx.update(|window, cx| window.draw(cx).clear(cx));
517 assert!(cx.debug_bounds("base-popover-content").is_none());
518 assert_eq!(&*changes.borrow(), &[true, false]);
519 cx.update(|window, cx| {
522 assert!(
523 window.focused(cx).is_none(),
524 "focus stays on {:?}",
525 window.focused(cx)
526 )
527 });
528 }
529
530 struct NestedPopoverHarness;
531
532 impl Render for NestedPopoverHarness {
533 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
534 Popover::new("outer-popover")
535 .trigger_with(|_, _, _| div().size(px(40.)).child("Open").into_any_element())
536 .content(|_, _, _| {
537 div()
538 .debug_selector(|| "outer-popover-content".into())
539 .size(px(40.))
540 .child(
541 Popover::new("inner-popover")
542 .trigger_with(|_, _, _| {
543 div()
544 .debug_selector(|| "inner-popover-trigger".into())
545 .size(px(20.))
546 .into_any_element()
547 })
548 .content(|_, _, _| {
549 div()
550 .debug_selector(|| "inner-popover-content".into())
551 .size(px(120.))
552 }),
553 )
554 })
555 }
556 }
557
558 #[gpui::test]
562 fn a_press_in_a_nested_popup_keeps_the_popover_open(cx: &mut gpui::TestAppContext) {
563 cx.update(crate::init);
564 let (_, cx) = cx.add_window_view(|_, _| NestedPopoverHarness);
565 cx.update(|window, cx| window.draw(cx).clear(cx));
566
567 cx.simulate_click(point(px(20.), px(10.)), Default::default());
568 cx.update(|window, cx| window.draw(cx).clear(cx));
569 let outer = cx
570 .debug_bounds("outer-popover-content")
571 .expect("the outer popover opens");
572
573 let inner_trigger = cx
574 .debug_bounds("inner-popover-trigger")
575 .expect("the outer popover holds the inner trigger");
576 cx.simulate_click(inner_trigger.center(), Default::default());
577 cx.update(|window, cx| window.draw(cx).clear(cx));
578 let inner = cx
579 .debug_bounds("inner-popover-content")
580 .expect("the inner popover opens");
581
582 let in_inner_only = point(inner.right() - px(2.), inner.top() + px(2.));
583 assert!(
584 !outer.contains(&in_inner_only),
585 "the press must land outside the outer popover's bounds"
586 );
587 cx.simulate_click(in_inner_only, Default::default());
588 cx.update(|window, cx| window.draw(cx).clear(cx));
589 assert!(cx.debug_bounds("inner-popover-content").is_some());
590 assert!(
591 cx.debug_bounds("outer-popover-content").is_some(),
592 "a press in the nested popup must not dismiss the popover"
593 );
594
595 cx.simulate_click(point(px(300.), px(300.)), Default::default());
596 cx.update(|window, cx| window.draw(cx).clear(cx));
597 assert!(cx.debug_bounds("inner-popover-content").is_none());
598 assert!(
599 cx.debug_bounds("outer-popover-content").is_none(),
600 "a press outside both closes both"
601 );
602 }
603
604 #[gpui::test]
605 fn default_open_renders_content_without_activation(cx: &mut gpui::TestAppContext) {
606 cx.update(crate::init);
607 let (_, cx) = cx.add_window_view(|_, _| PopoverHarness {
608 changes: Rc::new(RefCell::new(Vec::new())),
609 default_open: true,
610 });
611 cx.update(|window, cx| window.draw(cx).clear(cx));
612 cx.update(|window, cx| window.draw(cx).clear(cx));
613 assert!(cx.debug_bounds("base-popover-content").is_some());
614 }
615
616 #[derive(IntoElement)]
620 struct RecordingTrigger {
621 calls: Rc<RefCell<Vec<(&'static str, bool)>>>,
622 selected: bool,
623 open: bool,
624 }
625
626 impl Selectable for RecordingTrigger {
627 fn selected(mut self, selected: bool) -> Self {
628 self.calls.borrow_mut().push(("selected", selected));
629 self.selected = selected;
630 self
631 }
632
633 fn is_selected(&self) -> bool {
634 self.selected
635 }
636
637 fn open(mut self, open: bool) -> Self {
638 self.calls.borrow_mut().push(("open", open));
639 self.open = open;
640 self
641 }
642
643 fn is_open(&self) -> bool {
644 self.open
645 }
646 }
647
648 impl RenderOnce for RecordingTrigger {
649 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
650 div().size(px(40.)).child("Open")
651 }
652 }
653
654 struct RecordingTriggerHarness {
655 calls: Rc<RefCell<Vec<(&'static str, bool)>>>,
656 }
657
658 impl Render for RecordingTriggerHarness {
659 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
660 Popover::new("recording-popover")
661 .trigger(RecordingTrigger {
662 calls: self.calls.clone(),
663 selected: false,
664 open: false,
665 })
666 .content(|_, _, _| div().size(px(40.)))
667 }
668 }
669
670 #[gpui::test]
671 fn an_open_popover_tells_its_trigger_it_is_open_not_selected(cx: &mut gpui::TestAppContext) {
672 cx.update(crate::init);
673 let calls = Rc::new(RefCell::new(Vec::new()));
674 let (_, cx) = cx.add_window_view({
675 let calls = calls.clone();
676 move |_, _| RecordingTriggerHarness { calls }
677 });
678 cx.update(|window, cx| window.draw(cx).clear(cx));
679 calls.borrow_mut().clear();
680
681 cx.simulate_click(point(px(20.), px(10.)), Default::default());
682 cx.update(|window, cx| window.draw(cx).clear(cx));
683
684 let calls = calls.borrow();
685 assert!(
686 calls.contains(&("open", true)),
687 "an open popover marks its trigger open, got {calls:?}"
688 );
689 assert!(
690 !calls.iter().any(|(name, _)| *name == "selected"),
691 "opening must not touch the trigger's own selection, got {calls:?}"
692 );
693 }
694
695 #[gpui::test]
696 fn keyboard_activation_opens_the_popover(cx: &mut gpui::TestAppContext) {
697 cx.update(crate::init);
698 let (view, cx) = cx.add_window_view(|_, cx| KeyboardPopoverHarness {
699 trigger_focus: cx.focus_handle(),
700 });
701 cx.update(|window, cx| window.draw(cx).clear(cx));
702
703 cx.update(|window, cx| {
704 let focus = view.read(cx).trigger_focus.clone();
705 focus.focus(window, cx);
706 });
707 cx.simulate_keystrokes("enter");
708 cx.update(|window, cx| window.draw(cx).clear(cx));
709
710 assert!(cx.debug_bounds("keyboard-popover-content").is_some());
711 }
712}