1use std::{cell::Cell, rc::Rc, time::Duration};
4
5use gpui::{
6 AnyElement, AnyTooltip, App, AppContext as _, Context, ElementId, Entity, FocusHandle,
7 InteractiveElement as _, IntoElement, MouseButton, ParentElement as _, Render, RenderOnce,
8 Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription,
9 Task, Window, canvas, div, point, px,
10};
11
12use crate::{Button, StyledExt as _, TestSupportExt as _};
13
14const HOVER_DELAY: Duration = Duration::from_millis(500);
15
16pub struct TooltipState {
26 focus: FocusHandle,
27 mounted: bool,
28 hovered: bool,
29 open: bool,
30 suppressed: bool,
31 hover_task: Option<Task<()>>,
32 _subscriptions: Vec<Subscription>,
33}
34
35impl TooltipState {
36 pub fn new(focus: &FocusHandle, window: &mut Window, cx: &mut Context<Self>) -> Self {
37 let subscriptions = vec![
38 cx.on_focus(focus, window, |state, window, cx| {
39 if state.suppressed && !window.last_input_was_keyboard() {
42 return;
43 }
44 state.suppressed = false;
45 state.show(window, cx);
46 }),
47 cx.on_blur(focus, window, |state, window, cx| {
48 state.dismiss(window, cx);
49 if !state.hovered {
50 state.suppressed = false;
51 }
52 }),
53 cx.observe_window_activation(window, |state, window, cx| {
54 if !window.is_window_active() {
55 state.dismiss(window, cx);
56 }
57 }),
58 ];
59 Self {
60 focus: focus.clone(),
61 mounted: false,
62 hovered: false,
63 open: false,
64 suppressed: false,
65 hover_task: None,
66 _subscriptions: subscriptions,
67 }
68 }
69
70 pub fn is_open(&self) -> bool {
71 self.open
72 }
73
74 pub fn focus_handle(&self) -> &FocusHandle {
76 &self.focus
77 }
78
79 fn show(&mut self, window: &mut Window, cx: &mut Context<Self>) {
80 self.hover_task = None;
81 if self.open || !self.mounted || !window.is_window_active() {
82 return;
83 }
84 self.open = true;
85 cx.notify();
86 window.refresh();
87 }
88
89 fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
90 self.hover_task = None;
91 self.suppressed = true;
92 if !self.open {
93 return;
94 }
95 self.open = false;
96 cx.notify();
97 window.refresh();
98 }
99
100 fn hover(&mut self, hovered: bool, window: &mut Window, cx: &mut Context<Self>) {
101 self.hovered = hovered;
102 self.hover_task = None;
103 if !hovered {
104 if !self.focus.is_focused(window) {
105 self.dismiss(window, cx);
106 self.suppressed = false;
107 }
108 return;
109 }
110 self.suppressed = false;
111 if self.focus.is_focused(window) {
112 self.show(window, cx);
113 } else {
114 self.hover_task = Some(cx.spawn_in(window, async move |state, cx| {
115 cx.background_executor().timer(HOVER_DELAY).await;
116 let _ = state.update_in(cx, |state, window, cx| {
117 if state.hovered && !state.suppressed {
118 state.show(window, cx);
119 }
120 });
121 }));
122 }
123 }
124}
125
126type TooltipContent = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
127
128struct TooltipSurface {
129 id: ElementId,
130 description: SharedString,
131 content: Option<TooltipContent>,
132 style: StyleRefinement,
133}
134
135impl Render for TooltipSurface {
136 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
137 let surface = div()
138 .id(self.id.clone())
139 .test_support()
140 .role(Role::Tooltip)
141 .aria_label(self.description.clone())
142 .refine_style(&self.style);
143 match &self.content {
144 Some(content) => surface.child(content(window, cx)),
145 None => surface.child(self.description.clone()),
146 }
147 }
148}
149
150struct TooltipMount {
153 surface: Entity<TooltipSurface>,
154 visible: Rc<Cell<bool>>,
155 _escape: Subscription,
156 _release: Subscription,
157}
158
159#[derive(IntoElement)]
170pub struct Tooltip {
171 id: ElementId,
172 state: Entity<TooltipState>,
173 description: SharedString,
174 content: Option<TooltipContent>,
175 trigger: Button,
176 style: StyleRefinement,
177}
178
179impl Tooltip {
180 pub fn new(
181 id: impl Into<ElementId>,
182 state: &Entity<TooltipState>,
183 description: impl Into<SharedString>,
184 ) -> Self {
185 let id = id.into();
186 Self {
187 trigger: Button::new(id.clone()),
188 id,
189 state: state.clone(),
190 description: description.into(),
191 content: None,
192 style: StyleRefinement::default(),
193 }
194 }
195
196 pub fn trigger(mut self, build: impl FnOnce(Button) -> Button) -> Self {
197 self.trigger = build(self.trigger);
198 self
199 }
200
201 pub fn content<E: IntoElement>(
208 mut self,
209 build: impl Fn(&mut Window, &mut App) -> E + 'static,
210 ) -> Self {
211 self.content = Some(Rc::new(move |window, cx| {
212 build(window, cx).into_any_element()
213 }));
214 self
215 }
216}
217
218impl Styled for Tooltip {
219 fn style(&mut self) -> &mut StyleRefinement {
220 &mut self.style
221 }
222}
223
224impl RenderOnce for Tooltip {
225 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
226 let focus = self.state.read(cx).focus.clone();
227 let weak_state = self.state.downgrade();
228 let surface_id = (self.id.clone(), "tooltip-content").into();
229 let mount = window.with_element_namespace(self.id.clone(), |window| {
230 window.use_keyed_state(
231 ("tooltip-mount", self.state.entity_id()),
232 cx,
233 |window, cx| {
234 let _ = weak_state.update(cx, |state, _| state.mounted = true);
235 let visible = Rc::new(Cell::new(false));
236 let escape_visible = visible.clone();
237 let release_visible = visible.clone();
238 let release_state = weak_state.clone();
239 let owner_window = window.window_handle();
240 let surface = cx.new(|_| TooltipSurface {
241 id: surface_id,
242 description: self.description.clone(),
243 content: self.content.clone(),
244 style: self.style.clone(),
245 });
246 let escape = cx.intercept_keystrokes(move |event, window, cx| {
247 if window.window_handle() != owner_window
248 || !matches!(event.keystroke.key.as_str(), "escape" | "enter" | "space")
249 {
250 return;
251 }
252 let _ =
253 weak_state.update(cx, |state, cx| match event.keystroke.key.as_str() {
254 "escape" if state.open || state.hover_task.is_some() => {
255 let was_visible = escape_visible.get();
256 state.dismiss(window, cx);
257 if was_visible {
258 cx.stop_propagation();
259 }
260 }
261 "enter" | "space" if state.focus.is_focused(window) => {
262 state.dismiss(window, cx);
263 }
264 _ => {}
265 });
266 });
267 let release = cx.on_release(move |_, cx| {
268 release_visible.set(false);
269 let _ = release_state.update(cx, |state, cx| {
270 state.mounted = false;
271 state.hover_task = None;
272 state.hovered = false;
273 state.suppressed = false;
274 if state.open {
275 state.open = false;
276 cx.notify();
277 }
278 });
279 });
280 TooltipMount {
281 surface,
282 visible,
283 _escape: escape,
284 _release: release,
285 }
286 },
287 )
288 });
289 let surface = mount.read(cx).surface.clone();
290 surface.update(cx, |surface, _| {
291 surface.description = self.description.clone();
292 surface.content = self.content;
293 surface.style = self.style;
294 });
295 let visible = mount.read(cx).visible.clone();
296 let hover_state = self.state.clone();
297 let press_state = self.state.clone();
298 let trigger = self
299 .trigger
300 .track_focus(&focus)
301 .aria_description(self.description)
302 .on_hover(move |hovered, window, cx| {
303 hover_state.update(cx, |state, cx| state.hover(*hovered, window, cx));
304 })
305 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
306 press_state.update(cx, |state, cx| state.dismiss(window, cx));
307 });
308 let state = self.state;
309
310 div()
311 .id((self.id, "tooltip-host"))
312 .relative()
313 .flex()
314 .child(trigger)
315 .child(
316 canvas(
317 move |bounds, window, cx| {
318 visible.set(false);
319 if !state.read(cx).is_open()
320 || !bounds.intersects(&window.content_mask().bounds)
321 {
322 return;
323 }
324 let state = state.downgrade();
325 let visible = visible.clone();
326 window.set_tooltip(AnyTooltip {
327 view: surface.clone().into(),
328 mouse_position: bounds.bottom_left() + point(px(0.), px(4.)),
329 check_visible_and_update: Rc::new(move |_, window, cx| {
330 let show = window.is_window_active()
331 && state
332 .read_with(cx, |state, _| state.is_open())
333 .unwrap_or(false);
334 visible.set(show);
335 show
336 }),
337 });
338 },
339 |_, _, _, _| {},
340 )
341 .absolute()
342 .top_0()
343 .left_0()
344 .size_full(),
345 )
346 }
347}
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352 use crate::{Root, actions::Cancel};
353 use gpui::{
354 KeyBinding, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext,
355 VisualTestContext, prelude::FluentBuilder as _,
356 };
357
358 const DESCRIPTION: &str = "Change the session settings.";
359
360 struct Harness {
361 tooltip: Entity<TooltipState>,
362 trigger: FocusHandle,
363 after: FocusHandle,
364 activations: Rc<Cell<usize>>,
365 escapes: Rc<Cell<usize>>,
366 show_tooltip: bool,
367 rich: bool,
368 _observation: Subscription,
369 }
370
371 impl Render for Harness {
372 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
373 let activations = self.activations.clone();
374 let escapes = self.escapes.clone();
375 div()
376 .id("tooltip-test")
377 .key_context("TooltipTest")
378 .size_full()
379 .p(px(16.))
380 .flex()
381 .flex_col()
382 .gap(px(16.))
383 .on_action(move |_: &Cancel, _, _| escapes.set(escapes.get() + 1))
384 .when(self.show_tooltip, |this| {
385 this.child(
386 Tooltip::new("tooltip-trigger", &self.tooltip, DESCRIPTION)
387 .w(px(220.))
388 .p(px(8.))
389 .trigger(move |button| {
390 button
391 .debug_selector(|| "tooltip-trigger".into())
392 .w(px(160.))
393 .h(px(32.))
394 .accessibility_label("Edit settings")
395 .child("Edit settings")
396 .on_click(move |_, _, _| activations.set(activations.get() + 1))
397 })
398 .when(self.rich, |tooltip| {
399 tooltip.content(|_, _| {
400 div().flex().gap(px(8.)).child("Change settings").child(
401 div().id("tooltip-shortcut").test_support().child("Ctrl+,"),
402 )
403 })
404 }),
405 )
406 })
407 .child(
408 Button::new("after-tooltip")
409 .track_focus(&self.after)
410 .w(px(160.))
411 .h(px(32.))
412 .child("After"),
413 )
414 }
415 }
416
417 fn settle(cx: &mut VisualTestContext) {
418 cx.update(|window, cx| window.draw(cx).clear(cx));
419 cx.run_until_parked();
420 cx.update(|window, cx| window.draw(cx).clear(cx));
421 }
422
423 fn harness(cx: &mut TestAppContext) -> (&mut VisualTestContext, Entity<Harness>) {
424 cx.update(|cx| {
425 crate::init(cx);
426 cx.bind_keys([KeyBinding::new("escape", Cancel, Some("TooltipTest"))]);
427 });
428 let (root, cx) = cx.add_window_view(|window, cx| {
429 let view = cx.new(|cx| {
430 let trigger = cx.focus_handle();
431 let tooltip = cx.new(|cx| TooltipState::new(&trigger, window, cx));
432 let observation = cx.observe(&tooltip, |_, _, cx| cx.notify());
433 Harness {
434 tooltip,
435 trigger,
436 after: cx.focus_handle(),
437 activations: Rc::default(),
438 escapes: Rc::default(),
439 show_tooltip: true,
440 rich: false,
441 _observation: observation,
442 }
443 });
444 Root::new(view, window, cx)
445 });
446 let view = root
447 .read_with(cx, |root, _| root.view().clone())
448 .downcast::<Harness>()
449 .unwrap();
450 cx.update(|window, cx| {
451 window.activate_window();
452 let after = view.read(cx).after.clone();
453 after.focus(window, cx);
454 });
455 settle(cx);
456 (cx, view)
457 }
458
459 fn activate(cx: &mut VisualTestContext) {
460 let keystroke =
461 cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
462 cx.simulate_event(KeyDownEvent {
463 keystroke: keystroke.clone(),
464 is_held: false,
465 prefer_character_input: false,
466 });
467 cx.simulate_event(KeyUpEvent { keystroke });
468 settle(cx);
469 }
470
471 #[gpui::test]
472 fn focus_escape_and_activation_preserve_the_trigger_contract(cx: &mut TestAppContext) {
473 let (cx, view) = harness(cx);
474 cx.simulate_keystrokes("shift-tab");
475 settle(cx);
476 cx.update(|window, cx| {
477 let view = view.read(cx);
478 assert!(view.trigger.is_focused(window));
479 assert!(view.tooltip.read(cx).is_open());
480 #[cfg(feature = "test-support")]
481 {
482 let trigger =
483 crate::test_support::find(window, &[], &"tooltip-trigger".into()).unwrap();
484 assert_eq!(trigger.description(), Some(DESCRIPTION));
485 assert!(crate::test_support::snapshots(window).iter().any(|item| {
486 item.role() == Some(Role::Tooltip) && item.label() == Some(DESCRIPTION)
487 }));
488 }
489 });
490 cx.simulate_keystrokes("escape");
491 settle(cx);
492 cx.update(|window, cx| {
493 let view = view.read(cx);
494 assert!(!view.tooltip.read(cx).is_open());
495 assert!(view.trigger.is_focused(window));
496 assert_eq!(view.activations.get(), 0);
497 assert_eq!(view.escapes.get(), 0);
498 });
499 cx.simulate_keystrokes("escape");
500 settle(cx);
501 cx.update(|_, cx| assert_eq!(view.read(cx).escapes.get(), 1));
502 cx.simulate_keystrokes("tab");
503 settle(cx);
504 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
505 cx.simulate_keystrokes("shift-tab");
506 settle(cx);
507 cx.update(|_, cx| assert!(view.read(cx).tooltip.read(cx).is_open()));
508 activate(cx);
509 cx.update(|window, cx| {
510 let view = view.read(cx);
511 assert_eq!(view.activations.get(), 1);
512 assert!(!view.tooltip.read(cx).is_open());
513 assert!(view.trigger.is_focused(window));
514 });
515
516 cx.simulate_keystrokes("tab");
517 settle(cx);
518 let previous = view.read_with(cx, |view, _| view.tooltip.clone());
519 cx.update(|window, cx| {
520 view.update(cx, |view, cx| {
521 view.tooltip = cx.new(|cx| TooltipState::new(&view.trigger, window, cx));
522 view._observation = cx.observe(&view.tooltip, |_, _, cx| cx.notify());
523 cx.notify();
524 });
525 });
526 settle(cx);
527 cx.simulate_keystrokes("shift-tab");
528 settle(cx);
529 cx.update(|window, cx| {
530 let view = view.read(cx);
531 assert!(view.trigger.is_focused(window));
532 assert!(view.tooltip.read(cx).is_open());
533 assert!(!previous.read(cx).is_open());
534 });
535 cx.simulate_keystrokes("escape");
536 settle(cx);
537 cx.update(|_, cx| {
538 let view = view.read(cx);
539 assert!(!view.tooltip.read(cx).is_open());
540 assert_eq!(view.escapes.get(), 1);
541 });
542 }
543
544 #[cfg(feature = "test-support")]
545 #[gpui::test]
546 fn rich_content_is_drawn_while_the_description_stays_the_native_text(cx: &mut TestAppContext) {
547 let (cx, view) = harness(cx);
548 view.update(cx, |view, cx| {
549 view.rich = true;
550 cx.notify();
551 });
552 settle(cx);
553 cx.simulate_keystrokes("shift-tab");
554 settle(cx);
555 cx.update(|window, cx| {
556 let view = view.read(cx);
557 assert!(view.trigger.is_focused(window));
558 assert!(view.tooltip.read(cx).is_open());
559 let trigger =
560 crate::test_support::find(window, &[], &"tooltip-trigger".into()).unwrap();
561 assert_eq!(trigger.description(), Some(DESCRIPTION));
562 let surface = crate::test_support::snapshots(window)
563 .into_iter()
564 .find(|item| item.role() == Some(Role::Tooltip))
565 .unwrap();
566 assert_eq!(surface.label(), Some(DESCRIPTION));
567 let shortcut =
568 crate::test_support::find(window, &[], &"tooltip-shortcut".into()).unwrap();
569 assert!(shortcut.visible());
570 assert_eq!(shortcut.focused(), None, "rich content adds no focus stop");
571 assert!(shortcut.bounds().left() >= surface.bounds().left());
572 assert!(shortcut.bounds().right() <= surface.bounds().right() + px(1.));
573 });
574 cx.simulate_keystrokes("tab");
575 settle(cx);
576 cx.update(|window, cx| {
577 let view = view.read(cx);
578 assert!(view.after.is_focused(window), "Tab skips the rich content");
579 assert!(!view.tooltip.read(cx).is_open());
580 });
581 }
582
583 #[gpui::test]
584 fn hover_delay_leave_escape_and_click_do_not_steal_focus(cx: &mut TestAppContext) {
585 let (cx, view) = harness(cx);
586 let trigger = cx.debug_bounds("tooltip-trigger").unwrap().center();
587 let outside = point(px(4.), px(4.));
588 cx.simulate_mouse_move(trigger, None, Modifiers::default());
589 cx.run_until_parked();
590 cx.executor().advance_clock(HOVER_DELAY / 2);
591 cx.simulate_mouse_move(outside, None, Modifiers::default());
592 cx.executor().advance_clock(HOVER_DELAY);
593 settle(cx);
594 cx.update(|_, cx| assert!(!view.read(cx).tooltip.read(cx).is_open()));
595
596 cx.simulate_mouse_move(trigger, None, Modifiers::default());
599 cx.run_until_parked();
600 cx.executor().advance_clock(HOVER_DELAY / 2);
601 view.update(cx, |view, cx| {
602 view.show_tooltip = false;
603 cx.notify();
604 });
605 settle(cx);
606 cx.simulate_mouse_move(outside, None, Modifiers::default());
607 cx.executor().advance_clock(HOVER_DELAY);
608 settle(cx);
609 cx.update(|_, cx| assert!(!view.read(cx).tooltip.read(cx).is_open()));
610 view.update(cx, |view, cx| {
611 view.show_tooltip = true;
612 cx.notify();
613 });
614 settle(cx);
615 cx.update(|_, cx| assert!(!view.read(cx).tooltip.read(cx).is_open()));
616 cx.simulate_keystrokes("escape");
617 settle(cx);
618 cx.update(|_, cx| assert_eq!(view.read(cx).escapes.get(), 1));
619
620 cx.simulate_mouse_move(trigger, None, Modifiers::default());
621 cx.run_until_parked();
622 cx.executor().advance_clock(HOVER_DELAY);
623 settle(cx);
624 cx.update(|window, cx| {
625 let view = view.read(cx);
626 assert!(view.tooltip.read(cx).is_open());
627 assert!(view.after.is_focused(window));
628 assert_eq!(view.activations.get(), 0);
629 });
630 cx.simulate_keystrokes("escape");
631 settle(cx);
632 cx.executor().advance_clock(HOVER_DELAY * 2);
633 settle(cx);
634 cx.update(|window, cx| {
635 let view = view.read(cx);
636 assert!(!view.tooltip.read(cx).is_open());
637 assert_eq!(view.escapes.get(), 1);
638 assert!(view.after.is_focused(window));
639 });
640
641 cx.simulate_mouse_move(outside, None, Modifiers::default());
642 cx.simulate_mouse_move(trigger, None, Modifiers::default());
643 cx.run_until_parked();
644 cx.executor().advance_clock(HOVER_DELAY);
645 settle(cx);
646 cx.update(|_, cx| assert!(view.read(cx).tooltip.read(cx).is_open()));
647 cx.simulate_click(trigger, Modifiers::default());
648 settle(cx);
649 cx.update(|window, cx| {
650 let view = view.read(cx);
651 assert_eq!(view.activations.get(), 1);
652 assert!(!view.tooltip.read(cx).is_open());
653 assert!(view.trigger.is_focused(window));
654 });
655 }
656}