Skip to main content

gpui_component/
tooltip.rs

1use crate::root::WindowState;
2use std::{
3    cell::RefCell,
4    rc::{Rc, Weak},
5    time::Duration,
6};
7
8use gpui::{
9    Action, AnyElement, AnyView, App, AppContext, AvailableSpace, Bounds, Context, ElementId,
10    GlobalElementId, IntoElement, MouseButton, ParentElement, Pixels, Render, SharedString, Size,
11    StatefulInteractiveElement, StyleRefinement, Styled, Window, div, prelude::FluentBuilder, px,
12    size,
13};
14pub use gpui_base::TooltipDefaults;
15use gpui_base::{
16    Tooltip as BaseTooltip, TooltipOverlay as BaseTooltipOverlay,
17    TooltipRequest as BaseTooltipRequest, TooltipTransition as BaseTooltipTransition,
18};
19
20use crate::{
21    ActiveTheme, ElementExt as _, Placement, StyledExt,
22    animation::{EffectTransition, ease_in_out_cubic, ease_out_cubic},
23    kbd::Kbd,
24    text::Text,
25};
26
27pub(crate) fn init(_cx: &mut App) {
28    // No app-level init needed — TooltipOverlay is per-window via Root.
29}
30
31// ── Tooltip view (unchanged API) ────────────────────────────────────────────
32
33enum TooltipContext {
34    Text(Text),
35    Element(Box<dyn Fn(&mut Window, &mut App) -> AnyElement>),
36}
37
38/// A Tooltip element that can display text or custom content,
39/// with optional key binding information.
40pub struct Tooltip {
41    style: StyleRefinement,
42    content: TooltipContext,
43    key_binding: Option<Kbd>,
44    action: Option<(Box<dyn Action>, Option<SharedString>)>,
45}
46
47impl Tooltip {
48    /// Create a Tooltip with a text content.
49    pub fn new(text: impl Into<Text>) -> Self {
50        Self {
51            style: StyleRefinement::default(),
52            content: TooltipContext::Text(text.into()),
53            key_binding: None,
54            action: None,
55        }
56    }
57
58    /// Create a Tooltip with a custom element.
59    pub fn element<E, F>(builder: F) -> Self
60    where
61        E: IntoElement,
62        F: Fn(&mut Window, &mut App) -> E + 'static,
63    {
64        Self {
65            style: StyleRefinement::default(),
66            key_binding: None,
67            action: None,
68            content: TooltipContext::Element(Box::new(move |window, cx| {
69                builder(window, cx).into_any_element()
70            })),
71        }
72    }
73
74    /// Set Action to display key binding information for the tooltip if it exists.
75    pub fn action(mut self, action: &dyn Action, context: Option<&str>) -> Self {
76        self.action = Some((action.boxed_clone(), context.map(SharedString::new)));
77        self
78    }
79
80    /// Set KeyBinding information for the tooltip.
81    pub fn key_binding(mut self, key_binding: Option<Kbd>) -> Self {
82        self.key_binding = key_binding;
83        self
84    }
85
86    /// Build the tooltip and return it as an `AnyView`.
87    pub fn build(self, _: &mut Window, cx: &mut App) -> AnyView {
88        cx.new(|_| self).into()
89    }
90}
91
92impl FluentBuilder for Tooltip {}
93impl Styled for Tooltip {
94    fn style(&mut self) -> &mut StyleRefinement {
95        &mut self.style
96    }
97}
98impl Render for Tooltip {
99    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
100        let key_binding = if let Some(key_binding) = &self.key_binding {
101            Some(key_binding.clone())
102        } else {
103            if let Some((action, context)) = &self.action {
104                Kbd::binding_for_action(
105                    action.as_ref(),
106                    context.as_ref().map(|s| s.as_ref()),
107                    window,
108                )
109            } else {
110                None
111            }
112        };
113
114        div().child(
115            // Wrap in a child, to ensure the left margin is applied to the tooltip
116            BaseTooltip::new("tooltip-popup")
117                .h_flex()
118                .font_family(cx.theme().font_family.clone())
119                .m_3()
120                .bg(cx.theme().tokens.popover)
121                .text_color(cx.theme().popover_foreground)
122                .bg(cx.theme().tokens.popover)
123                .border_1()
124                .border_color(cx.theme().border)
125                .shadow_md()
126                .rounded(cx.theme().radius)
127                .justify_between()
128                .py_0p5()
129                .px_2()
130                .text_sm()
131                .gap_3()
132                .refine_style(&self.style)
133                .map(|this| {
134                    this.child(
135                        div()
136                            .min_w_0()
137                            .overflow_hidden()
138                            .map(|this| match self.content {
139                                TooltipContext::Text(ref text) => this.child(text.clone()),
140                                TooltipContext::Element(ref builder) => {
141                                    this.child(builder(window, cx))
142                                }
143                            }),
144                    )
145                })
146                .when_some(key_binding, |this, kbd| {
147                    this.child(
148                        div()
149                            .text_xs()
150                            .flex_shrink_0()
151                            .text_color(cx.theme().muted_foreground)
152                            .child(kbd.appearance(false)),
153                    )
154                }),
155        )
156    }
157}
158
159// ── Managed tooltip system ──────────────────────────────────────────────────
160
161/// Duration of the slide-down enter animation.
162const ENTER_DURATION: Duration = Duration::from_millis(150);
163/// Duration of the position-slide animation when switching tooltips.
164const SLIDE_DURATION: Duration = Duration::from_millis(200);
165
166#[derive(Default)]
167struct TooltipMotion {
168    drawn_size: Option<Size<Pixels>>,
169    switch_from: Option<(usize, Size<Pixels>)>,
170}
171
172impl TooltipMotion {
173    fn switch_from(&mut self, epoch: usize) -> Option<Size<Pixels>> {
174        match self.switch_from {
175            Some((switch_epoch, size)) if switch_epoch == epoch => Some(size),
176            _ => {
177                self.switch_from = self.drawn_size.map(|size| (epoch, size));
178                self.drawn_size
179            }
180        }
181    }
182}
183
184pub(crate) fn tooltip_renderer()
185-> impl Fn(AnyView, BaseTooltipTransition, &mut Window, &mut App) -> AnyElement + 'static {
186    let motion = Rc::new(RefCell::new(TooltipMotion::default()));
187    move |content_view, transition, window, cx| {
188        render_tooltip(content_view, transition, &motion, window, cx)
189    }
190}
191
192fn render_tooltip(
193    content_view: AnyView,
194    transition: BaseTooltipTransition,
195    motion: &Rc<RefCell<TooltipMotion>>,
196    window: &mut Window,
197    cx: &mut App,
198) -> AnyElement {
199    let record_size = {
200        let motion = motion.clone();
201        move |bounds: Bounds<Pixels>, _: &mut Window, _: &mut App| {
202            motion.borrow_mut().drawn_size = Some(bounds.size);
203        }
204    };
205
206    match transition {
207        BaseTooltipTransition::Switch {
208            epoch,
209            previous,
210            current,
211        } => {
212            let same_row = (current.origin.y - previous.origin.y).abs() < px(10.);
213            if !same_row {
214                return div()
215                    .child(content_view)
216                    .on_prepaint(record_size)
217                    .into_any_element();
218            }
219            let resize = motion
220                .borrow_mut()
221                .switch_from(epoch)
222                .map(|from| (from, natural_size(&content_view, window, cx)))
223                .filter(|(from, to)| from != to);
224            let dx = current.center().x - previous.center().x;
225            EffectTransition::new(SLIDE_DURATION)
226                .ease(ease_in_out_cubic)
227                .slide_x(-dx, px(0.))
228                .when_some(resize, |transition, (from, to)| {
229                    transition
230                        .width(from.width, to.width)
231                        .height(from.height, to.height)
232                })
233                .apply(
234                    div()
235                        .child(content_view)
236                        .when_some(resize, |this, (from, to)| {
237                            this.overflow_hidden()
238                                .when(from.height == to.height, |this| this.whitespace_nowrap())
239                        })
240                        .on_prepaint(record_size),
241                    ElementId::NamedInteger("tooltip-slide".into(), epoch as u64),
242                )
243                .into_any_element()
244        }
245        BaseTooltipTransition::Enter { epoch } => EffectTransition::new(ENTER_DURATION)
246            .ease(ease_out_cubic)
247            .slide_y(px(4.), px(0.))
248            .fade(0.0, 1.0)
249            .apply(
250                div().child(content_view).on_prepaint(record_size),
251                ElementId::NamedInteger("tooltip-enter".into(), epoch as u64),
252            )
253            .into_any_element(),
254    }
255}
256
257fn natural_size(content_view: &AnyView, window: &mut Window, cx: &mut App) -> Size<Pixels> {
258    div()
259        .child(content_view.clone())
260        .into_any_element()
261        .layout_as_root(
262            size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
263            window,
264            cx,
265        )
266}
267
268// ── Extension trait for managed tooltips ─────────────────────────────────────
269
270// ── Shared tooltip state for components ─────────────────────────────────────
271
272/// Shared tooltip state that components (Button, Switch, Checkbox, Radio, etc.)
273/// can embed to get `.tooltip()` support with minimal boilerplate.
274#[derive(Default)]
275pub(crate) struct ComponentTooltip {
276    pub text: Option<(
277        SharedString,
278        Option<(Rc<Box<dyn Action>>, Option<SharedString>)>,
279    )>,
280    pub builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyView>>,
281    pub show_delay: Option<Duration>,
282}
283
284impl ComponentTooltip {
285    /// Apply this tooltip to a `Stateful<Div>` (or any `ManagedTooltipExt` element).
286    pub fn apply<E: ManagedTooltipExt>(self, el: E) -> E {
287        let show_delay = self.show_delay;
288        if let Some(builder) = self.builder {
289            el.managed_tooltip_with(None, show_delay, move |window, cx| builder(window, cx))
290        } else if let Some((text, action)) = self.text {
291            el.managed_tooltip_with(None, show_delay, move |window, cx| {
292                Tooltip::new(text.clone())
293                    .when_some(action.clone(), |this, (action, context)| {
294                        this.action(
295                            action.boxed_clone().as_ref(),
296                            context.as_ref().map(|c| c.as_ref()),
297                        )
298                    })
299                    .build(window, cx)
300            })
301        } else {
302            el
303        }
304    }
305}
306
307// ── Internal managed tooltip trait ──────────────────────────────────────────
308
309#[derive(Default)]
310struct TooltipLifetime(Rc<()>);
311
312#[derive(Default)]
313struct TooltipTrigger {
314    id: Option<GlobalElementId>,
315    lifetime: Weak<()>,
316    bounds: Bounds<Pixels>,
317}
318
319pub(crate) trait ManagedTooltipExt:
320    StatefulInteractiveElement + crate::ElementExt + Sized
321{
322    fn managed_tooltip(
323        self,
324        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
325    ) -> Self {
326        self.managed_tooltip_with(None, None, build_tooltip)
327    }
328
329    fn managed_tooltip_at(
330        self,
331        placement: Placement,
332        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
333    ) -> Self {
334        self.managed_tooltip_with(Some(placement), None, build_tooltip)
335    }
336
337    fn managed_tooltip_with(
338        self,
339        preferred_placement: Option<Placement>,
340        show_delay: Option<Duration>,
341        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
342    ) -> Self {
343        let build_tooltip = Rc::new(build_tooltip);
344        let trigger = Rc::new(RefCell::new(TooltipTrigger::default()));
345        let trigger_writer = trigger.clone();
346
347        self.on_prepaint(move |bounds, window, _| {
348            let id = window.with_global_id("managed-tooltip-trigger".into(), |id, _| id.clone());
349            // GPUI retains keyed element state for cached subtrees too, and
350            // drops it after a frame that no longer contains the trigger.
351            let lifetime = window.with_element_state(&id, |state: Option<TooltipLifetime>, _| {
352                let state = state.unwrap_or_default();
353                (Rc::downgrade(&state.0), state)
354            });
355            *trigger_writer.borrow_mut() = TooltipTrigger {
356                id: Some(id),
357                lifetime,
358                bounds,
359            };
360        })
361        .on_hover({
362            let trigger = trigger.clone();
363            move |hovered, window, cx| {
364                let trigger = trigger.borrow();
365                let Some(id) = trigger.id.as_ref() else {
366                    return;
367                };
368                let bounds = trigger.bounds;
369                // A press keeps the tooltip dismissed until the pointer leaves
370                // the trigger. This also drops the hover-enter that a click
371                // removing the trigger dispatches to the stale frame.
372                if *hovered && WindowState::is_tooltip_trigger_pressed(bounds, window, cx) {
373                    return;
374                }
375                if let Some(overlay) = WindowState::tooltip_overlay_for_trigger(
376                    id,
377                    trigger.lifetime.clone(),
378                    *hovered,
379                    window,
380                    cx,
381                ) {
382                    if *hovered {
383                        overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
384                            let build = build_tooltip.clone();
385                            let request = BaseTooltipRequest::new(bounds, move |window, cx| {
386                                build(window, cx)
387                            });
388                            let request = match preferred_placement {
389                                Some(placement) => request.with_placement(placement),
390                                None => request,
391                            };
392                            let request = match show_delay {
393                                Some(delay) => request.with_show_delay(delay),
394                                None => request,
395                            };
396                            o.request_show(request, window, cx);
397                        });
398                    } else {
399                        overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
400                            o.request_hide(window, cx);
401                        });
402                    }
403                }
404            }
405        })
406        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
407            WindowState::press_tooltip_trigger(trigger.borrow().bounds, window, cx);
408            if let Some(overlay) = WindowState::tooltip_overlay(window, cx) {
409                overlay.update(cx, |overlay, cx| {
410                    overlay.hide(cx);
411                });
412            }
413        })
414    }
415}
416
417impl<E: StatefulInteractiveElement + crate::ElementExt> ManagedTooltipExt for E {}
418
419#[cfg(test)]
420mod tests {
421    use std::{cell::Cell, rc::Rc, time::Duration};
422
423    use gpui::{
424        AppContext as _, Context, Entity, InputEvent as _, InteractiveElement as _, IntoElement,
425        MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _, Render,
426        StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext, Window,
427        div, point, prelude::FluentBuilder as _, px,
428    };
429
430    use super::{ManagedTooltipExt as _, SLIDE_DURATION};
431    use crate::Root;
432
433    // Distinct scene markers let assertions observe retained tooltip output
434    // without requiring its renderer to run on every frame.
435    const TOOLTIP_COLORS: [u32; 2] = [0x7a135e, 0x136b7a];
436
437    fn assert_tooltip_painted(cx: &mut VisualTestContext, index: usize, shown: bool) {
438        draw(cx);
439        let painted = cx.update(|window, _| {
440            let marker: gpui::Background = gpui::rgb(TOOLTIP_COLORS[index]).into();
441            window
442                .painted_quads()
443                .iter()
444                .any(|quad| quad.background == marker)
445        });
446        assert_eq!(
447            painted, shown,
448            "tooltip {index} visibility in the rendered scene"
449        );
450    }
451
452    /// A trigger that removes itself when clicked, like a button that
453    /// replaces the view it sits in.
454    struct Probe {
455        shown: bool,
456        removes_on_click: bool,
457        builds: Rc<Cell<usize>>,
458    }
459
460    impl Render for Probe {
461        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
462            let builds = self.builds.clone();
463            div().size_full().when(self.shown, |this| {
464                this.child(
465                    div()
466                        .id("trigger")
467                        .absolute()
468                        .left(px(10.))
469                        .top(px(10.))
470                        .w(px(100.))
471                        .h(px(30.))
472                        .managed_tooltip(move |_, cx| {
473                            builds.set(builds.get() + 1);
474                            cx.new(|_| super::Tooltip::new("tip").bg(gpui::rgb(TOOLTIP_COLORS[0])))
475                                .into()
476                        })
477                        .on_click(cx.listener(|this, _, _, cx| {
478                            if this.removes_on_click {
479                                this.shown = false;
480                            }
481                            cx.notify();
482                        })),
483                )
484            })
485        }
486    }
487
488    fn open(
489        cx: &mut TestAppContext,
490        removes_on_click: bool,
491        builds: Rc<Cell<usize>>,
492    ) -> (VisualTestContext, Entity<Probe>) {
493        cx.update(|cx| {
494            crate::init(cx);
495            // These tests cover tooltip lifetime, not intermediate fade frames.
496            cx.set_reduce_motion(true);
497        });
498        let probe = cx.new(|_| Probe {
499            shown: true,
500            removes_on_click,
501            builds,
502        });
503        let window = cx.update(|cx| {
504            cx.open_window(Default::default(), |window, cx| {
505                cx.new(|cx| Root::new(probe.clone(), window, cx))
506            })
507            .unwrap()
508        });
509        let mut cx = VisualTestContext::from_window(window.into(), cx);
510        draw(&mut cx);
511        (cx, probe)
512    }
513
514    /// Presses at `at` and releases a pixel away, as most real clicks do.
515    fn click_with_drift(cx: &mut VisualTestContext, at: gpui::Point<gpui::Pixels>) {
516        let drift = point(at.x + px(1.), at.y);
517        cx.simulate_mouse_down(at, MouseButton::Left, Default::default());
518        cx.simulate_mouse_move(drift, Some(MouseButton::Left), Default::default());
519        cx.simulate_mouse_up(drift, MouseButton::Left, Default::default());
520    }
521
522    fn draw(cx: &mut VisualTestContext) {
523        cx.update(|window, cx| {
524            let _ = window.draw(cx);
525        })
526    }
527
528    /// Lets any show delay or grace period run out, then draws.
529    fn wait(cx: &mut VisualTestContext) {
530        cx.executor().advance_clock(Duration::from_secs(1));
531        cx.run_until_parked();
532        draw(cx);
533    }
534
535    struct AdjacentTriggers;
536
537    impl Render for AdjacentTriggers {
538        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
539            div().size_full().children((0..2).map(|index| {
540                div()
541                    .id(("trigger", index))
542                    .absolute()
543                    .left(px(10. + index as f32 * 100.))
544                    .top(px(10.))
545                    .w(px(100.))
546                    .h(px(30.))
547                    .managed_tooltip(move |_, cx| {
548                        cx.new(|_| super::Tooltip::new("tip").bg(gpui::rgb(TOOLTIP_COLORS[index])))
549                            .into()
550                    })
551            }))
552        }
553    }
554
555    fn open_adjacent_triggers(
556        cx: &mut TestAppContext,
557    ) -> (VisualTestContext, Entity<AdjacentTriggers>) {
558        cx.update(|cx| {
559            crate::init(cx);
560            // These tests cover tooltip lifetime, not intermediate fade frames.
561            cx.set_reduce_motion(true);
562        });
563        let probe = cx.new(|_| AdjacentTriggers);
564        let window = cx.update(|cx| {
565            cx.open_window(Default::default(), |window, cx| {
566                cx.new(|cx| Root::new(probe.clone(), window, cx))
567            })
568            .unwrap()
569        });
570        let mut cx = VisualTestContext::from_window(window.into(), cx);
571        draw(&mut cx);
572        (cx, probe)
573    }
574
575    fn assert_tooltip_shown(cx: &mut VisualTestContext, index: usize) {
576        assert_tooltip_painted(cx, index, true);
577        assert_tooltip_painted(cx, 1 - index, false);
578    }
579
580    /// A managed trigger inside an element that has a native GPUI tooltip.
581    struct NestedInNative;
582
583    impl Render for NestedInNative {
584        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
585            div().size_full().child(
586                div()
587                    .id("native")
588                    .absolute()
589                    .left(px(0.))
590                    .top(px(0.))
591                    .w(px(300.))
592                    .h(px(100.))
593                    .tooltip(|_, cx| {
594                        cx.new(|_| super::Tooltip::new("outer").bg(gpui::rgb(TOOLTIP_COLORS[0])))
595                            .into()
596                    })
597                    .child(
598                        div()
599                            .id("managed")
600                            .absolute()
601                            .left(px(10.))
602                            .top(px(10.))
603                            .w(px(100.))
604                            .h(px(30.))
605                            .managed_tooltip(|_, cx| {
606                                cx.new(|_| {
607                                    super::Tooltip::new("inner").bg(gpui::rgb(TOOLTIP_COLORS[1]))
608                                })
609                                .into()
610                            }),
611                    ),
612            )
613        }
614    }
615
616    #[gpui::test]
617    fn a_managed_tooltip_hides_the_native_tooltip_around_it(cx: &mut TestAppContext) {
618        cx.update(|cx| {
619            crate::init(cx);
620            cx.set_reduce_motion(true);
621        });
622        let view = cx.new(|_| NestedInNative);
623        let window = cx.update(|cx| {
624            cx.open_window(Default::default(), |window, cx| {
625                cx.new(|cx| Root::new(view.clone(), window, cx))
626            })
627            .unwrap()
628        });
629        let mut cx = VisualTestContext::from_window(window.into(), cx);
630        draw(&mut cx);
631
632        let outside_the_trigger = point(px(200.), px(50.));
633        let on_the_trigger = point(px(50.), px(25.));
634        for (at, shown) in [
635            (outside_the_trigger, 0),
636            (on_the_trigger, 1),
637            (outside_the_trigger, 0),
638        ] {
639            cx.simulate_mouse_move(at, None, Default::default());
640            wait(&mut cx);
641            assert_tooltip_shown(&mut cx, shown);
642        }
643    }
644
645    #[gpui::test]
646    fn tooltips_switch_in_both_directions(cx: &mut TestAppContext) {
647        let (mut cx, probe) = open_adjacent_triggers(cx);
648        for (step, index) in [0, 1, 0].into_iter().enumerate() {
649            let at = point(px(50. + index as f32 * 100.), px(25.));
650            cx.simulate_mouse_move(at, None, Default::default());
651            if step > 0 {
652                draw(&mut cx);
653                assert_tooltip_shown(&mut cx, index);
654            }
655            wait(&mut cx);
656            assert_tooltip_shown(&mut cx, index);
657            // Rebuilding the triggers must preserve ownership for hover-leave.
658            cx.update(|_, cx| probe.update(cx, |_, cx| cx.notify()));
659            draw(&mut cx);
660        }
661        cx.simulate_mouse_move(point(px(300.), px(300.)), None, Default::default());
662        wait(&mut cx);
663        assert_tooltip_painted(&mut cx, 0, false);
664        assert_tooltip_painted(&mut cx, 1, false);
665    }
666
667    #[gpui::test]
668    fn leaving_a_trigger_does_not_cancel_the_next_tooltip_delay(cx: &mut TestAppContext) {
669        for (source, destination) in [(0, 1), (1, 0)] {
670            let (mut cx, _) = open_adjacent_triggers(cx);
671            cx.simulate_mouse_move(
672                point(px(50. + source as f32 * 100.), px(25.)),
673                None,
674                Default::default(),
675            );
676            cx.executor().advance_clock(Duration::from_millis(100));
677            cx.run_until_parked();
678            cx.simulate_mouse_move(
679                point(px(50. + destination as f32 * 100.), px(25.)),
680                None,
681                Default::default(),
682            );
683            wait(&mut cx);
684            assert_tooltip_shown(&mut cx, destination);
685        }
686    }
687
688    /// A press dismisses the tooltip, and it stays dismissed while the
689    /// pointer stays on the trigger; leaving and coming back shows it again.
690    #[gpui::test]
691    fn a_press_dismisses_the_tooltip_until_the_pointer_leaves(cx: &mut TestAppContext) {
692        let builds = Rc::new(Cell::new(0));
693        let (mut cx, _) = open(cx, false, builds.clone());
694        let at = point(px(50.), px(25.));
695        cx.simulate_mouse_move(at, None, Default::default());
696        wait(&mut cx);
697        assert!(builds.get() > 0, "the hovered trigger shows its tooltip");
698
699        // Hover reads false while the button is held, so the move after the
700        // release is a hover-enter that must not show the tooltip.
701        click_with_drift(&mut cx, at);
702        cx.simulate_mouse_move(point(px(52.), px(25.)), None, Default::default());
703        wait(&mut cx);
704        assert_tooltip_painted(&mut cx, 0, false);
705
706        cx.simulate_mouse_move(point(px(300.), px(300.)), None, Default::default());
707        wait(&mut cx);
708        cx.simulate_mouse_move(at, None, Default::default());
709        wait(&mut cx);
710        assert_tooltip_painted(&mut cx, 0, true);
711    }
712
713    /// A pointer move that lands between the release and the next frame is
714    /// dispatched to the old frame, where the trigger is still hovered, so it
715    /// used to request the tooltip again. The trigger is gone from the next
716    /// frame, nothing ever sent the hover-leave, and the tooltip appeared
717    /// after the show delay and stayed.
718    #[gpui::test]
719    fn clicking_a_trigger_away_does_not_leave_its_tooltip(cx: &mut TestAppContext) {
720        let builds = Rc::new(Cell::new(0));
721        let (mut cx, _) = open(cx, true, builds.clone());
722
723        let at = point(px(50.), px(25.));
724        cx.simulate_mouse_move(at, None, Default::default());
725        draw(&mut cx);
726        wait(&mut cx);
727        draw(&mut cx);
728        assert!(builds.get() > 0, "the hovered trigger shows its tooltip");
729
730        // Press, drift a pixel while held, release, and drift again before
731        // the next frame is drawn.
732        cx.simulate_mouse_down(at, MouseButton::Left, Default::default());
733        let drift = point(px(51.), px(25.));
734        cx.simulate_mouse_move(drift, Some(MouseButton::Left), Default::default());
735        // One update, so no frame is drawn between the two: the test
736        // platform otherwise draws a dirty window after every event.
737        cx.update(|window, cx| {
738            window.dispatch_event(
739                MouseUpEvent {
740                    button: MouseButton::Left,
741                    position: drift,
742                    modifiers: Default::default(),
743                    click_count: 1,
744                }
745                .to_platform_input(),
746                cx,
747            );
748            window.dispatch_event(
749                MouseMoveEvent {
750                    position: point(px(52.), px(25.)),
751                    pressed_button: None,
752                    modifiers: Default::default(),
753                }
754                .to_platform_input(),
755                cx,
756            );
757        });
758        draw(&mut cx);
759        wait(&mut cx);
760
761        let before = builds.get();
762        draw(&mut cx);
763        assert_eq!(
764            builds.get(),
765            before,
766            "no tooltip may be shown for a trigger the click removed"
767        );
768    }
769
770    /// A trigger that a click removed never reports a hover-leave, so the
771    /// press must end when the pointer moves away, or a trigger later shown
772    /// at the same bounds would lose its tooltip.
773    #[gpui::test]
774    fn a_press_on_a_removed_trigger_ends_when_the_pointer_moves_away(cx: &mut TestAppContext) {
775        let builds = Rc::new(Cell::new(0));
776        let (mut cx, probe) = open(cx, true, builds.clone());
777        let at = point(px(50.), px(25.));
778        cx.simulate_mouse_move(at, None, Default::default());
779        wait(&mut cx);
780
781        cx.simulate_click(at, Default::default());
782        wait(&mut cx);
783        cx.simulate_mouse_move(point(px(300.), px(300.)), None, Default::default());
784        wait(&mut cx);
785
786        cx.update(|_, cx| {
787            probe.update(cx, |probe, cx| {
788                probe.shown = true;
789                cx.notify();
790            })
791        });
792        wait(&mut cx);
793        let before = builds.get();
794        cx.simulate_mouse_move(at, None, Default::default());
795        wait(&mut cx);
796        draw(&mut cx);
797        assert!(
798            builds.get() > before,
799            "the trigger shown again has its tooltip"
800        );
801    }
802
803    struct Buttons {
804        shown: [bool; 2],
805        delay: Duration,
806    }
807
808    impl Render for Buttons {
809        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
810            div().size_full().children((0..2).filter_map(|index| {
811                self.shown[index].then(|| {
812                    crate::button::Button::new(("button", index))
813                        .absolute()
814                        .left(px(10. + index as f32 * 100.))
815                        .top(px(10.))
816                        .w(px(80.))
817                        .h(px(30.))
818                        .label(if index == 0 { "A" } else { "B" })
819                        .tooltip(if index == 0 { "First" } else { "Second" })
820                        .tooltip_show_delay(self.delay)
821                })
822            }))
823        }
824    }
825
826    struct CachedButtons(Entity<Buttons>);
827
828    impl Render for CachedButtons {
829        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
830            div().size_full().child(
831                self.0
832                    .clone()
833                    .cached(gpui::StyleRefinement::default().size_full()),
834            )
835        }
836    }
837
838    fn open_buttons(
839        cx: &mut TestAppContext,
840        shown: [bool; 2],
841        delay: Duration,
842    ) -> (VisualTestContext, Entity<Buttons>, Rc<Cell<usize>>) {
843        cx.update(|cx| {
844            crate::init(cx);
845            // These tests cover tooltip lifetime, not intermediate fade frames.
846            cx.set_reduce_motion(true);
847        });
848        let buttons = cx.new(|_| Buttons { shown, delay });
849        let window = cx.update(|cx| {
850            cx.open_window(Default::default(), |window, cx| {
851                let content = cx.new(|_| CachedButtons(buttons.clone()));
852                cx.new(|cx| Root::new(content, window, cx))
853            })
854            .unwrap()
855        });
856        let mut cx = VisualTestContext::from_window(window.into(), cx);
857        draw(&mut cx);
858        let builds = Rc::new(Cell::new(0));
859        cx.update(|window, cx| {
860            let builds = builds.clone();
861            let render_tooltip = super::tooltip_renderer();
862            // Observe the real Button's overlay without changing Base's public
863            // API or adding test-only markup to the production Tooltip.
864            super::WindowState::tooltip_overlay(window, cx)
865                .unwrap()
866                .update(cx, |overlay, _| {
867                    *overlay =
868                        std::mem::take(overlay).render_with(move |view, transition, window, cx| {
869                            builds.set(builds.get() + 1);
870                            div()
871                                .bg(gpui::rgb(TOOLTIP_COLORS[0]))
872                                .child(render_tooltip(view, transition, window, cx))
873                                .into_any_element()
874                        });
875                });
876        });
877        (cx, buttons, builds)
878    }
879
880    #[gpui::test]
881    fn removing_button_hides_visible_tooltip(cx: &mut TestAppContext) {
882        let (mut cx, buttons, _) = open_buttons(cx, [true, false], Duration::ZERO);
883        cx.simulate_mouse_move(point(px(50.), px(25.)), None, Default::default());
884        wait(&mut cx);
885        assert_tooltip_painted(&mut cx, 0, true);
886        // A redraw reusing the cached button subtree preserves the owner.
887        draw(&mut cx);
888        assert_tooltip_painted(&mut cx, 0, true);
889        cx.update(|_, cx| {
890            buttons.update(cx, |buttons, cx| {
891                buttons.shown[0] = false;
892                cx.notify();
893            })
894        });
895        draw(&mut cx);
896        cx.run_until_parked();
897        assert_tooltip_painted(&mut cx, 0, false);
898    }
899
900    #[gpui::test]
901    fn removing_button_cancels_pending_tooltip(cx: &mut TestAppContext) {
902        let (mut cx, buttons, builds) = open_buttons(cx, [true, false], Duration::from_millis(500));
903        cx.simulate_mouse_move(point(px(50.), px(25.)), None, Default::default());
904        draw(&mut cx);
905        // Finish the hover frame and drain its deferred cleanup before removal,
906        // without advancing the pending tooltip's show delay.
907        cx.run_until_parked();
908        assert_eq!(builds.get(), 0, "tooltip is still pending");
909        cx.update(|_, cx| {
910            buttons.update(cx, |buttons, cx| {
911                buttons.shown[0] = false;
912                cx.notify();
913            })
914        });
915        draw(&mut cx);
916        cx.run_until_parked();
917        wait(&mut cx);
918        assert_eq!(
919            builds.get(),
920            0,
921            "a removed trigger must never build its tooltip"
922        );
923        assert_tooltip_painted(&mut cx, 0, false);
924    }
925
926    #[gpui::test]
927    fn pending_button_shows_after_deferred_work_drains(cx: &mut TestAppContext) {
928        let (mut cx, _, builds) = open_buttons(cx, [true, false], Duration::from_millis(500));
929        cx.simulate_mouse_move(point(px(50.), px(25.)), None, Default::default());
930        draw(&mut cx);
931        cx.run_until_parked();
932        assert_eq!(builds.get(), 0, "tooltip is still pending");
933        wait(&mut cx);
934        assert!(
935            builds.get() > 0,
936            "a surviving trigger builds its delayed tooltip"
937        );
938        assert_tooltip_painted(&mut cx, 0, true);
939    }
940
941    #[gpui::test]
942    fn removing_old_button_preserves_new_tooltip(cx: &mut TestAppContext) {
943        let (mut cx, buttons, _) = open_buttons(cx, [true, true], Duration::ZERO);
944        cx.simulate_mouse_move(point(px(50.), px(25.)), None, Default::default());
945        wait(&mut cx);
946        cx.simulate_mouse_move(point(px(150.), px(25.)), None, Default::default());
947        wait(&mut cx);
948        assert_tooltip_painted(&mut cx, 0, true);
949        cx.update(|_, cx| {
950            buttons.update(cx, |buttons, cx| {
951                buttons.shown[0] = false;
952                cx.notify();
953            })
954        });
955        draw(&mut cx);
956        cx.run_until_parked();
957        assert_tooltip_painted(&mut cx, 0, true);
958    }
959
960    struct TextTooltip(&'static str);
961
962    impl Render for TextTooltip {
963        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
964            let text = self.0;
965            div().size_full().child(
966                div()
967                    .id("trigger")
968                    .absolute()
969                    .left(px(10.))
970                    .top(px(10.))
971                    .w(px(100.))
972                    .h(px(30.))
973                    .managed_tooltip(move |_, cx| {
974                        cx.new(|_| {
975                            super::Tooltip::new(text)
976                                .max_w(px(200.))
977                                .bg(gpui::rgb(TOOLTIP_COLORS[0]))
978                        })
979                        .into()
980                    }),
981            )
982        }
983    }
984
985    fn tooltip_size(cx: &mut TestAppContext, text: &'static str) -> gpui::Size<f32> {
986        cx.update(|cx| {
987            crate::init(cx);
988            cx.set_reduce_motion(true);
989        });
990        let view = cx.new(|_| TextTooltip(text));
991        let window = cx.update(|cx| {
992            cx.open_window(Default::default(), |window, cx| {
993                cx.new(|cx| Root::new(view.clone(), window, cx))
994            })
995            .unwrap()
996        });
997        let mut cx = VisualTestContext::from_window(window.into(), cx);
998        draw(&mut cx);
999        cx.simulate_mouse_move(point(px(50.), px(25.)), None, Default::default());
1000        wait(&mut cx);
1001        cx.update(|window, _| {
1002            let marker: gpui::Background = gpui::rgb(TOOLTIP_COLORS[0]).into();
1003            let scale = window.scale_factor();
1004            let quad = window
1005                .painted_quads()
1006                .into_iter()
1007                .find(|quad| quad.background == marker)
1008                .expect("tooltip is painted");
1009            gpui::size(
1010                quad.bounds.size.width.0 / scale,
1011                quad.bounds.size.height.0 / scale,
1012            )
1013        })
1014    }
1015
1016    #[gpui::test]
1017    fn long_text_wraps_within_max_width(cx: &mut TestAppContext) {
1018        let line = tooltip_size(cx, "tip");
1019        let long = tooltip_size(
1020            cx,
1021            "Band AD_WBGT_20240621T00-20240621T23 - WBGT [time=477499] with a few more words",
1022        );
1023        assert_eq!(long.width, 200.);
1024        assert!(
1025            long.height > line.height * 2.,
1026            "long text wraps onto several lines: {long:?} vs {line:?}"
1027        );
1028    }
1029
1030    const SWITCH_TEXTS: [&str; 2] = ["Cancel", "Do something awesome"];
1031
1032    struct ShortAndLongTriggers;
1033
1034    impl Render for ShortAndLongTriggers {
1035        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1036            div().size_full().children((0..2).map(|index| {
1037                div()
1038                    .id(("trigger", index))
1039                    .absolute()
1040                    .left(px(200. + index as f32 * 100.))
1041                    .top(px(10.))
1042                    .w(px(100.))
1043                    .h(px(30.))
1044                    .managed_tooltip(move |_, cx| {
1045                        cx.new(|_| {
1046                            super::Tooltip::new(SWITCH_TEXTS[index])
1047                                .bg(gpui::rgb(TOOLTIP_COLORS[index]))
1048                        })
1049                        .into()
1050                    })
1051            }))
1052        }
1053    }
1054
1055    fn painted_width(cx: &mut VisualTestContext, index: usize) -> f32 {
1056        // The animation's frame request only reaches the test window through
1057        // the platform frame callback, which a direct draw skips. Without a
1058        // refresh, GPUI Fast replays the retained first frame (fade at 0).
1059        cx.update(|window, _| window.refresh());
1060        draw(cx);
1061        cx.update(|window, _| {
1062            let marker: gpui::Background = gpui::rgb(TOOLTIP_COLORS[index]).into();
1063            let quad = window
1064                .painted_quads()
1065                .into_iter()
1066                .find(|quad| quad.background == marker)
1067                .expect("tooltip is painted");
1068            quad.bounds.size.width.0 / window.scale_factor()
1069        })
1070    }
1071
1072    #[gpui::test]
1073    fn switching_tooltips_animates_the_width(cx: &mut TestAppContext) {
1074        cx.update(crate::init);
1075        let view = cx.new(|_| ShortAndLongTriggers);
1076        let window = cx.update(|cx| {
1077            cx.open_window(Default::default(), |window, cx| {
1078                cx.new(|cx| Root::new(view.clone(), window, cx))
1079            })
1080            .unwrap()
1081        });
1082        let mut cx = VisualTestContext::from_window(window.into(), cx);
1083        draw(&mut cx);
1084
1085        cx.simulate_mouse_move(point(px(250.), px(25.)), None, Default::default());
1086        wait(&mut cx);
1087        let short = painted_width(&mut cx, 0);
1088
1089        cx.simulate_mouse_move(point(px(350.), px(25.)), None, Default::default());
1090        cx.run_until_parked();
1091        let start = painted_width(&mut cx, 1);
1092        cx.executor().advance_clock(SLIDE_DURATION / 2);
1093        let middle = painted_width(&mut cx, 1);
1094        wait(&mut cx);
1095        let long = painted_width(&mut cx, 1);
1096
1097        assert!(short < long, "{short} < {long}");
1098        assert_eq!(start, short, "the switch starts at the previous width");
1099        assert!(
1100            short < middle && middle < long,
1101            "{short} < {middle} < {long}"
1102        );
1103    }
1104}