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 fn move_focus(
104 &self,
105 opening: bool,
106 restore: Option<Option<FocusHandle>>,
107 window: &mut Window,
108 cx: &mut App,
109 ) {
110 if self.open != opening {
111 return;
112 }
113 if opening {
114 self.tracked_focus_handle
115 .clone()
116 .unwrap_or_else(|| self.focus_handle.clone())
117 .focus(window, cx);
118 return;
119 }
120 match restore {
121 Some(Some(previous)) => previous.focus(window, cx),
122 Some(None) => window.blur(cx),
126 None => {}
127 }
128 }
129
130 #[doc(hidden)]
131 pub fn toggle_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
132 self.transition_to(!self.open, true, window, cx);
133 }
134
135 fn transition_to(
136 &mut self,
137 opening: bool,
138 announce: bool,
139 window: &mut Window,
140 cx: &mut Context<Self>,
141 ) {
142 if self.open == opening {
143 return;
144 }
145 if opening {
146 self.previous_focus_handle = window.focused(cx);
147 }
148 self.set_open(opening, cx);
149
150 let restore = if self.open {
152 None
153 } else {
154 let previous = self.previous_focus_handle.take();
155 self.focus_handle
156 .contains_focused(window, cx)
157 .then_some(previous)
158 };
159 if announce {
160 self.move_focus(self.open, restore, window, cx);
161 } else {
162 let state = cx.entity().downgrade();
168 let opening = self.open;
169 window.defer(cx, move |window, cx| {
170 _ = state.update(cx, |state, cx| {
171 state.move_focus(opening, restore, window, cx)
172 });
173 });
174 }
175
176 if self.open {
177 let state = cx.entity().downgrade();
181 self.dismiss_subscription =
182 Some(
183 window.subscribe(&cx.entity(), cx, move |_, _: &DismissEvent, window, cx| {
184 _ = state.update(cx, |state, cx| state.dismiss(window, cx));
185 window.refresh();
186 }),
187 );
188 } else {
189 self.dismiss_subscription = None;
190 }
191
192 if announce && let Some(callback) = self.on_open_change.as_ref() {
193 callback(&opening, window, cx);
194 }
195 cx.notify();
196 }
197
198 #[doc(hidden)]
199 pub fn track_focus(&mut self, focus_handle: Option<FocusHandle>) {
200 self.tracked_focus_handle = focus_handle;
201 }
202
203 #[doc(hidden)]
204 pub fn set_on_open_change(&mut self, handler: Option<OpenChangeHandler>) {
205 self.on_open_change = handler;
206 }
207
208 #[doc(hidden)]
209 pub fn on_action_cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
210 self.dismiss(window, cx);
211 }
212}
213
214impl Focusable for PopoverState {
215 fn focus_handle(&self, _: &App) -> FocusHandle {
216 self.focus_handle.clone()
217 }
218}
219
220impl Render for PopoverState {
221 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
222 div()
223 }
224}
225
226impl EventEmitter<DismissEvent> for PopoverState {}
227
228type TriggerBuilder = Box<dyn FnOnce(bool, &Window, &App) -> AnyElement>;
229type ContentBuilder =
230 Box<dyn FnOnce(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> AnyElement>;
231
232#[derive(IntoElement)]
238pub struct Popover {
239 id: ElementId,
240 style: StyleRefinement,
241 anchor: Anchor,
242 offset: gpui::Pixels,
243 boundary: Option<gpui::Bounds<gpui::Pixels>>,
244 on_position: Option<Box<dyn Fn(ResolvedPosition, gpui::Bounds<gpui::Pixels>)>>,
245 default_open: bool,
246 open: Option<bool>,
247 tracked_focus_handle: Option<FocusHandle>,
248 trigger: Option<TriggerBuilder>,
249 content: Option<ContentBuilder>,
250 mouse_button: MouseButton,
251 overlay_closable: bool,
252 on_open_change: Option<OpenChangeHandler>,
253}
254
255impl Popover {
256 pub fn new(id: impl Into<ElementId>) -> Self {
257 Self {
258 id: id.into(),
259 style: StyleRefinement::default(),
260 anchor: Anchor::TopLeft,
261 offset: gpui::px(0.),
262 boundary: None,
263 on_position: None,
264 default_open: false,
265 open: None,
266 tracked_focus_handle: None,
267 trigger: None,
268 content: None,
269 mouse_button: MouseButton::Left,
270 overlay_closable: true,
271 on_open_change: None,
272 }
273 }
274
275 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
276 self.anchor = anchor.into();
277 self
278 }
279
280 pub fn offset(mut self, offset: gpui::Pixels) -> Self {
282 self.offset = offset;
283 self
284 }
285
286 pub fn boundary(mut self, boundary: gpui::Bounds<gpui::Pixels>) -> Self {
289 self.boundary = Some(boundary);
290 self
291 }
292
293 pub fn on_position(
295 mut self,
296 callback: impl Fn(ResolvedPosition, gpui::Bounds<gpui::Pixels>) + 'static,
297 ) -> Self {
298 self.on_position = Some(Box::new(callback));
299 self
300 }
301
302 pub fn mouse_button(mut self, mouse_button: MouseButton) -> Self {
303 self.mouse_button = mouse_button;
304 self
305 }
306
307 pub fn trigger<T>(mut self, trigger: T) -> Self
308 where
309 T: Selectable + IntoElement + 'static,
310 {
311 self.trigger = Some(Box::new(|is_open, _, _| {
312 let open = trigger.is_open();
313 trigger.open(open || is_open).into_any_element()
314 }));
315 self
316 }
317
318 #[doc(hidden)]
320 pub fn trigger_with(
321 mut self,
322 trigger: impl FnOnce(bool, &Window, &App) -> AnyElement + 'static,
323 ) -> Self {
324 self.trigger = Some(Box::new(trigger));
325 self
326 }
327
328 pub fn default_open(mut self, open: bool) -> Self {
329 self.default_open = open;
330 self
331 }
332
333 pub fn open(mut self, open: bool) -> Self {
334 self.open = Some(open);
335 self
336 }
337
338 pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
339 self.tracked_focus_handle = Some(handle.clone());
340 self
341 }
342
343 pub fn overlay_closable(mut self, closable: bool) -> Self {
344 self.overlay_closable = closable;
345 self
346 }
347
348 pub fn on_open_change(
349 mut self,
350 callback: impl Fn(&bool, &mut Window, &mut App) + 'static,
351 ) -> Self {
352 self.on_open_change = Some(Rc::new(callback));
353 self
354 }
355
356 pub fn content<F, E>(mut self, content: F) -> Self
357 where
358 E: IntoElement,
359 F: FnOnce(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> E + 'static,
360 {
361 self.content = Some(Box::new(move |state, window, cx| {
362 content(state, window, cx).into_any_element()
363 }));
364 self
365 }
366}
367
368impl Styled for Popover {
371 fn style(&mut self) -> &mut StyleRefinement {
372 &mut self.style
373 }
374}
375
376impl RenderOnce for Popover {
377 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
378 let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| {
379 PopoverState::new(self.default_open, cx)
380 });
381 state.update(cx, |state, cx| {
382 state.track_focus(self.tracked_focus_handle);
383 state.set_on_open_change(self.on_open_change);
384 if let Some(open) = self.open {
385 state.sync_open(open, window, cx);
386 }
387 });
388
389 let open = state.read(cx).is_open();
390 let focus_handle = state.read(cx).focus_handle(cx);
391 let Some(trigger) = self.trigger else {
392 return div().id("empty").into_any_element();
393 };
394 let parent_view_id = window.current_view();
395 let popup = Popup::new(self.id, trigger(open, window, cx))
396 .refine_style(&self.style)
397 .anchor(self.anchor)
398 .offset(self.offset)
399 .when_some(self.boundary, |this, boundary| this.boundary(boundary))
400 .when_some(self.on_position, |this, callback| {
401 this.on_position(callback)
402 })
403 .key_context(CONTEXT)
404 .on_action({
405 let state = state.clone();
406 move |_: &Confirm, window, cx| {
407 state.update(cx, |state, cx| state.toggle_open(window, cx));
408 cx.notify(parent_view_id);
409 }
410 })
411 .on_mouse_down(self.mouse_button, {
412 let state = state.clone();
413 move |_, window, cx| {
414 cx.stop_propagation();
415 state.update(cx, |state, cx| {
416 if state.is_open() == open {
417 state.toggle_open(window, cx);
418 }
419 });
420 cx.notify(parent_view_id);
421 }
422 });
423 if !open {
424 return popup.into_any_element();
425 }
426
427 let content = div()
428 .id("content")
429 .role(Role::Dialog)
433 .occlude()
434 .tab_group()
435 .track_focus(&focus_handle)
436 .key_context(CONTENT_CONTEXT)
437 .on_action(window.listener_for(&state, PopoverState::on_action_cancel))
438 .when_some(self.content, |this, content| {
439 this.child(state.update(cx, |state, cx| (content)(state, window, cx)))
440 })
441 .when(self.overlay_closable, |this| {
442 this.on_mouse_down_out({
443 let state = state.clone();
444 move |_, window, cx| {
445 if !state.read(cx).has_nested_popup(cx) {
446 state.update(cx, |state, cx| state.dismiss(window, cx));
447 cx.notify(parent_view_id);
448 return;
449 }
450 let state = state.clone();
455 window.defer(cx, move |window, cx| {
456 if !state.read(cx).has_nested_popup(cx) {
457 state.update(cx, |state, cx| state.dismiss(window, cx));
458 cx.notify(parent_view_id);
459 }
460 });
461 }
462 })
463 });
464 popup.content(content).into_any_element()
465 }
466}
467
468#[cfg(test)]
469mod tests {
470 use super::*;
471 use gpui::{AppContext as _, Context, Render, point, px};
472 use std::{cell::RefCell, rc::Rc};
473
474 #[gpui::test]
479 fn a_state_dropped_while_open_closes_the_deferred_context(cx: &mut gpui::TestAppContext) {
480 let state = cx.update(|cx| {
481 GlobalState::init(cx);
482 let state = cx.new(|cx| PopoverState::new(false, cx));
483 state.update(cx, |state, cx| state.set_open(true, cx));
484 assert!(GlobalState::is_in_deferred_context(cx));
485 state
486 });
487
488 cx.update(|_| drop(state));
489 cx.update(|cx| assert!(!GlobalState::is_in_deferred_context(cx)));
490 }
491
492 #[gpui::test]
493 fn open_state_registers_and_unregisters_deferred_context(cx: &mut gpui::TestAppContext) {
494 cx.update(|cx| {
495 GlobalState::init(cx);
496 let state = cx.new(|cx| PopoverState::new(false, cx));
497
498 state.update(cx, |state, cx| state.set_open(true, cx));
499 assert!(state.read(cx).is_open());
500 assert!(GlobalState::is_in_deferred_context(cx));
501
502 state.update(cx, |state, cx| state.set_open(false, cx));
503 assert!(!state.read(cx).is_open());
504 assert!(!GlobalState::is_in_deferred_context(cx));
505 });
506 }
507
508 struct PopoverHarness {
509 changes: Rc<RefCell<Vec<bool>>>,
510 default_open: bool,
511 }
512
513 struct KeyboardPopoverHarness {
514 trigger_focus: FocusHandle,
515 }
516
517 impl Render for KeyboardPopoverHarness {
518 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
519 Popover::new("keyboard-popover")
520 .trigger(
521 crate::Button::new("keyboard-trigger")
522 .track_focus(&self.trigger_focus)
523 .child("Open"),
524 )
525 .content(|_, _, _| {
526 div()
527 .debug_selector(|| "keyboard-popover-content".into())
528 .size(px(40.))
529 })
530 }
531 }
532
533 impl Render for PopoverHarness {
534 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
535 let changes = self.changes.clone();
536 Popover::new("base-popover")
537 .default_open(self.default_open)
538 .trigger_with(|_, _, _| div().child("Open").into_any_element())
539 .content(|_, _, _| {
540 div()
541 .debug_selector(|| "base-popover-content".into())
542 .size(px(40.))
543 })
544 .on_open_change(move |open, _, _| changes.borrow_mut().push(*open))
545 }
546 }
547
548 #[gpui::test]
549 fn unstyled_popover_owns_pointer_open_and_outside_dismiss(cx: &mut gpui::TestAppContext) {
550 cx.update(crate::init);
551 let changes = Rc::new(RefCell::new(Vec::new()));
552 let (_, cx) = cx.add_window_view({
553 let changes = changes.clone();
554 move |_, _| PopoverHarness {
555 changes,
556 default_open: false,
557 }
558 });
559 cx.update(|window, cx| window.draw(cx).clear(cx));
560 cx.update(|window, cx| assert!(window.focused(cx).is_none(), "nothing has focus yet"));
561
562 cx.simulate_click(point(px(20.), px(10.)), Default::default());
563 cx.update(|window, cx| window.draw(cx).clear(cx));
564 assert!(cx.debug_bounds("base-popover-content").is_some());
565 cx.update(|window, cx| assert!(window.focused(cx).is_some(), "the popover takes focus"));
566
567 cx.simulate_click(point(px(300.), px(300.)), Default::default());
568 cx.update(|window, cx| window.draw(cx).clear(cx));
569 assert!(cx.debug_bounds("base-popover-content").is_none());
570 assert_eq!(&*changes.borrow(), &[true, false]);
571 cx.update(|window, cx| {
574 assert!(
575 window.focused(cx).is_none(),
576 "focus stays on {:?}",
577 window.focused(cx)
578 )
579 });
580 }
581
582 struct NestedPopoverHarness;
583
584 impl Render for NestedPopoverHarness {
585 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
586 Popover::new("outer-popover")
587 .trigger_with(|_, _, _| div().size(px(40.)).child("Open").into_any_element())
588 .content(|_, _, _| {
589 div()
590 .debug_selector(|| "outer-popover-content".into())
591 .size(px(40.))
592 .child(
593 Popover::new("inner-popover")
594 .trigger_with(|_, _, _| {
595 div()
596 .debug_selector(|| "inner-popover-trigger".into())
597 .size(px(20.))
598 .into_any_element()
599 })
600 .content(|_, _, _| {
601 div()
602 .debug_selector(|| "inner-popover-content".into())
603 .size(px(120.))
604 }),
605 )
606 })
607 }
608 }
609
610 #[gpui::test]
614 fn a_press_in_a_nested_popup_keeps_the_popover_open(cx: &mut gpui::TestAppContext) {
615 cx.update(crate::init);
616 let (_, cx) = cx.add_window_view(|_, _| NestedPopoverHarness);
617 cx.update(|window, cx| window.draw(cx).clear(cx));
618
619 cx.simulate_click(point(px(20.), px(10.)), Default::default());
620 cx.update(|window, cx| window.draw(cx).clear(cx));
621 let outer = cx
622 .debug_bounds("outer-popover-content")
623 .expect("the outer popover opens");
624
625 let inner_trigger = cx
626 .debug_bounds("inner-popover-trigger")
627 .expect("the outer popover holds the inner trigger");
628 cx.simulate_click(inner_trigger.center(), Default::default());
629 cx.update(|window, cx| window.draw(cx).clear(cx));
630 let inner = cx
631 .debug_bounds("inner-popover-content")
632 .expect("the inner popover opens");
633
634 let in_inner_only = point(inner.right() - px(2.), inner.top() + px(2.));
635 assert!(
636 !outer.contains(&in_inner_only),
637 "the press must land outside the outer popover's bounds"
638 );
639 cx.simulate_click(in_inner_only, Default::default());
640 cx.update(|window, cx| window.draw(cx).clear(cx));
641 assert!(cx.debug_bounds("inner-popover-content").is_some());
642 assert!(
643 cx.debug_bounds("outer-popover-content").is_some(),
644 "a press in the nested popup must not dismiss the popover"
645 );
646
647 cx.simulate_click(point(px(300.), px(300.)), Default::default());
648 cx.update(|window, cx| window.draw(cx).clear(cx));
649 assert!(cx.debug_bounds("inner-popover-content").is_none());
650 assert!(
651 cx.debug_bounds("outer-popover-content").is_none(),
652 "a press outside both closes both"
653 );
654 }
655
656 #[gpui::test]
657 fn default_open_renders_content_without_activation(cx: &mut gpui::TestAppContext) {
658 cx.update(crate::init);
659 let (_, cx) = cx.add_window_view(|_, _| PopoverHarness {
660 changes: Rc::new(RefCell::new(Vec::new())),
661 default_open: true,
662 });
663 cx.update(|window, cx| window.draw(cx).clear(cx));
664 cx.update(|window, cx| window.draw(cx).clear(cx));
665 assert!(cx.debug_bounds("base-popover-content").is_some());
666 }
667
668 #[derive(IntoElement)]
672 struct RecordingTrigger {
673 calls: Rc<RefCell<Vec<(&'static str, bool)>>>,
674 selected: bool,
675 open: bool,
676 }
677
678 impl Selectable for RecordingTrigger {
679 fn selected(mut self, selected: bool) -> Self {
680 self.calls.borrow_mut().push(("selected", selected));
681 self.selected = selected;
682 self
683 }
684
685 fn is_selected(&self) -> bool {
686 self.selected
687 }
688
689 fn open(mut self, open: bool) -> Self {
690 self.calls.borrow_mut().push(("open", open));
691 self.open = open;
692 self
693 }
694
695 fn is_open(&self) -> bool {
696 self.open
697 }
698 }
699
700 impl RenderOnce for RecordingTrigger {
701 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
702 div().size(px(40.)).child("Open")
703 }
704 }
705
706 struct RecordingTriggerHarness {
707 calls: Rc<RefCell<Vec<(&'static str, bool)>>>,
708 }
709
710 impl Render for RecordingTriggerHarness {
711 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
712 Popover::new("recording-popover")
713 .trigger(RecordingTrigger {
714 calls: self.calls.clone(),
715 selected: false,
716 open: false,
717 })
718 .content(|_, _, _| div().size(px(40.)))
719 }
720 }
721
722 #[gpui::test]
723 fn an_open_popover_tells_its_trigger_it_is_open_not_selected(cx: &mut gpui::TestAppContext) {
724 cx.update(crate::init);
725 let calls = Rc::new(RefCell::new(Vec::new()));
726 let (_, cx) = cx.add_window_view({
727 let calls = calls.clone();
728 move |_, _| RecordingTriggerHarness { calls }
729 });
730 cx.update(|window, cx| window.draw(cx).clear(cx));
731 calls.borrow_mut().clear();
732
733 cx.simulate_click(point(px(20.), px(10.)), Default::default());
734 cx.update(|window, cx| window.draw(cx).clear(cx));
735
736 let calls = calls.borrow();
737 assert!(
738 calls.contains(&("open", true)),
739 "an open popover marks its trigger open, got {calls:?}"
740 );
741 assert!(
742 !calls.iter().any(|(name, _)| *name == "selected"),
743 "opening must not touch the trigger's own selection, got {calls:?}"
744 );
745 }
746
747 #[gpui::test]
748 fn keyboard_activation_opens_the_popover(cx: &mut gpui::TestAppContext) {
749 cx.update(crate::init);
750 let (view, cx) = cx.add_window_view(|_, cx| KeyboardPopoverHarness {
751 trigger_focus: cx.focus_handle(),
752 });
753 cx.update(|window, cx| window.draw(cx).clear(cx));
754
755 cx.update(|window, cx| {
756 let focus = view.read(cx).trigger_focus.clone();
757 focus.focus(window, cx);
758 });
759 cx.simulate_keystrokes("enter");
760 cx.update(|window, cx| window.draw(cx).clear(cx));
761
762 assert!(cx.debug_bounds("keyboard-popover-content").is_some());
763 }
764}