Skip to main content

gpui_deck/
hover_card.rs

1//! Noninteractive rich previews with retained hover and keyboard-focus timing.
2
3use std::{cell::Cell, rc::Rc, time::Duration};
4
5use gpui::{
6    Anchor, AnyElement, App, Context, ElementId, Entity, FocusHandle, HoverListenerMode,
7    InteractiveElement as _, IntoElement, MouseDownEvent, ParentElement as _, Pixels, RenderOnce,
8    Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription,
9    Task, Window, canvas, div, prelude::FluentBuilder as _, px,
10};
11
12use crate::{Button, ElementExt as _, Popup, StyledExt as _, TestSupportExt as _};
13
14const OPEN_DELAY: Duration = Duration::from_millis(500);
15const CLOSE_DELAY: Duration = Duration::from_millis(200);
16
17/// Retained visibility for a rich, noninteractive preview of a Button's action.
18///
19/// Pointer entry waits before opening; leaving both trigger and card waits
20/// before closing, so the pointer can cross their gap. Keyboard focus opens
21/// immediately. The preview never moves focus and adds no Tab stops. Escape,
22/// pointer presses, trigger activation keys, focus changes, and window
23/// deactivation dismiss it. A touch long press on the trigger opens it at once
24/// without activating the Button; the next press dismisses it. Explicit
25/// dismissal suppresses reopening until a
26/// fresh trigger entry or keyboard focus.
27///
28/// Keep the matching HoverCard mounted with its trigger and observe this state
29/// to redraw its consumer. The mount cancels delayed work when removed, even
30/// if the application retains the state for later reuse.
31pub struct HoverCardState {
32    focus: FocusHandle,
33    open: bool,
34    disabled: bool,
35    mounted: bool,
36    trigger_hovered: bool,
37    content_hovered: bool,
38    keyboard_focused: bool,
39    suppressed: bool,
40    open_delay: Duration,
41    close_delay: Duration,
42    open_task: Option<Task<()>>,
43    close_task: Option<Task<()>>,
44    focus_when_open: Option<FocusHandle>,
45    focus_watch: Option<Subscription>,
46    _subscriptions: Vec<Subscription>,
47}
48
49impl HoverCardState {
50    /// Uses the same focus handle as the underlying Button and application.
51    pub fn new(focus: &FocusHandle, window: &mut Window, cx: &mut Context<Self>) -> Self {
52        let subscriptions = vec![
53            cx.on_focus(focus, window, |state, window, cx| {
54                if window.last_input_was_keyboard() {
55                    state.keyboard_focused = true;
56                    state.suppressed = false;
57                    state.show(window, cx);
58                }
59            }),
60            cx.on_blur(focus, window, |state, window, cx| {
61                state.keyboard_focused = false;
62                state.close(window, cx);
63                if !state.trigger_hovered {
64                    state.suppressed = false;
65                }
66            }),
67            cx.observe_window_activation(window, |state, window, cx| {
68                if !window.is_window_active() {
69                    state.close(window, cx);
70                }
71            }),
72        ];
73        Self {
74            focus: focus.clone(),
75            open: false,
76            disabled: false,
77            mounted: false,
78            trigger_hovered: false,
79            content_hovered: false,
80            keyboard_focused: false,
81            suppressed: false,
82            open_delay: OPEN_DELAY,
83            close_delay: CLOSE_DELAY,
84            open_task: None,
85            close_task: None,
86            focus_when_open: None,
87            focus_watch: None,
88            _subscriptions: subscriptions,
89        }
90    }
91
92    /// Configures pointer entry and exit delays before mounting.
93    /// Keyboard focus remains immediate. Defaults are 500 ms and 200 ms.
94    pub fn with_delays(mut self, open: Duration, close: Duration) -> Self {
95        self.open_delay = open;
96        self.close_delay = close;
97        self
98    }
99
100    pub fn is_open(&self) -> bool {
101        self.open
102    }
103
104    pub fn is_disabled(&self) -> bool {
105        self.disabled
106    }
107
108    pub fn focus_handle(&self) -> &FocusHandle {
109        &self.focus
110    }
111
112    /// Coordinates disabled state for the preview and its native Button.
113    /// Enabling waits for another pointer entry or keyboard focus.
114    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
115        if self.disabled != disabled {
116            self.close(window, cx);
117            self.disabled = disabled;
118            cx.notify();
119            window.refresh();
120        }
121    }
122
123    /// Dismisses without moving focus, suppressing the current hover/focus entry.
124    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
125        self.hide(true, window, cx);
126    }
127
128    fn show(&mut self, window: &mut Window, cx: &mut Context<Self>) {
129        self.open_task = None;
130        self.close_task = None;
131        if self.open
132            || self.disabled
133            || self.suppressed
134            || !self.mounted
135            || !window.is_window_active()
136        {
137            return;
138        }
139        self.open = true;
140        self.focus_when_open = window.focused(cx);
141        // A pointer preview can open while another control owns focus. Close
142        // when that owner changes, before a new menu or dialog receives keys.
143        self.focus_watch = self.focus_when_open.as_ref().map(|focus| {
144            let expected = focus.clone();
145            cx.on_blur(focus, window, move |state, window, cx| {
146                if state.focus_when_open.as_ref() == Some(&expected) {
147                    state.close(window, cx);
148                }
149            })
150        });
151        cx.notify();
152        window.refresh();
153    }
154
155    fn hide(&mut self, suppressed: bool, window: &mut Window, cx: &mut Context<Self>) {
156        self.open_task = None;
157        self.close_task = None;
158        self.focus_watch = None;
159        self.focus_when_open = None;
160        self.content_hovered = false;
161        self.keyboard_focused = false;
162        self.suppressed = suppressed;
163        if self.open {
164            self.open = false;
165            cx.notify();
166            window.refresh();
167        }
168    }
169
170    fn hover(&mut self, content: bool, hovered: bool, window: &mut Window, cx: &mut Context<Self>) {
171        let previous = if content {
172            &mut self.content_hovered
173        } else {
174            &mut self.trigger_hovered
175        };
176        if *previous == hovered {
177            return;
178        }
179        *previous = hovered;
180        if hovered {
181            self.close_task = None;
182            if !content {
183                self.suppressed = false;
184                if !self.open && !self.disabled && self.open_task.is_none() {
185                    let delay = self.open_delay;
186                    self.open_task = Some(cx.spawn_in(window, async move |state, cx| {
187                        cx.background_executor().timer(delay).await;
188                        let _ = state.update_in(cx, |state, window, cx| {
189                            if state.trigger_hovered {
190                                state.show(window, cx);
191                            }
192                        });
193                    }));
194                }
195            }
196        } else if !self.trigger_hovered && !self.content_hovered && !self.keyboard_focused {
197            self.schedule_close(window, cx);
198        }
199    }
200
201    fn schedule_close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
202        self.open_task = None;
203        if !self.open || self.close_task.is_some() {
204            return;
205        }
206        let delay = self.close_delay;
207        self.close_task = Some(cx.spawn_in(window, async move |state, cx| {
208            cx.background_executor().timer(delay).await;
209            let _ = state.update_in(cx, |state, window, cx| {
210                if !state.trigger_hovered && !state.content_hovered && !state.keyboard_focused {
211                    state.hide(false, window, cx);
212                }
213            });
214        }));
215    }
216
217    fn unmount(&mut self, cx: &mut Context<Self>) {
218        self.mounted = false;
219        self.open_task = None;
220        self.close_task = None;
221        self.focus_watch = None;
222        self.focus_when_open = None;
223        self.trigger_hovered = false;
224        self.content_hovered = false;
225        self.keyboard_focused = false;
226        self.suppressed = false;
227        if self.open {
228            self.open = false;
229            cx.notify();
230        }
231    }
232}
233
234struct HoverCardMount {
235    visible: Rc<Cell<bool>>,
236    _keys: Subscription,
237    _release: Subscription,
238}
239
240/// A native Button with an application-owned, noninteractive rich preview.
241///
242/// The trigger retains its normal action; the card only adds preview behavior.
243/// Supply noninteractive content and keep essential information available in
244/// the trigger's accessible description or its ordinary destination. The card
245/// is a supplementary tooltip surface with no focus stop. `accessibility_label`
246/// names that surface; name the Button separately in its builder.
247///
248/// [`Styled`] applies to the host frame. Style the content's surface yourself.
249/// [`Popup`] supplies measured positioning, window-edge clamping, deferred
250/// painting, and occlusion. Interactive popup content belongs in Popover.
251#[derive(IntoElement)]
252pub struct HoverCard {
253    id: ElementId,
254    state: Entity<HoverCardState>,
255    trigger: Button,
256    content: Option<AnyElement>,
257    label: Option<SharedString>,
258    anchor: Anchor,
259    offset: Pixels,
260    style: StyleRefinement,
261}
262
263impl HoverCard {
264    pub fn new(id: impl Into<ElementId>, state: &Entity<HoverCardState>) -> Self {
265        let id = id.into();
266        Self {
267            trigger: Button::new(id.clone()),
268            id,
269            state: state.clone(),
270            content: None,
271            label: None,
272            anchor: Anchor::TopLeft,
273            offset: px(0.),
274            style: StyleRefinement::default(),
275        }
276    }
277
278    pub fn trigger(mut self, build: impl FnOnce(Button) -> Button) -> Self {
279        self.trigger = build(self.trigger);
280        self
281    }
282
283    pub fn content(mut self, content: impl IntoElement) -> Self {
284        self.content = Some(content.into_any_element());
285        self
286    }
287
288    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
289        self.label = Some(label.into());
290        self
291    }
292
293    pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
294        self.anchor = anchor.into();
295        self
296    }
297
298    pub fn offset(mut self, offset: Pixels) -> Self {
299        self.offset = offset;
300        self
301    }
302}
303
304impl Styled for HoverCard {
305    fn style(&mut self) -> &mut StyleRefinement {
306        &mut self.style
307    }
308}
309
310impl RenderOnce for HoverCard {
311    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
312        let weak_state = self.state.downgrade();
313        let mount = window.with_element_namespace(self.id.clone(), |window| {
314            window.use_keyed_state(
315                ("hover-card-mount", self.state.entity_id()),
316                cx,
317                |window, cx| {
318                    let _ = weak_state.update(cx, |state, _| state.mounted = true);
319                    let visible = Rc::new(Cell::new(false));
320                    let escape_visible = visible.clone();
321                    let release_visible = visible.clone();
322                    let release_state = weak_state.clone();
323                    let owner_window = window.window_handle();
324                    let keys = cx.intercept_keystrokes(move |event, window, cx| {
325                        if window.window_handle() != owner_window {
326                            return;
327                        }
328                        let _ =
329                            weak_state.update(cx, |state, cx| match event.keystroke.key.as_str() {
330                                "escape" if state.open || state.open_task.is_some() => {
331                                    let consume = state.open
332                                        && escape_visible.get()
333                                        && state.focus_when_open == window.focused(cx);
334                                    state.close(window, cx);
335                                    if consume {
336                                        cx.stop_propagation();
337                                    }
338                                }
339                                "enter" | "space" if state.focus.is_focused(window) => {
340                                    state.close(window, cx);
341                                }
342                                _ => {}
343                            });
344                    });
345                    let release = cx.on_release(move |_, cx| {
346                        release_visible.set(false);
347                        let _ = release_state.update(cx, |state, cx| state.unmount(cx));
348                    });
349                    HoverCardMount {
350                        visible,
351                        _keys: keys,
352                        _release: release,
353                    }
354                },
355            )
356        });
357        let visible = mount.read(cx).visible.clone();
358        visible.set(false);
359        if self.state.read(cx).open && self.state.read(cx).focus_when_open != window.focused(cx) {
360            self.state.update(cx, |state, cx| state.close(window, cx));
361        }
362        let model = self.state.read(cx);
363        let open = model.open;
364        let disabled = model.disabled;
365        let focus = model.focus.clone();
366        let trigger_state = self.state.clone();
367        let content_state = self.state.clone();
368        let trigger_visible = Rc::new(Cell::new(false));
369        let content_trigger_visible = trigger_visible.clone();
370        let trigger = self
371            .trigger
372            .track_focus(&focus)
373            .disabled(disabled)
374            .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
375            .on_hover(move |hovered, window, cx| {
376                trigger_state.update(cx, |state, cx| state.hover(false, *hovered, window, cx));
377            });
378        let mut popup = Popup::new((self.id.clone(), "hover-card-host"), trigger)
379            .anchor(self.anchor)
380            .offset(self.offset);
381        if open && let Some(content) = self.content {
382            popup = popup.content(
383                div()
384                    .id((self.id.clone(), "hover-card-content"))
385                    .test_support()
386                    .role(Role::Tooltip)
387                    .when_some(self.label, |this, label| this.aria_label(label))
388                    .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
389                    .on_hover(move |hovered, window, cx| {
390                        content_state
391                            .update(cx, |state, cx| state.hover(true, *hovered, window, cx));
392                    })
393                    .on_prepaint(move |bounds, window, _| {
394                        visible.set(
395                            content_trigger_visible.get()
396                                && bounds.intersects(&window.content_mask().bounds),
397                        );
398                    })
399                    .child(content),
400            );
401        }
402        let geometry_state = self.state.clone();
403        let touch_state = self.state.clone();
404        let press_state = self.state;
405        div()
406            .refine_style(&self.style)
407            .relative()
408            .child(popup)
409            .child(crate::long_press::long_press_region(
410                touch_state.clone(),
411                move |_, window, cx| {
412                    touch_state.update(cx, |state, cx| {
413                        // Touch has no hover: a long press previews immediately
414                        // instead of activating, until the next press elsewhere.
415                        state.suppressed = false;
416                        state.show(window, cx);
417                        state.open
418                    })
419                },
420            ))
421            .child(
422                canvas(
423                    move |bounds, window, cx| {
424                        let visible = bounds.intersects(&window.content_mask().bounds);
425                        trigger_visible.set(visible);
426                        if !visible && geometry_state.read(cx).open {
427                            window.defer(cx, move |window, cx| {
428                                geometry_state.update(cx, |state, cx| state.close(window, cx));
429                            });
430                        }
431                    },
432                    move |_, _, window, _| {
433                        // Closing a preview never consumes the original click.
434                        window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
435                            if phase.capture() {
436                                press_state.update(cx, |state, cx| state.close(window, cx));
437                            }
438                        });
439                    },
440                )
441                .absolute()
442                .top_0()
443                .left_0()
444                .size_full(),
445            )
446    }
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452    use crate::{Root, actions::Cancel};
453    use gpui::{
454        AppContext as _, KeyBinding, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
455        TestAppContext, VisualTestContext, point,
456    };
457
458    struct Harness {
459        state: Entity<HoverCardState>,
460        before: FocusHandle,
461        trigger: FocusHandle,
462        after: FocusHandle,
463        show_card: bool,
464        activations: Rc<Cell<usize>>,
465        escapes: Rc<Cell<usize>>,
466        _observation: Subscription,
467    }
468
469    impl Render for Harness {
470        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
471            let activations = self.activations.clone();
472            let escapes = self.escapes.clone();
473            div()
474                .id("hover-card-test")
475                .key_context("HoverCardTest")
476                .size_full()
477                .p(px(16.))
478                .flex()
479                .flex_col()
480                .gap(px(16.))
481                .on_action(move |_: &Cancel, _, _| escapes.set(escapes.get() + 1))
482                .child(
483                    Button::new("before")
484                        .track_focus(&self.before)
485                        .w(px(160.))
486                        .h(px(32.))
487                        .child("Before"),
488                )
489                .when(self.show_card, |this| {
490                    this.child(
491                        HoverCard::new("preview", &self.state)
492                            .w(px(160.))
493                            .offset(px(8.))
494                            .accessibility_label("Recording preview")
495                            .trigger(move |button| {
496                                button
497                                    .debug_selector(|| "preview-trigger".into())
498                                    .w_full()
499                                    .h(px(32.))
500                                    .accessibility_label("Preset details")
501                                    .child("Preset details")
502                                    .on_click(move |_, _, _| activations.set(activations.get() + 1))
503                            })
504                            .content(
505                                div()
506                                    .debug_selector(|| "preview-content".into())
507                                    .w(px(220.))
508                                    .h(px(72.))
509                                    .child("Balanced recording preset"),
510                            ),
511                    )
512                })
513                .child(
514                    Button::new("after")
515                        .track_focus(&self.after)
516                        .w(px(160.))
517                        .h(px(32.))
518                        .child("After"),
519                )
520        }
521    }
522
523    fn settle(cx: &mut VisualTestContext) {
524        cx.update(|window, cx| window.draw(cx).clear(cx));
525        cx.run_until_parked();
526        cx.update(|window, cx| window.draw(cx).clear(cx));
527    }
528
529    fn harness(cx: &mut TestAppContext) -> (&mut VisualTestContext, Entity<Harness>) {
530        cx.update(|cx| {
531            crate::init(cx);
532            cx.bind_keys([KeyBinding::new("escape", Cancel, Some("HoverCardTest"))]);
533        });
534        let (root, cx) = cx.add_window_view(|window, cx| {
535            let view = cx.new(|cx| {
536                let trigger = cx.focus_handle();
537                let state = cx.new(|cx| HoverCardState::new(&trigger, window, cx));
538                let observation = cx.observe(&state, |_, _, cx| cx.notify());
539                Harness {
540                    state,
541                    before: cx.focus_handle(),
542                    trigger,
543                    after: cx.focus_handle(),
544                    show_card: true,
545                    activations: Rc::default(),
546                    escapes: Rc::default(),
547                    _observation: observation,
548                }
549            });
550            Root::new(view, window, cx)
551        });
552        let view = root
553            .read_with(cx, |root, _| root.view().clone())
554            .downcast::<Harness>()
555            .unwrap();
556        cx.update(|window, cx| {
557            window.activate_window();
558            view.read(cx).after.clone().focus(window, cx);
559        });
560        settle(cx);
561        (cx, view)
562    }
563
564    fn enter(cx: &mut VisualTestContext) {
565        let keystroke =
566            cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
567        cx.simulate_event(KeyDownEvent {
568            keystroke: keystroke.clone(),
569            is_held: false,
570            prefer_character_input: false,
571        });
572        cx.simulate_event(KeyUpEvent { keystroke });
573        settle(cx);
574    }
575
576    #[gpui::test]
577    fn hover_delays_crossing_the_gap_and_clicks_preserve_focus(cx: &mut TestAppContext) {
578        let (cx, view) = harness(cx);
579        let trigger_bounds = cx.debug_bounds("preview-trigger").unwrap();
580        let trigger = trigger_bounds.center();
581        let outside = point(px(4.), px(4.));
582        cx.simulate_mouse_move(trigger, None, Modifiers::default());
583        cx.run_until_parked();
584        cx.executor().advance_clock(OPEN_DELAY / 2);
585        cx.simulate_mouse_move(outside, None, Modifiers::default());
586        cx.executor().advance_clock(OPEN_DELAY);
587        settle(cx);
588        cx.update(|_, cx| assert!(!view.read(cx).state.read(cx).is_open()));
589
590        cx.simulate_mouse_move(trigger, None, Modifiers::default());
591        cx.run_until_parked();
592        cx.executor().advance_clock(OPEN_DELAY);
593        settle(cx);
594        cx.update(|window, cx| {
595            let view = view.read(cx);
596            assert!(view.state.read(cx).is_open());
597            assert!(view.after.is_focused(window));
598            #[cfg(feature = "test-support")]
599            assert!(
600                crate::test_support::snapshots(window)
601                    .iter()
602                    .any(|item| item.role() == Some(Role::Tooltip)
603                        && item.label() == Some("Recording preview")
604                        && item.visible())
605            );
606        });
607        cx.simulate_keystrokes("escape");
608        settle(cx);
609        cx.simulate_mouse_move(trigger + point(px(1.), px(0.)), None, Modifiers::default());
610        cx.executor().advance_clock(OPEN_DELAY * 2);
611        settle(cx);
612        cx.update(|_, cx| assert!(!view.read(cx).state.read(cx).is_open()));
613        cx.simulate_mouse_move(outside, None, Modifiers::default());
614        cx.simulate_mouse_move(trigger, None, Modifiers::default());
615        cx.run_until_parked();
616        cx.executor().advance_clock(OPEN_DELAY);
617        settle(cx);
618        let content = cx.debug_bounds("preview-content").unwrap().center();
619        let gap = point(trigger.x, trigger_bounds.bottom_left().y + px(4.));
620        cx.simulate_mouse_move(gap, None, Modifiers::default());
621        cx.run_until_parked();
622        cx.executor().advance_clock(CLOSE_DELAY / 2);
623        cx.simulate_mouse_move(content, None, Modifiers::default());
624        cx.executor().advance_clock(CLOSE_DELAY * 2);
625        settle(cx);
626        cx.update(|window, cx| {
627            let view = view.read(cx);
628            assert!(
629                view.state.read(cx).is_open(),
630                "entering the card cancels its close delay"
631            );
632            assert!(view.after.is_focused(window));
633        });
634        cx.simulate_keystrokes("escape");
635        settle(cx);
636        cx.update(|window, cx| {
637            let view = view.read(cx);
638            assert!(!view.state.read(cx).is_open());
639            assert!(view.after.is_focused(window));
640            assert_eq!(view.escapes.get(), 0);
641        });
642        // The removed card's old hover flag must not retain a later preview.
643        cx.simulate_mouse_move(outside, None, Modifiers::default());
644        cx.simulate_mouse_move(trigger, None, Modifiers::default());
645        cx.run_until_parked();
646        cx.executor().advance_clock(OPEN_DELAY);
647        settle(cx);
648        cx.simulate_mouse_move(outside, None, Modifiers::default());
649        cx.run_until_parked();
650        cx.executor().advance_clock(CLOSE_DELAY / 2);
651        cx.update(|_, cx| assert!(view.read(cx).state.read(cx).is_open()));
652        cx.executor().advance_clock(CLOSE_DELAY);
653        settle(cx);
654        cx.update(|_, cx| assert!(!view.read(cx).state.read(cx).is_open()));
655
656        cx.simulate_mouse_move(trigger, None, Modifiers::default());
657        cx.run_until_parked();
658        cx.executor().advance_clock(OPEN_DELAY);
659        settle(cx);
660        cx.simulate_click(trigger, Modifiers::default());
661        settle(cx);
662        cx.executor().advance_clock(OPEN_DELAY * 2);
663        settle(cx);
664        cx.update(|window, cx| {
665            let view = view.read(cx);
666            assert_eq!(view.activations.get(), 1);
667            assert!(view.trigger.is_focused(window));
668            assert!(!view.state.read(cx).is_open());
669        });
670    }
671
672    #[gpui::test]
673    fn keyboard_dismissal_disabled_and_retained_mounts_keep_their_owners(cx: &mut TestAppContext) {
674        let (cx, view) = harness(cx);
675        cx.simulate_keystrokes("shift-tab");
676        settle(cx);
677        cx.update(|window, cx| {
678            let view = view.read(cx);
679            assert!(view.trigger.is_focused(window));
680            assert!(view.state.read(cx).is_open());
681        });
682        cx.simulate_mouse_move(point(px(4.), px(4.)), None, Modifiers::default());
683        cx.executor().advance_clock(CLOSE_DELAY * 2);
684        settle(cx);
685        cx.update(|window, cx| {
686            let view = view.read(cx);
687            assert!(view.trigger.is_focused(window));
688            assert!(
689                view.state.read(cx).is_open(),
690                "pointer movement does not blur keyboard focus"
691            );
692        });
693        cx.simulate_keystrokes("escape");
694        settle(cx);
695        cx.update(|window, cx| {
696            let view = view.read(cx);
697            assert!(view.trigger.is_focused(window));
698            assert!(!view.state.read(cx).is_open());
699            assert_eq!(view.escapes.get(), 0);
700        });
701        cx.simulate_keystrokes("escape");
702        settle(cx);
703        cx.update(|_, cx| assert_eq!(view.read(cx).escapes.get(), 1));
704        cx.simulate_keystrokes("tab shift-tab");
705        settle(cx);
706        enter(cx);
707        cx.update(|_, cx| {
708            let view = view.read(cx);
709            assert!(!view.state.read(cx).is_open());
710            assert_eq!(view.activations.get(), 1);
711        });
712        cx.update(|window, cx| {
713            let state = view.read(cx).state.clone();
714            state.update(cx, |state, cx| state.set_disabled(true, window, cx));
715        });
716        settle(cx);
717        cx.simulate_keystrokes("tab shift-tab");
718        settle(cx);
719        cx.update(|window, cx| {
720            let view = view.read(cx);
721            assert!(view.before.is_focused(window));
722            assert!(!view.state.read(cx).is_open());
723        });
724        cx.update(|window, cx| {
725            let state = view.read(cx).state.clone();
726            state.update(cx, |state, cx| state.set_disabled(false, window, cx));
727            view.read(cx).after.clone().focus(window, cx);
728        });
729        settle(cx);
730
731        let trigger = cx.debug_bounds("preview-trigger").unwrap().center();
732        let outside = point(px(4.), px(4.));
733        cx.simulate_mouse_move(trigger, None, Modifiers::default());
734        cx.run_until_parked();
735        cx.executor().advance_clock(OPEN_DELAY / 2);
736        view.update(cx, |view, cx| {
737            view.show_card = false;
738            cx.notify();
739        });
740        settle(cx);
741        cx.simulate_mouse_move(outside, None, Modifiers::default());
742        cx.executor().advance_clock(OPEN_DELAY);
743        settle(cx);
744        view.update(cx, |view, cx| {
745            view.show_card = true;
746            cx.notify();
747        });
748        settle(cx);
749        cx.update(|_, cx| assert!(!view.read(cx).state.read(cx).is_open()));
750
751        cx.simulate_mouse_move(trigger, None, Modifiers::default());
752        cx.run_until_parked();
753        cx.executor().advance_clock(OPEN_DELAY);
754        settle(cx);
755        cx.update(|window, cx| view.read(cx).before.clone().focus(window, cx));
756        // A new focus owner receives Escape even before the next paint.
757        cx.simulate_keystrokes("escape");
758        settle(cx);
759        cx.update(|window, cx| {
760            let view = view.read(cx);
761            assert!(view.before.is_focused(window));
762            assert!(!view.state.read(cx).is_open());
763            assert_eq!(view.escapes.get(), 2);
764        });
765
766        // Replacing a controller at the same UI position transfers the mount
767        // and its key interception to the newly supplied state.
768        let previous = view.read_with(cx, |view, _| view.state.clone());
769        cx.update(|window, cx| {
770            view.update(cx, |view, cx| {
771                view.state = cx.new(|cx| HoverCardState::new(&view.trigger, window, cx));
772                view._observation = cx.observe(&view.state, |_, _, cx| cx.notify());
773                cx.notify();
774            });
775        });
776        settle(cx);
777        cx.simulate_keystrokes("tab");
778        settle(cx);
779        cx.update(|window, cx| {
780            let view = view.read(cx);
781            assert!(view.trigger.is_focused(window));
782            assert!(view.state.read(cx).is_open());
783            assert!(!previous.read(cx).is_open());
784        });
785        cx.simulate_keystrokes("escape");
786        settle(cx);
787        cx.update(|_, cx| {
788            let view = view.read(cx);
789            assert!(!view.state.read(cx).is_open());
790            assert_eq!(view.escapes.get(), 2);
791        });
792    }
793
794    #[gpui::test]
795    fn touch_long_press_previews_without_activation_until_the_next_press(cx: &mut TestAppContext) {
796        use gpui::{TouchEvent, TouchId, TouchPhase};
797        let (cx, view) = harness(cx);
798        let trigger = cx.debug_bounds("preview-trigger").unwrap().center();
799        let touch = |phase| TouchEvent {
800            id: TouchId(3),
801            phase,
802            position: trigger,
803            predicted_position: None,
804            force: None,
805        };
806        cx.simulate_event(touch(TouchPhase::Started));
807        cx.executor().advance_clock(
808            gpui::GestureTuning::default().long_press_duration + Duration::from_millis(1),
809        );
810        settle(cx);
811        cx.simulate_event(touch(TouchPhase::Ended));
812        settle(cx);
813        cx.update(|window, cx| {
814            let view = view.read(cx);
815            assert!(
816                view.state.read(cx).is_open(),
817                "the preview opens without a delay"
818            );
819            assert_eq!(view.activations.get(), 0, "a long press does not activate");
820            assert!(view.after.is_focused(window), "focus does not move");
821        });
822        cx.simulate_mouse_down(
823            point(px(400.), px(400.)),
824            gpui::MouseButton::Left,
825            Modifiers::default(),
826        );
827        settle(cx);
828        cx.update(|_, cx| assert!(!view.read(cx).state.read(cx).is_open()));
829    }
830}