1use std::{cell::Cell, rc::Rc};
6
7use gpui::{
8 Anchor, AnyElement, App, Bounds, ClickEvent, Context, ElementId, Entity, FocusHandle,
9 HitboxBehavior, InteractiveElement as _, IntoElement, KeyBinding, MouseButton, MouseDownEvent,
10 ParentElement as _, Pixels, Point, RenderOnce, Role, SharedString,
11 StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Window, anchored,
12 canvas, deferred, div, point, prelude::FluentBuilder as _, px,
13};
14
15use crate::{
16 Align, Button, POPUP_PRIORITY, Placement, Popup, StyledExt as _, TestSupportExt as _,
17 actions::Cancel,
18 global_state::{DeferredPopover, GlobalState},
19};
20
21const CONTEXT: &str = "Popover";
22
23pub(crate) fn init(cx: &mut App) {
24 cx.bind_keys([KeyBinding::new("escape", Cancel, Some(CONTEXT))]);
25}
26
27pub struct PopoverState {
34 open: bool,
35 disabled: bool,
36 focus: FocusHandle,
37 content_focus: FocusHandle,
38 initial_focus: Option<FocusHandle>,
39 initial_focus_builder: Option<Box<dyn Fn(&mut Window, &mut App) -> FocusHandle>>,
40 open_on_pointer_down: bool,
41 deferred_context: Option<DeferredPopover>,
42 dismiss_subscription: Option<Subscription>,
43}
44
45impl PopoverState {
46 pub fn new(cx: &mut Context<Self>) -> Self {
47 Self {
48 open: false,
49 disabled: false,
50 focus: cx.focus_handle().tab_stop(true),
51 content_focus: cx.focus_handle(),
52 initial_focus: None,
53 initial_focus_builder: None,
54 open_on_pointer_down: false,
55 deferred_context: None,
56 dismiss_subscription: None,
57 }
58 }
59
60 pub fn with_initial_focus(mut self, focus: &FocusHandle) -> Self {
62 self.initial_focus = Some(focus.clone());
63 self
64 }
65
66 pub(crate) fn with_initial_focus_builder(
70 mut self,
71 build: impl Fn(&mut Window, &mut App) -> FocusHandle + 'static,
72 ) -> Self {
73 self.initial_focus_builder = Some(Box::new(build));
74 self
75 }
76
77 pub fn is_open(&self) -> bool {
78 self.open
79 }
80
81 pub fn is_disabled(&self) -> bool {
82 self.disabled
83 }
84
85 pub fn focus_handle(&self) -> &FocusHandle {
87 &self.focus
88 }
89
90 pub fn content_focus_handle(&self) -> &FocusHandle {
92 &self.content_focus
93 }
94
95 pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
96 if self.disabled == disabled {
97 return;
98 }
99 if disabled {
100 self.close(window, cx);
101 }
102 self.disabled = disabled;
103 cx.notify();
104 window.refresh();
105 }
106
107 pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
108 if self.disabled || self.open {
109 return;
110 }
111 if let Some(build) = &self.initial_focus_builder {
112 self.initial_focus = Some(build(window, cx));
113 }
114 self.open = true;
115 self.deferred_context = Some(GlobalState::register_deferred_popover(cx));
116 self.dismiss_subscription =
117 Some(
118 cx.on_focus_out(&self.content_focus, window, |_, event, window, cx| {
119 cx.defer_in(window, move |state, window, cx| {
123 let detached = event
124 .blurred
125 .upgrade()
126 .is_some_and(|focus| focus.is_focused(window));
127 if !window.is_window_active()
128 || detached
129 || !state.content_focus.contains_focused(window, cx)
130 {
131 state.dismiss(window, cx);
132 }
133 });
134 }),
135 );
136 self.initial_focus
137 .as_ref()
138 .unwrap_or(&self.content_focus)
139 .focus(window, cx);
140 cx.notify();
141 window.refresh();
142 }
143
144 pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
146 if !self.open {
147 return;
148 }
149 if self.content_focus.contains_focused(window, cx)
150 || self
151 .initial_focus
152 .as_ref()
153 .is_some_and(|focus| focus.is_focused(window))
154 {
155 self.focus.focus(window, cx);
156 }
157 self.dismiss(window, cx);
158 }
159
160 fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
161 if !self.open {
162 return;
163 }
164 self.open = false;
165 self.deferred_context = None;
166 self.dismiss_subscription = None;
167 cx.notify();
168 window.refresh();
169 }
170
171 fn activate(&mut self, event: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
172 let was_open = match event {
175 ClickEvent::Mouse(_) => self.open_on_pointer_down,
176 ClickEvent::Keyboard(_) => self.open,
177 ClickEvent::Touch(_) => self.open,
180 };
181 if was_open {
182 self.close(window, cx);
183 } else {
184 self.open(window, cx);
185 }
186 }
187
188 pub(crate) fn tab(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
189 let trap = crate::active_focus_trap(window, cx);
190 let previous = window.focused(cx);
191 if forward {
192 window.focus_next(cx);
193 } else {
194 window.focus_prev(cx);
195 }
196 if window.focused(cx) != previous && self.content_focus.contains_focused(window, cx) {
197 return;
198 }
199
200 self.focus.focus(window, cx);
205 self.dismiss(window, cx);
206 if forward {
207 let mut visited = Vec::new();
208 loop {
209 window.focus_next(cx);
210 let focused = window.focused(cx);
211 if visited.contains(&focused) {
212 self.focus.focus(window, cx);
213 break;
214 }
215 visited.push(focused);
216 if !self.content_focus.contains_focused(window, cx)
217 && trap
218 .as_ref()
219 .is_none_or(|trap| trap.contains_focused(window, cx))
220 {
221 break;
222 }
223 }
224 }
225 }
226}
227
228#[derive(IntoElement)]
235pub struct Popover {
236 id: ElementId,
237 state: Entity<PopoverState>,
238 trigger: Button,
239 supplied_trigger: Option<AnyElement>,
240 position: Option<Point<Pixels>>,
241 content: Option<AnyElement>,
242 label: Option<SharedString>,
243 content_role: Option<Role>,
244 anchor: Anchor,
245 side: Option<Placement>,
246 align: Align,
247 offset: Pixels,
248 style: StyleRefinement,
249}
250
251impl Popover {
252 pub fn new(id: impl Into<ElementId>, state: &Entity<PopoverState>) -> Self {
253 let id = id.into();
254 Self {
255 trigger: Button::new(id.clone()),
256 supplied_trigger: None,
257 position: None,
258 id,
259 state: state.clone(),
260 content: None,
261 label: None,
262 content_role: Some(Role::Dialog),
263 anchor: Anchor::TopLeft,
264 side: None,
265 align: Align::Center,
266 offset: px(0.),
267 style: StyleRefinement::default(),
268 }
269 }
270
271 pub fn trigger(mut self, build: impl FnOnce(Button) -> Button) -> Self {
272 self.trigger = build(self.trigger);
273 self
274 }
275
276 pub(crate) fn supplied_trigger(mut self, trigger: impl IntoElement) -> Self {
279 self.supplied_trigger = Some(trigger.into_any_element());
280 self
281 }
282
283 pub(crate) fn at_position(mut self, position: Point<Pixels>) -> Self {
284 self.position = Some(position);
285 self.side = None;
286 self
287 }
288
289 pub fn content(mut self, content: impl IntoElement) -> Self {
290 self.content = Some(content.into_any_element());
291 self
292 }
293
294 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
296 self.label = Some(label.into());
297 self
298 }
299
300 pub(crate) fn content_role(mut self, role: Option<Role>) -> Self {
303 self.content_role = role;
304 self
305 }
306
307 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
309 self.anchor = anchor.into();
310 self.side = None;
311 self
312 }
313
314 pub fn side(mut self, side: Placement) -> Self {
317 self.side = Some(side);
318 self.position = None;
319 self
320 }
321
322 pub fn align(mut self, align: Align) -> Self {
325 self.align = align;
326 self.side.get_or_insert(Placement::Bottom);
327 self.position = None;
328 self
329 }
330
331 pub fn offset(mut self, offset: Pixels) -> Self {
333 self.offset = offset;
334 self
335 }
336}
337
338impl Styled for Popover {
339 fn style(&mut self) -> &mut StyleRefinement {
340 &mut self.style
341 }
342}
343
344impl RenderOnce for Popover {
345 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
346 let model = self.state.read(cx);
347 let open = model.open;
348 let disabled = model.disabled;
349 let focus = model.focus.clone();
350 let content_focus = model.content_focus.clone();
351 let press_state = self.state.clone();
352 let trigger_state = self.state.clone();
353 let trigger = if let Some(trigger) = self.supplied_trigger {
354 trigger
355 } else {
356 self.trigger
357 .role(Role::Button)
358 .track_focus(&focus)
359 .focusable(true)
360 .tab_stop(true)
361 .disabled(disabled)
362 .aria_expanded(open)
363 .when(!disabled, |this| {
364 this.on_mouse_down(MouseButton::Left, move |_, _, cx| {
365 press_state.update(cx, |state, _| {
366 state.open_on_pointer_down = state.open;
367 });
368 })
369 })
370 .on_click(move |event, window, cx| {
371 trigger_state.update(cx, |state, cx| state.activate(event, window, cx));
372 })
373 .into_any_element()
374 };
375 let trigger_bounds = Rc::new(Cell::new(Bounds::<Pixels>::default()));
376 let position_bounds = trigger_bounds.clone();
377 let mut popup = Popup::new((self.id, "popover-host"), trigger)
378 .anchor(self.anchor)
379 .when_some(self.side, |popup, side| popup.side(side).align(self.align))
380 .offset(self.offset)
381 .when_some(self.position, |popup, position| popup.at_position(position))
382 .on_position(move |_, bounds| position_bounds.set(bounds));
383
384 let mut host = div().refine_style(&self.style);
385 if open {
386 let cancel_state = self.state.clone();
387 let tab_state = self.state.clone();
388 let previous_state = self.state.clone();
389 popup = popup.content(
390 div()
391 .id(("popover-content", self.state.entity_id()))
392 .test_support()
393 .when_some(self.content_role, |this, role| this.role(role))
394 .when_some(self.label, |this, label| this.aria_label(label))
395 .track_focus(&content_focus)
396 .key_context(CONTEXT)
397 .on_action(move |_: &Cancel, window, cx| {
398 cx.stop_propagation();
399 cancel_state.update(cx, |state, cx| state.close(window, cx));
400 })
401 .on_action(move |_: &crate::root::Tab, window, cx| {
402 tab_state.update(cx, |state, cx| state.tab(true, window, cx));
403 })
404 .on_action(move |_: &crate::root::TabPrev, window, cx| {
405 previous_state.update(cx, |state, cx| state.tab(false, window, cx));
406 })
407 .children(self.content),
408 );
409
410 let viewport = window.viewport_size();
411 let outside_state = self.state;
412 host = host.child(
418 deferred(
419 anchored().position(point(px(0.), px(0.))).child(
420 canvas(
421 |bounds, window, _| {
422 window.insert_hitbox(bounds, HitboxBehavior::Normal)
423 },
424 move |_, hitbox, window, _| {
425 window.on_mouse_event(
426 move |event: &MouseDownEvent, phase, window, cx| {
427 if phase.bubble()
428 && hitbox.is_hovered(window)
429 && !trigger_bounds.get().contains(&event.position)
430 {
431 outside_state.update(cx, |state, cx| {
432 state.close(window, cx);
433 });
434 }
435 },
436 );
437 },
438 )
439 .absolute()
440 .top_0()
441 .left_0()
442 .w(viewport.width)
443 .h(viewport.height),
444 ),
445 )
446 .with_priority(POPUP_PRIORITY - 1),
447 );
448 }
449 host.child(popup)
450 }
451}
452
453#[cfg(test)]
454mod tests {
455 use super::*;
456 use crate::{
457 Dialog, DialogBackdrop, DialogPopup, DialogState, Input, InputBase, InputState, Root,
458 Select, SelectItem, SelectOption, SelectState,
459 };
460 use gpui::{
461 AppContext as _, Focusable as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
462 TestAppContext, VisualTestContext,
463 };
464
465 struct Harness {
466 popover: Entity<PopoverState>,
467 dialog: Entity<DialogState>,
468 input: Entity<InputState>,
469 select: Entity<SelectState>,
470 outside: FocusHandle,
471 first: FocusHandle,
472 last: FocusHandle,
473 after: FocusHandle,
474 show_host: bool,
475 show_select: bool,
476 trailing: bool,
477 activations: usize,
478 _subscriptions: Vec<Subscription>,
479 }
480
481 impl Render for Harness {
482 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
483 let content = div()
484 .debug_selector(|| "popover-panel".into())
485 .w(px(180.))
486 .p(px(8.))
487 .flex()
488 .flex_col()
489 .gap(px(8.))
490 .child(
491 Button::new("inside-first")
492 .track_focus(&self.first)
493 .h(px(28.))
494 .child("First")
495 .on_click(cx.listener(|this, _, _, cx| {
496 this.activations += 1;
497 cx.notify();
498 })),
499 )
500 .child(
501 Button::new("inside-last")
502 .track_focus(&self.last)
503 .h(px(28.))
504 .child("Last"),
505 )
506 .when(self.show_select, |this| {
507 this.child(
508 Select::new("nested-select", &self.select)
509 .accessibility_label("Nested choice")
510 .trigger(div().h(px(28.)).child("Choose"))
511 .content(
512 div().w(px(164.)).flex().flex_col().children(
513 ["One", "Two"]
514 .into_iter()
515 .enumerate()
516 .map(|(index, label)| {
517 SelectOption::new(&self.select, index).h(px(32.)).child(
518 div()
519 .debug_selector(move || {
520 format!("nested-option-{index}").into()
521 })
522 .size_full()
523 .child(label),
524 )
525 }),
526 ),
527 ),
528 )
529 });
530 let popup = DialogPopup::new()
531 .w(px(360.))
532 .h(px(350.))
533 .p(px(12.))
534 .flex()
535 .flex_col()
536 .gap(px(12.))
537 .child(
538 InputBase::new("outside-input")
539 .debug_selector(|| "outside-input".into())
540 .h(px(32.))
541 .child(Input::new(&self.input)),
542 )
543 .when(self.show_host, |this| {
544 this.child(
545 Popover::new("popover-trigger", &self.popover)
546 .accessibility_label("Quick tools")
547 .trigger(|button| {
548 button
549 .debug_selector(|| "popover-trigger".into())
550 .accessibility_label("Open quick tools")
551 .h(px(32.))
552 .child("Quick tools")
553 })
554 .content(content),
555 )
556 })
557 .when(self.trailing, |this| {
558 this.child(
559 Button::new("after-popover")
560 .track_focus(&self.after)
561 .h(px(28.))
562 .child("After"),
563 )
564 });
565
566 div()
567 .size_full()
568 .child(
569 Button::new("outside-dialog")
570 .track_focus(&self.outside)
571 .w(px(120.))
572 .h(px(28.))
573 .child("Outside dialog"),
574 )
575 .child(
576 Dialog::new(&self.dialog)
577 .accessibility_label("Parent dialog")
578 .backdrop(DialogBackdrop::new().size_full())
579 .popup(popup),
580 )
581 }
582 }
583
584 fn draw(cx: &mut VisualTestContext) {
585 cx.update(|window, cx| window.draw(cx).clear(cx));
586 }
587
588 fn settle(cx: &mut VisualTestContext) {
589 draw(cx);
590 cx.run_until_parked();
591 draw(cx);
592 }
593
594 fn press(cx: &mut VisualTestContext, key: &str) {
595 let keystroke =
596 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
597 cx.simulate_event(KeyDownEvent {
598 keystroke: keystroke.clone(),
599 is_held: false,
600 prefer_character_input: false,
601 });
602 cx.simulate_event(KeyUpEvent { keystroke });
603 settle(cx);
604 }
605
606 fn harness(
607 cx: &mut TestAppContext,
608 initial_focus: bool,
609 ) -> (&mut VisualTestContext, Entity<Harness>) {
610 cx.update(crate::init);
611 let (root, cx) = cx.add_window_view(move |window, cx| {
612 let controls = cx.new(|cx| {
613 let first = cx.focus_handle();
614 let popover = cx.new(|cx| {
615 let state = PopoverState::new(cx);
616 if initial_focus {
617 state.with_initial_focus(&first)
618 } else {
619 state
620 }
621 });
622 let input = cx.new(|cx| InputState::new(window, cx).default_value("Outside"));
623 let dialog =
624 cx.new(|cx| DialogState::new(cx).with_initial_focus(&input.focus_handle(cx)));
625 let select = cx.new(|cx| {
626 SelectState::new(
627 [SelectItem::new("one", "One"), SelectItem::new("two", "Two")],
628 cx,
629 )
630 .default_value("one")
631 });
632 let subscriptions = vec![
633 cx.observe(&popover, |_, _, cx| cx.notify()),
634 cx.observe(&dialog, |_, _, cx| cx.notify()),
635 cx.observe(&select, |_, _, cx| cx.notify()),
636 ];
637 Harness {
638 popover,
639 dialog,
640 input,
641 select,
642 outside: cx.focus_handle(),
643 first,
644 last: cx.focus_handle(),
645 after: cx.focus_handle(),
646 show_host: true,
647 show_select: false,
648 trailing: true,
649 activations: 0,
650 _subscriptions: subscriptions,
651 }
652 });
653 Root::new(controls, window, cx)
654 });
655 let controls = root
656 .read_with(cx, |root, _| root.view().clone())
657 .downcast::<Harness>()
658 .unwrap();
659 cx.update(|window, cx| {
660 window.activate_window();
661 window.draw(cx).clear(cx);
662 let outside = controls.read(cx).outside.clone();
663 outside.focus(window, cx);
664 let dialog = controls.read(cx).dialog.clone();
665 dialog.update(cx, |state, cx| state.open(window, cx));
666 });
667 settle(cx);
668 (cx, controls)
669 }
670
671 fn open(cx: &mut VisualTestContext, controls: &Entity<Harness>) {
672 cx.update(|window, cx| {
673 let focus = controls.read(cx).popover.read(cx).focus_handle().clone();
674 focus.focus(window, cx);
675 });
676 draw(cx);
677 press(cx, "enter");
678 cx.update(|_, cx| assert!(controls.read(cx).popover.read(cx).is_open()));
679 }
680
681 #[gpui::test]
682 fn native_trigger_and_content_activation_remain_separate(cx: &mut TestAppContext) {
683 let (cx, controls) = harness(cx, true);
684 open(cx, &controls);
685 #[cfg(feature = "test-support")]
686 cx.update(|window, cx| {
687 let controls = controls.read(cx);
688 let modal = crate::test_support::find(
689 window,
690 &[],
691 &("dialog", controls.dialog.entity_id()).into(),
692 )
693 .unwrap();
694 let popover = crate::test_support::find(
695 window,
696 &[],
697 &("popover-content", controls.popover.entity_id()).into(),
698 )
699 .unwrap();
700 assert!(modal.modal());
701 assert_eq!(popover.role(), Some(Role::Dialog));
702 assert!(!popover.modal());
703 });
704 cx.update(|window, cx| assert!(controls.read(cx).first.is_focused(window)));
705 press(cx, "enter");
706 press(cx, "space");
707 cx.update(|_, cx| {
708 assert_eq!(controls.read(cx).activations, 2);
709 assert!(controls.read(cx).popover.read(cx).is_open());
710 });
711
712 press(cx, "escape");
713 cx.update(|window, cx| {
714 let controls = controls.read(cx);
715 assert!(!controls.popover.read(cx).is_open());
716 assert!(controls.dialog.read(cx).is_open());
717 assert!(controls.popover.read(cx).focus_handle().is_focused(window));
718 });
719 press(cx, "space");
720 cx.update(|_, cx| assert!(controls.read(cx).popover.read(cx).is_open()));
721
722 let trigger = cx.debug_bounds("popover-trigger").unwrap().center();
725 cx.simulate_mouse_down(trigger, MouseButton::Left, Modifiers::default());
726 settle(cx);
727 cx.simulate_mouse_up(trigger, MouseButton::Left, Modifiers::default());
728 settle(cx);
729 cx.update(|window, cx| {
730 let controls = controls.read(cx);
731 assert!(!controls.popover.read(cx).is_open());
732 assert!(controls.popover.read(cx).focus_handle().is_focused(window));
733 assert!(controls.dialog.read(cx).is_open());
734 });
735 cx.simulate_click(trigger, Modifiers::default());
736 settle(cx);
737 cx.update(|_, cx| assert!(controls.read(cx).popover.read(cx).is_open()));
738 }
739
740 #[gpui::test]
741 fn last_trigger_in_a_modal_skips_closed_content_and_background(cx: &mut TestAppContext) {
742 let (cx, controls) = harness(cx, true);
743 controls.update(cx, |controls, cx| {
744 controls.trailing = false;
745 cx.notify();
746 });
747 settle(cx);
748 open(cx, &controls);
749 press(cx, "tab");
750 cx.update(|window, cx| assert!(controls.read(cx).last.is_focused(window)));
751 press(cx, "tab");
752 cx.update(|window, cx| {
753 let controls = controls.read(cx);
754 assert!(!controls.popover.read(cx).is_open());
755 assert!(controls.input.focus_handle(cx).is_focused(window));
756 assert!(
757 controls
758 .dialog
759 .read(cx)
760 .focus_handle()
761 .contains_focused(window, cx)
762 );
763 });
764 }
765
766 #[gpui::test]
767 fn modal_backdrop_receives_the_outside_press(cx: &mut TestAppContext) {
768 let (cx, controls) = harness(cx, false);
769 open(cx, &controls);
770 cx.simulate_click(point(px(2.), px(2.)), Modifiers::default());
771 settle(cx);
772 cx.update(|window, cx| {
773 let controls = controls.read(cx);
774 assert!(!controls.popover.read(cx).is_open());
775 assert!(!controls.dialog.read(cx).is_open());
776 assert!(controls.outside.is_focused(window));
777 assert!(!GlobalState::is_in_deferred_context(cx));
778 });
779 }
780
781 #[gpui::test]
782 fn nested_select_pointer_and_escape_preserve_outer_scopes(cx: &mut TestAppContext) {
783 let (cx, controls) = harness(cx, false);
784 controls.update(cx, |controls, cx| {
785 controls.show_select = true;
786 cx.notify();
787 });
788 settle(cx);
789 open(cx, &controls);
790 cx.update(|window, cx| {
791 let focus = controls.read(cx).select.read(cx).focus_handle().clone();
792 focus.focus(window, cx);
793 });
794 draw(cx);
795 press(cx, "down");
796 let option = cx.debug_bounds("nested-option-1").unwrap().center();
797 assert!(!cx.debug_bounds("popover-panel").unwrap().contains(&option));
798 cx.simulate_click(option, Modifiers::default());
799 settle(cx);
800 cx.update(|window, cx| {
801 let controls = controls.read(cx);
802 assert!(controls.popover.read(cx).is_open());
803 assert!(!controls.select.read(cx).is_open());
804 assert_eq!(controls.select.read(cx).selected_index(), Some(1));
805 assert!(controls.select.read(cx).focus_handle().is_focused(window));
806 });
807
808 press(cx, "down");
809 press(cx, "escape");
810 cx.update(|_, cx| {
811 let controls = controls.read(cx);
812 assert!(!controls.select.read(cx).is_open());
813 assert!(controls.popover.read(cx).is_open());
814 assert!(controls.dialog.read(cx).is_open());
815 });
816 press(cx, "escape");
817 cx.update(|_, cx| {
818 assert!(!controls.read(cx).popover.read(cx).is_open());
819 assert!(controls.read(cx).dialog.read(cx).is_open());
820 });
821 press(cx, "escape");
822 cx.update(|window, cx| {
823 assert!(!controls.read(cx).dialog.read(cx).is_open());
824 assert!(controls.read(cx).outside.is_focused(window));
825 });
826 }
827
828 #[gpui::test]
829 fn disabled_popover_closes_and_keeps_traversal_available(cx: &mut TestAppContext) {
830 let (cx, controls) = harness(cx, false);
831 open(cx, &controls);
832 cx.update(|window, cx| {
833 let state = controls.read(cx).popover.clone();
834 state.update(cx, |state, cx| state.set_disabled(true, window, cx));
835 });
836 settle(cx);
837 cx.update(|window, cx| {
838 let state = controls.read(cx).popover.read(cx);
839 assert!(!state.is_open());
840 assert!(state.is_disabled());
841 assert!(state.focus_handle().is_focused(window));
842 #[cfg(feature = "test-support")]
843 {
844 let trigger =
845 crate::test_support::find(window, &[], &"popover-trigger".into()).unwrap();
846 assert_eq!(trigger.role(), Some(Role::Button));
847 assert_eq!(trigger.label(), Some("Open quick tools"));
848 assert_eq!(trigger.expanded(), Some(false));
849 assert_eq!(trigger.disabled(), Some(true));
850 }
851 });
852 press(cx, "enter");
853 press(cx, "space");
854 let trigger = cx.debug_bounds("popover-trigger").unwrap().center();
855 cx.simulate_click(trigger, Modifiers::default());
856 settle(cx);
857 cx.update(|window, cx| {
858 let state = controls.read(cx).popover.clone();
859 state.update(cx, |state, cx| state.open(window, cx));
860 assert!(!state.read(cx).is_open());
861 });
862 press(cx, "tab");
863 cx.update(|window, cx| assert!(controls.read(cx).after.is_focused(window)));
864 }
865
866 #[gpui::test]
867 fn external_focus_parent_close_and_deactivation_dismiss_retained_state(
868 cx: &mut TestAppContext,
869 ) {
870 let (cx, controls) = harness(cx, false);
871 open(cx, &controls);
872 cx.update(|window, cx| controls.read(cx).input.focus_handle(cx).focus(window, cx));
873 settle(cx);
874 cx.update(|window, cx| {
875 assert!(!controls.read(cx).popover.read(cx).is_open());
876 assert!(controls.read(cx).input.focus_handle(cx).is_focused(window));
877 });
878
879 open(cx, &controls);
880 cx.update(|window, cx| {
881 let dialog = controls.read(cx).dialog.clone();
882 dialog.update(cx, |state, cx| state.close(window, cx));
883 });
884 settle(cx);
885 cx.update(|window, cx| {
886 assert!(!controls.read(cx).popover.read(cx).is_open());
887 assert!(controls.read(cx).outside.is_focused(window));
888 let dialog = controls.read(cx).dialog.clone();
889 dialog.update(cx, |state, cx| state.open(window, cx));
890 });
891 settle(cx);
892 open(cx, &controls);
893 cx.deactivate_window();
894 settle(cx);
895 cx.update(|_, cx| {
896 assert!(!controls.read(cx).popover.read(cx).is_open());
897 assert!(controls.read(cx).dialog.read(cx).is_open());
898 assert!(!GlobalState::is_in_deferred_context(cx));
899 });
900 }
901
902 #[gpui::test]
903 fn unmounting_a_focused_host_never_refocuses_its_hidden_trigger(cx: &mut TestAppContext) {
904 for initial in [false, true] {
905 let (cx, controls) = harness(cx, initial);
906 open(cx, &controls);
907 controls.update(cx, |controls, cx| {
908 controls.show_host = false;
909 cx.notify();
910 });
911 settle(cx);
912 cx.update(|window, cx| {
913 let state = controls.read(cx).popover.read(cx);
914 assert!(!state.is_open());
915 assert!(!state.focus_handle().is_focused(window));
916 assert!(!GlobalState::is_in_deferred_context(cx));
917 });
918 }
919 }
920
921 #[gpui::test]
922 fn immediate_close_restores_the_trigger_before_initial_focus_is_painted(
923 cx: &mut TestAppContext,
924 ) {
925 let (cx, controls) = harness(cx, true);
926 cx.update(|window, cx| {
927 let state = controls.read(cx).popover.clone();
928 state.update(cx, |state, cx| {
929 state.open(window, cx);
930 state.close(window, cx);
931 });
932 assert!(!state.read(cx).is_open());
933 assert!(state.read(cx).focus_handle().is_focused(window));
934 assert!(!GlobalState::is_in_deferred_context(cx));
935 });
936 }
937}