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 on_position: Option<Box<dyn Fn(ResolvedPosition, gpui::Bounds<gpui::Pixels>)>>,
244 default_open: bool,
245 open: Option<bool>,
246 tracked_focus_handle: Option<FocusHandle>,
247 trigger: Option<TriggerBuilder>,
248 content: Option<ContentBuilder>,
249 mouse_button: MouseButton,
250 overlay_closable: bool,
251 on_open_change: Option<OpenChangeHandler>,
252}
253
254impl Popover {
255 pub fn new(id: impl Into<ElementId>) -> Self {
256 Self {
257 id: id.into(),
258 style: StyleRefinement::default(),
259 anchor: Anchor::TopLeft,
260 offset: gpui::px(0.),
261 on_position: None,
262 default_open: false,
263 open: None,
264 tracked_focus_handle: None,
265 trigger: None,
266 content: None,
267 mouse_button: MouseButton::Left,
268 overlay_closable: true,
269 on_open_change: None,
270 }
271 }
272
273 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
274 self.anchor = anchor.into();
275 self
276 }
277
278 pub fn offset(mut self, offset: gpui::Pixels) -> Self {
280 self.offset = offset;
281 self
282 }
283
284 pub fn on_position(
286 mut self,
287 callback: impl Fn(ResolvedPosition, gpui::Bounds<gpui::Pixels>) + 'static,
288 ) -> Self {
289 self.on_position = Some(Box::new(callback));
290 self
291 }
292
293 pub fn mouse_button(mut self, mouse_button: MouseButton) -> Self {
294 self.mouse_button = mouse_button;
295 self
296 }
297
298 pub fn trigger<T>(mut self, trigger: T) -> Self
299 where
300 T: Selectable + IntoElement + 'static,
301 {
302 self.trigger = Some(Box::new(|is_open, _, _| {
303 let open = trigger.is_open();
304 trigger.open(open || is_open).into_any_element()
305 }));
306 self
307 }
308
309 #[doc(hidden)]
311 pub fn trigger_with(
312 mut self,
313 trigger: impl FnOnce(bool, &Window, &App) -> AnyElement + 'static,
314 ) -> Self {
315 self.trigger = Some(Box::new(trigger));
316 self
317 }
318
319 pub fn default_open(mut self, open: bool) -> Self {
320 self.default_open = open;
321 self
322 }
323
324 pub fn open(mut self, open: bool) -> Self {
325 self.open = Some(open);
326 self
327 }
328
329 pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
330 self.tracked_focus_handle = Some(handle.clone());
331 self
332 }
333
334 pub fn overlay_closable(mut self, closable: bool) -> Self {
335 self.overlay_closable = closable;
336 self
337 }
338
339 pub fn on_open_change(
340 mut self,
341 callback: impl Fn(&bool, &mut Window, &mut App) + 'static,
342 ) -> Self {
343 self.on_open_change = Some(Rc::new(callback));
344 self
345 }
346
347 pub fn content<F, E>(mut self, content: F) -> Self
348 where
349 E: IntoElement,
350 F: FnOnce(&mut PopoverState, &mut Window, &mut Context<PopoverState>) -> E + 'static,
351 {
352 self.content = Some(Box::new(move |state, window, cx| {
353 content(state, window, cx).into_any_element()
354 }));
355 self
356 }
357}
358
359impl Styled for Popover {
362 fn style(&mut self) -> &mut StyleRefinement {
363 &mut self.style
364 }
365}
366
367impl RenderOnce for Popover {
368 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
369 let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| {
370 PopoverState::new(self.default_open, cx)
371 });
372 state.update(cx, |state, cx| {
373 state.track_focus(self.tracked_focus_handle);
374 state.set_on_open_change(self.on_open_change);
375 if let Some(open) = self.open {
376 state.sync_open(open, window, cx);
377 }
378 });
379
380 let open = state.read(cx).is_open();
381 let focus_handle = state.read(cx).focus_handle(cx);
382 let Some(trigger) = self.trigger else {
383 return div().id("empty").into_any_element();
384 };
385 let parent_view_id = window.current_view();
386 let popup = Popup::new(self.id, trigger(open, window, cx))
387 .refine_style(&self.style)
388 .anchor(self.anchor)
389 .offset(self.offset)
390 .when_some(self.on_position, |this, callback| {
391 this.on_position(callback)
392 })
393 .key_context(CONTEXT)
394 .on_action({
395 let state = state.clone();
396 move |_: &Confirm, window, cx| {
397 state.update(cx, |state, cx| state.toggle_open(window, cx));
398 cx.notify(parent_view_id);
399 }
400 })
401 .on_mouse_down(self.mouse_button, {
402 let state = state.clone();
403 move |_, window, cx| {
404 cx.stop_propagation();
405 state.update(cx, |state, cx| {
406 if state.is_open() == open {
407 state.toggle_open(window, cx);
408 }
409 });
410 cx.notify(parent_view_id);
411 }
412 });
413 if !open {
414 return popup.into_any_element();
415 }
416
417 let content = div()
418 .id("content")
419 .role(Role::Dialog)
423 .occlude()
424 .tab_group()
425 .track_focus(&focus_handle)
426 .key_context(CONTENT_CONTEXT)
427 .on_action(window.listener_for(&state, PopoverState::on_action_cancel))
428 .when_some(self.content, |this, content| {
429 this.child(state.update(cx, |state, cx| (content)(state, window, cx)))
430 })
431 .when(self.overlay_closable, |this| {
432 this.on_mouse_down_out({
433 let state = state.clone();
434 move |_, window, cx| {
435 if !state.read(cx).has_nested_popup(cx) {
436 state.update(cx, |state, cx| state.dismiss(window, cx));
437 cx.notify(parent_view_id);
438 return;
439 }
440 let state = state.clone();
445 window.defer(cx, move |window, cx| {
446 if !state.read(cx).has_nested_popup(cx) {
447 state.update(cx, |state, cx| state.dismiss(window, cx));
448 cx.notify(parent_view_id);
449 }
450 });
451 }
452 })
453 });
454 popup.content(content).into_any_element()
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461 use gpui::{AppContext as _, Context, Render, point, px};
462 use std::{cell::RefCell, rc::Rc};
463
464 #[gpui::test]
469 fn a_state_dropped_while_open_closes_the_deferred_context(cx: &mut gpui::TestAppContext) {
470 let state = cx.update(|cx| {
471 GlobalState::init(cx);
472 let state = cx.new(|cx| PopoverState::new(false, cx));
473 state.update(cx, |state, cx| state.set_open(true, cx));
474 assert!(GlobalState::is_in_deferred_context(cx));
475 state
476 });
477
478 cx.update(|_| drop(state));
479 cx.update(|cx| assert!(!GlobalState::is_in_deferred_context(cx)));
480 }
481
482 #[gpui::test]
483 fn open_state_registers_and_unregisters_deferred_context(cx: &mut gpui::TestAppContext) {
484 cx.update(|cx| {
485 GlobalState::init(cx);
486 let state = cx.new(|cx| PopoverState::new(false, cx));
487
488 state.update(cx, |state, cx| state.set_open(true, cx));
489 assert!(state.read(cx).is_open());
490 assert!(GlobalState::is_in_deferred_context(cx));
491
492 state.update(cx, |state, cx| state.set_open(false, cx));
493 assert!(!state.read(cx).is_open());
494 assert!(!GlobalState::is_in_deferred_context(cx));
495 });
496 }
497
498 struct PopoverHarness {
499 changes: Rc<RefCell<Vec<bool>>>,
500 default_open: bool,
501 }
502
503 struct KeyboardPopoverHarness {
504 trigger_focus: FocusHandle,
505 }
506
507 impl Render for KeyboardPopoverHarness {
508 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
509 Popover::new("keyboard-popover")
510 .trigger(
511 crate::Button::new("keyboard-trigger")
512 .track_focus(&self.trigger_focus)
513 .child("Open"),
514 )
515 .content(|_, _, _| {
516 div()
517 .debug_selector(|| "keyboard-popover-content".into())
518 .size(px(40.))
519 })
520 }
521 }
522
523 impl Render for PopoverHarness {
524 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
525 let changes = self.changes.clone();
526 Popover::new("base-popover")
527 .default_open(self.default_open)
528 .trigger_with(|_, _, _| div().child("Open").into_any_element())
529 .content(|_, _, _| {
530 div()
531 .debug_selector(|| "base-popover-content".into())
532 .size(px(40.))
533 })
534 .on_open_change(move |open, _, _| changes.borrow_mut().push(*open))
535 }
536 }
537
538 #[gpui::test]
539 fn unstyled_popover_owns_pointer_open_and_outside_dismiss(cx: &mut gpui::TestAppContext) {
540 cx.update(crate::init);
541 let changes = Rc::new(RefCell::new(Vec::new()));
542 let (_, cx) = cx.add_window_view({
543 let changes = changes.clone();
544 move |_, _| PopoverHarness {
545 changes,
546 default_open: false,
547 }
548 });
549 cx.update(|window, cx| window.draw(cx).clear(cx));
550 cx.update(|window, cx| assert!(window.focused(cx).is_none(), "nothing has focus yet"));
551
552 cx.simulate_click(point(px(20.), px(10.)), Default::default());
553 cx.update(|window, cx| window.draw(cx).clear(cx));
554 assert!(cx.debug_bounds("base-popover-content").is_some());
555 cx.update(|window, cx| assert!(window.focused(cx).is_some(), "the popover takes focus"));
556
557 cx.simulate_click(point(px(300.), px(300.)), Default::default());
558 cx.update(|window, cx| window.draw(cx).clear(cx));
559 assert!(cx.debug_bounds("base-popover-content").is_none());
560 assert_eq!(&*changes.borrow(), &[true, false]);
561 cx.update(|window, cx| {
564 assert!(
565 window.focused(cx).is_none(),
566 "focus stays on {:?}",
567 window.focused(cx)
568 )
569 });
570 }
571
572 struct NestedPopoverHarness;
573
574 impl Render for NestedPopoverHarness {
575 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
576 Popover::new("outer-popover")
577 .trigger_with(|_, _, _| div().size(px(40.)).child("Open").into_any_element())
578 .content(|_, _, _| {
579 div()
580 .debug_selector(|| "outer-popover-content".into())
581 .size(px(40.))
582 .child(
583 Popover::new("inner-popover")
584 .trigger_with(|_, _, _| {
585 div()
586 .debug_selector(|| "inner-popover-trigger".into())
587 .size(px(20.))
588 .into_any_element()
589 })
590 .content(|_, _, _| {
591 div()
592 .debug_selector(|| "inner-popover-content".into())
593 .size(px(120.))
594 }),
595 )
596 })
597 }
598 }
599
600 #[gpui::test]
604 fn a_press_in_a_nested_popup_keeps_the_popover_open(cx: &mut gpui::TestAppContext) {
605 cx.update(crate::init);
606 let (_, cx) = cx.add_window_view(|_, _| NestedPopoverHarness);
607 cx.update(|window, cx| window.draw(cx).clear(cx));
608
609 cx.simulate_click(point(px(20.), px(10.)), Default::default());
610 cx.update(|window, cx| window.draw(cx).clear(cx));
611 let outer = cx
612 .debug_bounds("outer-popover-content")
613 .expect("the outer popover opens");
614
615 let inner_trigger = cx
616 .debug_bounds("inner-popover-trigger")
617 .expect("the outer popover holds the inner trigger");
618 cx.simulate_click(inner_trigger.center(), Default::default());
619 cx.update(|window, cx| window.draw(cx).clear(cx));
620 let inner = cx
621 .debug_bounds("inner-popover-content")
622 .expect("the inner popover opens");
623
624 let in_inner_only = point(inner.right() - px(2.), inner.top() + px(2.));
625 assert!(
626 !outer.contains(&in_inner_only),
627 "the press must land outside the outer popover's bounds"
628 );
629 cx.simulate_click(in_inner_only, Default::default());
630 cx.update(|window, cx| window.draw(cx).clear(cx));
631 assert!(cx.debug_bounds("inner-popover-content").is_some());
632 assert!(
633 cx.debug_bounds("outer-popover-content").is_some(),
634 "a press in the nested popup must not dismiss the popover"
635 );
636
637 cx.simulate_click(point(px(300.), px(300.)), Default::default());
638 cx.update(|window, cx| window.draw(cx).clear(cx));
639 assert!(cx.debug_bounds("inner-popover-content").is_none());
640 assert!(
641 cx.debug_bounds("outer-popover-content").is_none(),
642 "a press outside both closes both"
643 );
644 }
645
646 #[gpui::test]
647 fn default_open_renders_content_without_activation(cx: &mut gpui::TestAppContext) {
648 cx.update(crate::init);
649 let (_, cx) = cx.add_window_view(|_, _| PopoverHarness {
650 changes: Rc::new(RefCell::new(Vec::new())),
651 default_open: true,
652 });
653 cx.update(|window, cx| window.draw(cx).clear(cx));
654 cx.update(|window, cx| window.draw(cx).clear(cx));
655 assert!(cx.debug_bounds("base-popover-content").is_some());
656 }
657
658 #[derive(IntoElement)]
662 struct RecordingTrigger {
663 calls: Rc<RefCell<Vec<(&'static str, bool)>>>,
664 selected: bool,
665 open: bool,
666 }
667
668 impl Selectable for RecordingTrigger {
669 fn selected(mut self, selected: bool) -> Self {
670 self.calls.borrow_mut().push(("selected", selected));
671 self.selected = selected;
672 self
673 }
674
675 fn is_selected(&self) -> bool {
676 self.selected
677 }
678
679 fn open(mut self, open: bool) -> Self {
680 self.calls.borrow_mut().push(("open", open));
681 self.open = open;
682 self
683 }
684
685 fn is_open(&self) -> bool {
686 self.open
687 }
688 }
689
690 impl RenderOnce for RecordingTrigger {
691 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
692 div().size(px(40.)).child("Open")
693 }
694 }
695
696 struct RecordingTriggerHarness {
697 calls: Rc<RefCell<Vec<(&'static str, bool)>>>,
698 }
699
700 impl Render for RecordingTriggerHarness {
701 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
702 Popover::new("recording-popover")
703 .trigger(RecordingTrigger {
704 calls: self.calls.clone(),
705 selected: false,
706 open: false,
707 })
708 .content(|_, _, _| div().size(px(40.)))
709 }
710 }
711
712 #[gpui::test]
713 fn an_open_popover_tells_its_trigger_it_is_open_not_selected(cx: &mut gpui::TestAppContext) {
714 cx.update(crate::init);
715 let calls = Rc::new(RefCell::new(Vec::new()));
716 let (_, cx) = cx.add_window_view({
717 let calls = calls.clone();
718 move |_, _| RecordingTriggerHarness { calls }
719 });
720 cx.update(|window, cx| window.draw(cx).clear(cx));
721 calls.borrow_mut().clear();
722
723 cx.simulate_click(point(px(20.), px(10.)), Default::default());
724 cx.update(|window, cx| window.draw(cx).clear(cx));
725
726 let calls = calls.borrow();
727 assert!(
728 calls.contains(&("open", true)),
729 "an open popover marks its trigger open, got {calls:?}"
730 );
731 assert!(
732 !calls.iter().any(|(name, _)| *name == "selected"),
733 "opening must not touch the trigger's own selection, got {calls:?}"
734 );
735 }
736
737 #[gpui::test]
738 fn keyboard_activation_opens_the_popover(cx: &mut gpui::TestAppContext) {
739 cx.update(crate::init);
740 let (view, cx) = cx.add_window_view(|_, cx| KeyboardPopoverHarness {
741 trigger_focus: cx.focus_handle(),
742 });
743 cx.update(|window, cx| window.draw(cx).clear(cx));
744
745 cx.update(|window, cx| {
746 let focus = view.read(cx).trigger_focus.clone();
747 focus.focus(window, cx);
748 });
749 cx.simulate_keystrokes("enter");
750 cx.update(|window, cx| window.draw(cx).clear(cx));
751
752 assert!(cx.debug_bounds("keyboard-popover-content").is_some());
753 }
754}