Skip to main content

gpui_base/
tooltip.rs

1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4    AnyElement, AnyTooltip, AnyView, App, AppContext as _, Bounds, Context, Div, ElementId,
5    EmptyView, Global, InteractiveElement, IntoElement, ParentElement, Pixels, Render, RenderOnce,
6    Role, Stateful, StatefulInteractiveElement, Styled, Task, Window, canvas, deferred, div,
7    prelude::FluentBuilder as _, px,
8};
9
10use crate::{Placement, Positioner};
11
12const TOOLTIP_PRIORITY: usize = 200;
13const WINDOW_MARGIN: Pixels = px(4.);
14
15type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;
16type TooltipRenderer = Rc<dyn Fn(AnyView, TooltipTransition, &mut Window, &mut App) -> AnyElement>;
17
18/// An unstyled tooltip popup.
19///
20/// This corresponds to Base UI's `Tooltip.Popup`: it owns the accessible
21/// tooltip role and accepts application-owned content and presentation.
22#[derive(IntoElement)]
23pub struct Tooltip {
24    base: Stateful<Div>,
25}
26
27impl Tooltip {
28    pub fn new(id: impl Into<ElementId>) -> Self {
29        Self {
30            base: div().id(id).role(Role::Tooltip),
31        }
32    }
33}
34
35impl Styled for Tooltip {
36    fn style(&mut self) -> &mut gpui::StyleRefinement {
37        self.base.style()
38    }
39}
40
41impl ParentElement for Tooltip {
42    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
43        self.base.extend(children);
44    }
45}
46
47impl RenderOnce for Tooltip {
48    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
49        self.base
50    }
51}
52
53/// Application-wide timing for tooltips shown through [`TooltipOverlay`].
54///
55/// Read on every show and hide request, so installing new defaults takes
56/// effect in windows that are already open.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub struct TooltipDefaults {
59    show_delay: Duration,
60    grace_period: Duration,
61}
62
63impl Global for TooltipDefaults {}
64
65impl TooltipDefaults {
66    /// Creates the Base defaults: a 500 ms show delay and a 300 ms grace period.
67    pub fn new() -> Self {
68        Self {
69            show_delay: Duration::from_millis(500),
70            grace_period: Duration::from_millis(300),
71        }
72    }
73
74    /// Sets how long the pointer must rest on a trigger before its tooltip shows.
75    pub fn with_show_delay(mut self, delay: Duration) -> Self {
76        self.show_delay = delay;
77        self
78    }
79
80    /// Sets how long a tooltip stays after the pointer leaves its trigger.
81    ///
82    /// Entering another trigger within this period switches to its tooltip
83    /// without waiting for the show delay.
84    pub fn with_grace_period(mut self, period: Duration) -> Self {
85        self.grace_period = period;
86        self
87    }
88
89    /// How long the pointer must rest on a trigger before its tooltip shows.
90    pub fn show_delay(&self) -> Duration {
91        self.show_delay
92    }
93
94    /// How long a tooltip stays after the pointer leaves its trigger.
95    pub fn grace_period(&self) -> Duration {
96        self.grace_period
97    }
98
99    /// Installs these defaults for the whole application.
100    pub fn install(self, cx: &mut App) {
101        cx.set_global(self);
102    }
103
104    /// Returns the installed defaults, or the Base ones when none were.
105    pub fn global(cx: &App) -> Self {
106        cx.try_global::<Self>().copied().unwrap_or_default()
107    }
108}
109
110impl Default for TooltipDefaults {
111    fn default() -> Self {
112        Self::new()
113    }
114}
115
116/// Content requested by a tooltip trigger.
117#[derive(Clone)]
118pub struct TooltipRequest {
119    build: TooltipBuilder,
120    trigger_bounds: Bounds<Pixels>,
121    preferred_placement: Option<Placement>,
122    offset: Pixels,
123    show_delay: Option<Duration>,
124}
125
126impl TooltipRequest {
127    pub fn new(
128        trigger_bounds: Bounds<Pixels>,
129        build: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
130    ) -> Self {
131        Self {
132            build: Rc::new(build),
133            trigger_bounds,
134            preferred_placement: None,
135            offset: px(0.),
136            show_delay: None,
137        }
138    }
139
140    /// Prefers a side for the tooltip, falling back when it does not fit.
141    pub fn with_placement(mut self, placement: Placement) -> Self {
142        self.preferred_placement = Some(placement);
143        self
144    }
145
146    #[deprecated(note = "use `with_placement`")]
147    pub fn placement(self, placement: Placement) -> Self {
148        self.with_placement(placement)
149    }
150
151    /// Sets the gap between the trigger and tooltip. Defaults to zero.
152    pub fn with_offset(mut self, offset: Pixels) -> Self {
153        self.offset = offset;
154        self
155    }
156
157    /// Overrides [`TooltipDefaults::show_delay`] for this trigger.
158    pub fn with_show_delay(mut self, delay: Duration) -> Self {
159        self.show_delay = Some(delay);
160        self
161    }
162}
163
164/// Presentation transition requested by the Base tooltip lifecycle.
165#[derive(Clone, Copy, Debug)]
166pub enum TooltipTransition {
167    Enter {
168        epoch: usize,
169    },
170    Switch {
171        epoch: usize,
172        previous: Bounds<Pixels>,
173        current: Bounds<Pixels>,
174    },
175}
176
177/// Per-window tooltip provider and overlay.
178///
179/// Show requests are ignored on iOS and Android, where touch input must not
180/// open hover tooltips. This does not control GPUI's native `.tooltip()` API.
181pub struct TooltipOverlay {
182    enabled: bool,
183    content: Option<TooltipRequest>,
184    previous_bounds: Option<Bounds<Pixels>>,
185    epoch: usize,
186    had_recent_tooltip: bool,
187    animation_epoch: usize,
188    is_switching: bool,
189    show_task: Option<Task<()>>,
190    hide_task: Option<Task<()>>,
191    renderer: TooltipRenderer,
192    /// An empty GPUI tooltip that holds the window's one tooltip place while
193    /// this overlay shows one, so a native `.tooltip()` around the trigger
194    /// does not show as well.
195    native_placeholder: Option<AnyView>,
196}
197
198impl TooltipOverlay {
199    pub fn new() -> Self {
200        Self {
201            enabled: !crate::is_mobile(),
202            content: None,
203            previous_bounds: None,
204            epoch: 0,
205            had_recent_tooltip: false,
206            animation_epoch: 0,
207            is_switching: false,
208            show_task: None,
209            hide_task: None,
210            renderer: Rc::new(|view, _, _, _| div().child(view).into_any_element()),
211            native_placeholder: None,
212        }
213    }
214
215    pub fn render_with(
216        mut self,
217        renderer: impl Fn(AnyView, TooltipTransition, &mut Window, &mut App) -> AnyElement + 'static,
218    ) -> Self {
219        self.renderer = Rc::new(renderer);
220        self
221    }
222
223    fn next_epoch(&mut self) -> usize {
224        self.epoch += 1;
225        self.epoch
226    }
227
228    pub fn request_show(
229        &mut self,
230        content: TooltipRequest,
231        window: &mut Window,
232        cx: &mut Context<Self>,
233    ) {
234        // Gate both delayed display and the immediate grace-period switch.
235        // Keep this in Base so every managed component shares the policy.
236        if !self.enabled {
237            return;
238        }
239        self.hide_task = None;
240        let show_delay = content
241            .show_delay
242            .unwrap_or_else(|| TooltipDefaults::global(cx).show_delay);
243        let was_visible = self.content.is_some();
244        if was_visible || self.had_recent_tooltip || show_delay.is_zero() {
245            self.previous_bounds = self.content.as_ref().map(|content| content.trigger_bounds);
246            self.content = Some(content);
247            self.show_task = None;
248            self.is_switching = was_visible;
249            self.animation_epoch += 1;
250            cx.notify();
251            return;
252        }
253
254        let epoch = self.next_epoch();
255        self.show_task = Some(cx.spawn_in(window, async move |this, cx| {
256            cx.background_executor().timer(show_delay).await;
257            let _ = this.update_in(cx, |this, _, cx| {
258                if this.epoch == epoch {
259                    this.content = Some(content);
260                    this.previous_bounds = None;
261                    this.is_switching = false;
262                    this.animation_epoch += 1;
263                    cx.notify();
264                }
265            });
266        }));
267    }
268
269    pub fn request_hide(&mut self, window: &mut Window, cx: &mut Context<Self>) {
270        self.show_task = None;
271        if self.content.is_none() {
272            return;
273        }
274        let epoch = self.next_epoch();
275        let grace_period = TooltipDefaults::global(cx).grace_period;
276        self.had_recent_tooltip = true;
277        self.hide_task = Some(cx.spawn_in(window, async move |this, cx| {
278            cx.background_executor().timer(grace_period).await;
279            let _ = this.update_in(cx, |this, _, cx| {
280                if this.epoch == epoch {
281                    this.content = None;
282                    this.previous_bounds = None;
283                    this.had_recent_tooltip = false;
284                    cx.notify();
285                }
286            });
287        }));
288    }
289
290    pub fn hide(&mut self, cx: &mut Context<Self>) {
291        let changed = self.content.is_some()
292            || self.previous_bounds.is_some()
293            || self.had_recent_tooltip
294            || self.show_task.is_some()
295            || self.hide_task.is_some();
296        self.content = None;
297        self.previous_bounds = None;
298        self.had_recent_tooltip = false;
299        self.is_switching = false;
300        self.show_task = None;
301        self.hide_task = None;
302        if changed {
303            cx.notify();
304        }
305    }
306}
307
308impl Default for TooltipOverlay {
309    fn default() -> Self {
310        Self::new()
311    }
312}
313
314impl Render for TooltipOverlay {
315    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
316        let Some(content) = self.content.as_ref() else {
317            return div().into_any_element();
318        };
319        let view = (content.build)(window, cx);
320        let transition = match (self.is_switching, self.previous_bounds) {
321            (true, Some(previous)) => TooltipTransition::Switch {
322                epoch: self.animation_epoch,
323                previous,
324                current: content.trigger_bounds,
325            },
326            _ => TooltipTransition::Enter {
327                epoch: self.animation_epoch,
328            },
329        };
330        let rendered = (self.renderer)(view, transition, window, cx);
331        let placeholder = self
332            .native_placeholder
333            .get_or_insert_with(|| cx.new(|_| EmptyView).into())
334            .clone();
335        deferred(
336            div()
337                .child(
338                    TooltipPositioner::new(content.trigger_bounds)
339                        .offset(content.offset)
340                        .when_some(content.preferred_placement, |this, placement| {
341                            this.placement(placement)
342                        })
343                        .child(rendered),
344                )
345                // GPUI draws only the last tooltip requested in a frame, and
346                // this layer is prepainted after the content and its popups.
347                .child(canvas(
348                    move |_, window, _| {
349                        window.set_tooltip(AnyTooltip {
350                            view: placeholder,
351                            mouse_position: window.mouse_position(),
352                            check_visible_and_update: Rc::new(|_, _, _| true),
353                        });
354                    },
355                    |_, _, _, _| {},
356                )),
357        )
358        .with_priority(TOOLTIP_PRIORITY)
359        .into_any_element()
360    }
361}
362
363/// An unstyled tooltip positioner with viewport-aware flipping and clamping.
364///
365/// This is a tooltip-named view of [`crate::Positioner`]'s side placement. It
366/// adds no element of its own; the shared positioner is what gets rendered.
367pub struct TooltipPositioner(Positioner);
368
369impl TooltipPositioner {
370    pub fn new(trigger_bounds: Bounds<Pixels>) -> Self {
371        Self(Positioner::side(trigger_bounds).margin(WINDOW_MARGIN))
372    }
373
374    pub fn placement(mut self, placement: Placement) -> Self {
375        self.0 = self.0.placement(placement);
376        self
377    }
378
379    /// Sets the gap between the trigger and tooltip. Defaults to zero.
380    pub fn offset(mut self, offset: Pixels) -> Self {
381        self.0 = self.0.offset(offset);
382        self
383    }
384}
385
386impl ParentElement for TooltipPositioner {
387    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
388        self.0.extend(elements);
389    }
390}
391
392impl IntoElement for TooltipPositioner {
393    type Element = Positioner;
394
395    fn into_element(self) -> Self::Element {
396        self.0
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403    use gpui::{point, size};
404
405    fn bounds(x: f32, y: f32, width: f32, height: f32) -> Bounds<Pixels> {
406        Bounds::new(point(px(x), px(y)), size(px(width), px(height)))
407    }
408
409    #[gpui::test]
410    fn request_offset_reaches_popup_layout_and_preserves_edge_placement(
411        cx: &mut gpui::TestAppContext,
412    ) {
413        use std::cell::Cell;
414
415        struct Content(Rc<Cell<Option<Bounds<Pixels>>>>);
416        impl Render for Content {
417            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
418                let measured = self.0.clone();
419                gpui::canvas(
420                    move |bounds, _, _| measured.set(Some(bounds)),
421                    |_, _, _, _| {},
422                )
423                .w(px(40.))
424                .h(px(24.))
425            }
426        }
427
428        struct Harness(gpui::Entity<TooltipOverlay>);
429        impl Render for Harness {
430            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
431                div().size_full().child(self.0.clone())
432            }
433        }
434
435        let measured = Rc::new(Cell::new(None));
436        let (harness, cx) = cx.add_window_view(|_, cx| Harness(cx.new(|_| TooltipOverlay::new())));
437        let overlay = cx.update(|_, cx| harness.read(cx).0.clone());
438        cx.simulate_resize(size(px(500.), px(400.)));
439        cx.run_until_parked();
440        cx.update(|window, cx| window.draw(cx).clear(cx));
441        let height = cx.update(|window, _| f32::from(window.viewport_size().height));
442        for (trigger, placement, offset, expected) in [
443            (
444                bounds(100., 100., 40., 20.),
445                Placement::Top,
446                None,
447                point(px(100.), px(76.)),
448            ),
449            (
450                bounds(100., 100., 40., 20.),
451                Placement::Top,
452                Some(px(4.)),
453                point(px(100.), px(72.)),
454            ),
455            (
456                bounds(100., 100., 40., 20.),
457                Placement::Bottom,
458                Some(px(8.)),
459                point(px(100.), px(128.)),
460            ),
461            (
462                bounds(100., 100., 40., 20.),
463                Placement::Left,
464                Some(px(4.)),
465                point(px(56.), px(98.)),
466            ),
467            (
468                bounds(100., 100., 40., 20.),
469                Placement::Right,
470                Some(px(8.)),
471                point(px(148.), px(98.)),
472            ),
473            (
474                bounds(100., 4., 40., 20.),
475                Placement::Top,
476                Some(px(4.)),
477                point(px(100.), px(28.)),
478            ),
479            (
480                bounds(100., height - 24., 40., 20.),
481                Placement::Bottom,
482                Some(px(4.)),
483                point(px(100.), px(height - 52.)),
484            ),
485            (
486                bounds(0., 100., 20., 20.),
487                Placement::Top,
488                Some(px(8.)),
489                point(px(4.), px(68.)),
490            ),
491        ] {
492            let output = measured.clone();
493            let request = TooltipRequest::new(trigger, move |_, cx| {
494                cx.new(|_| Content(output.clone())).into()
495            })
496            .with_placement(placement)
497            .with_show_delay(Duration::ZERO);
498            let request = match offset {
499                Some(offset) => request.with_offset(offset),
500                None => request,
501            };
502            measured.set(None);
503            cx.update(|window, cx| {
504                overlay.update(cx, |overlay, cx| overlay.request_show(request, window, cx));
505                window.draw(cx).clear(cx);
506            });
507            assert_eq!(
508                measured.get(),
509                Some(Bounds::new(expected, size(px(40.), px(24.))))
510            );
511        }
512    }
513
514    #[gpui::test]
515    fn provider_owns_grace_switch_and_dismiss(cx: &mut gpui::TestAppContext) {
516        let state = cx.update(|cx| cx.new(|_| TooltipOverlay::new()));
517        let cx = cx.add_empty_window();
518        cx.update(|window, cx| {
519            state.update(cx, |tooltip, cx| {
520                tooltip.had_recent_tooltip = true;
521                tooltip.request_show(
522                    TooltipRequest::new(bounds(0., 0., 20., 20.), |_, _| {
523                        panic!("content is not rendered by this lifecycle test")
524                    }),
525                    window,
526                    cx,
527                );
528            });
529        });
530        cx.update(|_, cx| assert!(state.read(cx).content.is_some()));
531
532        cx.update(|_, cx| {
533            state.update(cx, |tooltip, cx| tooltip.hide(cx));
534        });
535        cx.update(|_, cx| assert!(state.read(cx).content.is_none()));
536    }
537
538    #[gpui::test]
539    fn show_delay_follows_defaults_and_request_override(cx: &mut gpui::TestAppContext) {
540        cx.update(|cx| {
541            TooltipDefaults::new()
542                .with_show_delay(Duration::from_millis(100))
543                .install(cx)
544        });
545        // The delayed show updates the overlay in the window it was drawn in.
546        let (state, cx) = cx.add_window_view(|_, _| TooltipOverlay::new());
547        cx.update(|window, cx| window.draw(cx).clear(cx));
548        let request = || {
549            TooltipRequest::new(bounds(0., 0., 20., 20.), |_, cx| {
550                cx.new(|_| gpui::Empty).into()
551            })
552        };
553
554        cx.update(|window, cx| {
555            state.update(cx, |tooltip, cx| {
556                tooltip.request_show(request(), window, cx)
557            });
558        });
559        cx.executor().advance_clock(Duration::from_millis(99));
560        cx.run_until_parked();
561        cx.update(|_, cx| assert!(state.read(cx).content.is_none()));
562        cx.executor().advance_clock(Duration::from_millis(1));
563        cx.run_until_parked();
564        cx.update(|_, cx| assert!(state.read(cx).content.is_some()));
565
566        cx.update(|_, cx| state.update(cx, |tooltip, cx| tooltip.hide(cx)));
567        cx.update(|window, cx| {
568            state.update(cx, |tooltip, cx| {
569                tooltip.request_show(request().with_show_delay(Duration::ZERO), window, cx);
570                assert!(tooltip.content.is_some());
571                assert!(tooltip.show_task.is_none());
572            });
573        });
574    }
575
576    #[test]
577    fn tooltip_priority_exceeds_popup_layer() {
578        assert!(TOOLTIP_PRIORITY > crate::POPUP_PRIORITY);
579    }
580
581    #[gpui::test]
582    fn disabled_provider_ignores_delayed_and_immediate_requests(cx: &mut gpui::TestAppContext) {
583        let state = cx.update(|cx| {
584            cx.new(|_| TooltipOverlay {
585                enabled: false,
586                ..TooltipOverlay::new()
587            })
588        });
589        let cx = cx.add_empty_window();
590        for had_recent_tooltip in [false, true] {
591            cx.update(|window, cx| {
592                state.update(cx, |tooltip, cx| {
593                    tooltip.had_recent_tooltip = had_recent_tooltip;
594                    tooltip.request_show(
595                        TooltipRequest::new(bounds(0., 0., 20., 20.), |_, _| {
596                            panic!("disabled tooltips must not build content")
597                        }),
598                        window,
599                        cx,
600                    );
601                    assert!(tooltip.content.is_none());
602                    assert!(tooltip.show_task.is_none());
603                    assert!(tooltip.hide_task.is_none());
604                    assert_eq!(tooltip.animation_epoch, 0);
605                });
606            });
607        }
608    }
609}