Skip to main content

gpui_material_components/overlay/
tooltip.rs

1mod appearance;
2mod interaction;
3mod label;
4
5use std::{cell::Cell, rc::Rc};
6
7use gpui::{
8    AccessibleAction, Anchor, AnyElement, App, Bounds, ElementId, Entity, FocusHandle,
9    InteractiveElement, IntoElement, KeyBinding, MouseButton, ParentElement, Pixels, RenderOnce,
10    Role, SharedString, Size, StatefulInteractiveElement, Styled, Window, canvas, deferred, div,
11    point, prelude::FluentBuilder, px,
12};
13use gpui_base::{Link, Placement, TestSupportExt};
14use gpui_material_foundation::{ThemeScope, current_material_theme};
15use gpui_material_theme::{CornerShape, Direction, Elevation, TypeRole};
16
17use appearance::{Appearance, SurfaceStyle};
18use interaction::{Dismiss, Interaction};
19
20pub use appearance::{TooltipCaret, TooltipColors, TooltipPlacement};
21pub use gpui_base::Positioner as TooltipPositioner;
22pub use interaction::TooltipState;
23pub use label::Label;
24
25use crate::{
26    Button, ButtonColors, ButtonVariant,
27    button_style::finite_length,
28    motion::{OverlayMotion, ScaledOverlay},
29};
30
31gpui::actions!(
32    material_tooltip,
33    [
34        FocusTooltipAction,
35        FocusTooltipTrigger,
36        DismissTooltip,
37        ActivateTooltipAction
38    ]
39);
40
41pub(crate) fn init(cx: &mut App) {
42    cx.bind_keys([
43        KeyBinding::new("tab", FocusTooltipAction, Some("MaterialTooltipTrigger")),
44        KeyBinding::new(
45            "shift-tab",
46            FocusTooltipTrigger,
47            Some("MaterialTooltipContent"),
48        ),
49        KeyBinding::new("escape", DismissTooltip, Some("MaterialTooltip")),
50        KeyBinding::new(
51            "enter",
52            ActivateTooltipAction,
53            Some("MaterialTooltipAction"),
54        ),
55        KeyBinding::new(
56            "space",
57            ActivateTooltipAction,
58            Some("MaterialTooltipAction"),
59        ),
60    ]);
61}
62
63type TooltipCallback = Rc<dyn Fn(&mut Window, &mut App)>;
64type PositionProvider = Box<dyn Fn(Bounds<Pixels>, Size<Pixels>, Direction) -> TooltipPositioner>;
65
66struct TooltipAction {
67    label: SharedString,
68    focus: FocusHandle,
69    callback: TooltipCallback,
70}
71
72/// A transient plain or rich Material tooltip, or a persistent rich tooltip
73/// with caller-owned visibility.
74#[derive(IntoElement)]
75pub struct Tooltip {
76    id: ElementId,
77    trigger: Option<AnyElement>,
78    text: SharedString,
79    title: Option<SharedString>,
80    action: Option<TooltipAction>,
81    title_content: Option<AnyElement>,
82    body_content: Option<AnyElement>,
83    action_content: Option<AnyElement>,
84    link: Option<(SharedString, TooltipCallback)>,
85    rich: bool,
86    trigger_focus: Option<FocusHandle>,
87    focus_target: Option<FocusHandle>,
88    focusable: bool,
89    enable_user_input: bool,
90    persistent: Option<Entity<TooltipState>>,
91    label_visible: Option<bool>,
92    on_dismiss_request: Option<TooltipCallback>,
93    placement: TooltipPlacement,
94    offset: Pixels,
95    positioner: Option<PositionProvider>,
96    appearance: Appearance,
97}
98
99impl Tooltip {
100    pub fn plain(
101        id: impl Into<ElementId>,
102        trigger: impl IntoElement,
103        text: impl Into<SharedString>,
104    ) -> Self {
105        Self {
106            id: id.into(),
107            trigger: Some(trigger.into_any_element()),
108            text: text.into(),
109            title: None,
110            action: None,
111            title_content: None,
112            body_content: None,
113            action_content: None,
114            link: None,
115            rich: false,
116            trigger_focus: None,
117            focus_target: None,
118            focusable: false,
119            enable_user_input: true,
120            persistent: None,
121            label_visible: None,
122            on_dismiss_request: None,
123            placement: TooltipPlacement::Above,
124            offset: px(4.),
125            positioner: None,
126            appearance: Appearance::default(),
127        }
128    }
129
130    pub fn rich(
131        id: impl Into<ElementId>,
132        trigger: impl IntoElement,
133        title: impl Into<SharedString>,
134        text: impl Into<SharedString>,
135    ) -> Self {
136        Self {
137            title: Some(title.into()),
138            rich: true,
139            ..Self::plain(id, trigger, text)
140        }
141    }
142
143    /// Adds a text button to a rich tooltip.
144    pub fn action(
145        mut self,
146        label: impl Into<SharedString>,
147        focus: &FocusHandle,
148        callback: impl Fn(&mut Window, &mut App) + 'static,
149    ) -> Self {
150        self.rich = true;
151        self.action = Some(TooltipAction {
152            label: label.into(),
153            focus: focus.clone(),
154            callback: Rc::new(callback),
155        });
156        self
157    }
158
159    pub fn title_content(mut self, content: impl IntoElement) -> Self {
160        self.rich = true;
161        self.title_content = Some(content.into_any_element());
162        self
163    }
164
165    pub fn body_content(mut self, content: impl IntoElement) -> Self {
166        self.body_content = Some(content.into_any_element());
167        self
168    }
169
170    /// Replaces the standard action with caller-authored interactive content.
171    pub fn action_content(mut self, content: impl IntoElement) -> Self {
172        self.rich = true;
173        self.action_content = Some(content.into_any_element());
174        self
175    }
176
177    /// Adds a semantic link. The callback owns the destination and navigation.
178    pub fn link(
179        mut self,
180        label: impl Into<SharedString>,
181        callback: impl Fn(&mut Window, &mut App) + 'static,
182    ) -> Self {
183        self.rich = true;
184        self.link = Some((label.into(), Rc::new(callback)));
185        self
186    }
187
188    /// Uses the trigger's focus handle for keyboard activation and restoration.
189    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
190        self.trigger_focus = Some(focus.clone());
191        self
192    }
193
194    /// Uses the caller's first focus target inside the tooltip.
195    pub fn focus_target(mut self, focus: &FocusHandle) -> Self {
196        self.focus_target = Some(focus.clone());
197        self
198    }
199
200    /// Moves focus to the tooltip when it opens. The default preserves focus.
201    pub fn focusable(mut self, focusable: bool) -> Self {
202        self.focusable = focusable;
203        self
204    }
205
206    /// Enables automatic trigger input for the chosen visibility mode.
207    pub fn enable_user_input(mut self, enable: bool) -> Self {
208        self.enable_user_input = enable;
209        self
210    }
211
212    /// Uses caller-owned visibility for a persistent rich tooltip.
213    pub fn persistent(mut self, state: &Entity<TooltipState>) -> Self {
214        self.rich = true;
215        self.persistent = Some(state.clone());
216        self
217    }
218
219    /// Handles Escape or a persistent tooltip's outside press. A persistent
220    /// tooltip with a handler closes when the owner accepts the request.
221    pub fn on_dismiss_request(
222        mut self,
223        callback: impl Fn(&mut Window, &mut App) + 'static,
224    ) -> Self {
225        self.on_dismiss_request = Some(Rc::new(callback));
226        self
227    }
228
229    pub fn placement(mut self, placement: TooltipPlacement) -> Self {
230        self.placement = placement;
231        self
232    }
233
234    /// Gap between the trigger and surface in logical pixels.
235    pub fn offset(mut self, offset: Pixels) -> Self {
236        self.offset = finite_length(offset);
237        self
238    }
239
240    /// Replaces the standard placement with a positioner built from the trigger
241    /// bounds, viewport size, and direction. The host applies viewport margins.
242    pub fn positioner(
243        mut self,
244        positioner: impl Fn(Bounds<Pixels>, Size<Pixels>, Direction) -> TooltipPositioner + 'static,
245    ) -> Self {
246        self.positioner = Some(Box::new(positioner));
247        self
248    }
249
250    pub fn caret(mut self, caret: TooltipCaret) -> Self {
251        self.appearance.caret = Some(caret);
252        self
253    }
254
255    pub fn max_width(mut self, width: Pixels) -> Self {
256        self.appearance.max_width = Some(finite_length(width));
257        self
258    }
259
260    pub fn shape(mut self, shape: CornerShape) -> Self {
261        self.appearance.shape = Some(shape);
262        self
263    }
264
265    pub fn colors(mut self, colors: TooltipColors) -> Self {
266        self.appearance.colors = colors;
267        self
268    }
269
270    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
271        self.appearance.tonal_elevation = elevation;
272        self
273    }
274
275    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
276        self.appearance.shadow_elevation = Some(elevation);
277        self
278    }
279}
280
281#[derive(Clone, Default)]
282struct Geometry {
283    anchor: Rc<Cell<Option<Bounds<Pixels>>>>,
284    placed: Rc<Cell<Bounds<Pixels>>>,
285    side: Rc<Cell<Option<Placement>>>,
286}
287
288impl RenderOnce for Tooltip {
289    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
290        let label = self.label_visible.is_some();
291        let state = window.use_keyed_state(
292            (self.id.clone(), "tooltip-interaction"),
293            cx,
294            Interaction::new,
295        );
296        let geometry = window
297            .use_keyed_state((self.id.clone(), "tooltip-geometry"), cx, |_, _| {
298                Geometry::default()
299            })
300            .read(cx)
301            .clone();
302        let transient = !label && self.enable_user_input && self.persistent.is_none();
303        state.update(cx, |state, cx| {
304            state.configure(
305                transient,
306                self.trigger_focus.as_ref(),
307                self.persistent.as_ref(),
308                window,
309                cx,
310            )
311        });
312        let open = self.label_visible.unwrap_or_else(|| {
313            self.persistent.as_ref().map_or_else(
314                || state.read(cx).is_open(window, cx),
315                |state| state.read(cx).is_visible(),
316            )
317        });
318        let surface = state.read(cx).surface.clone();
319        let first = self.focus_target.clone().or_else(|| {
320            self.action
321                .as_ref()
322                .filter(|_| self.action_content.is_none())
323                .map(|action| action.focus.clone())
324        });
325        let anchor = geometry.anchor.get();
326        state.update(cx, |state, cx| {
327            state.present(
328                !label && open && anchor.is_some(),
329                self.trigger_focus.as_ref(),
330                self.focusable
331                    .then(|| first.clone().unwrap_or_else(|| surface.clone())),
332                window,
333                cx,
334            )
335        });
336
337        let dismiss = Dismiss {
338            transient: state.clone(),
339            persistent: self.persistent.clone(),
340            request: self.on_dismiss_request.clone(),
341        };
342        let on_escape = dismiss.clone();
343        let hover = state.clone();
344        let measured = geometry.anchor.clone();
345        let trigger = div()
346            .id(if label {
347                "label-anchor"
348            } else {
349                "tooltip-trigger"
350            })
351            .role(Role::Group)
352            .aria_description(self.text.clone())
353            .when(self.persistent.is_some(), |trigger| {
354                trigger.aria_expanded(open)
355            })
356            .when(open && !label, |trigger| {
357                trigger.when_some(first.clone(), |trigger, first| {
358                    trigger.key_context("MaterialTooltipTrigger").on_action(
359                        move |_: &FocusTooltipAction, window, cx| first.focus(window, cx),
360                    )
361                })
362            })
363            .when(transient, |trigger| {
364                trigger.on_hover(move |hovering, window, cx| {
365                    hover.update(cx, |state, cx| state.hover(false, *hovering, window, cx));
366                })
367            })
368            .when_some(
369                self.persistent
370                    .clone()
371                    .filter(|_| self.enable_user_input && !label),
372                |trigger, visibility| {
373                    let press = state.clone();
374                    let release = state.clone();
375                    let release_outside = state.clone();
376                    let key = visibility.clone();
377                    let accessible = visibility.clone();
378                    trigger
379                        .capture_any_mouse_down(move |event, _, cx| {
380                            if event.button == MouseButton::Left {
381                                press.update(cx, |state, _| state.pressed = true);
382                            }
383                        })
384                        .capture_any_mouse_up(move |event, _, cx| {
385                            if event.button == MouseButton::Left
386                                && release.update(cx, |state, _| std::mem::take(&mut state.pressed))
387                            {
388                                visibility.update(cx, |state, cx| state.show(cx));
389                            }
390                        })
391                        .on_mouse_up_out(MouseButton::Left, move |_, _, cx| {
392                            release_outside.update(cx, |state, _| state.pressed = false);
393                        })
394                        .capture_key_down(move |event, _, cx| {
395                            if !event.is_held
396                                && matches!(event.keystroke.key.as_str(), "enter" | "space")
397                            {
398                                key.update(cx, |state, cx| state.show(cx));
399                            }
400                        })
401                        .on_a11y_action(AccessibleAction::Click, move |_, _, cx| {
402                            accessible.update(cx, |state, cx| state.show(cx));
403                        })
404                },
405            )
406            .relative()
407            .children(self.trigger.take())
408            .child(
409                canvas(
410                    move |bounds, window, _| {
411                        let anchor = (!label
412                            || !bounds.intersect(&window.content_mask().bounds).is_empty())
413                        .then_some(bounds);
414                        if measured.replace(anchor) != anchor && open {
415                            window.refresh();
416                        }
417                    },
418                    |_, _, _, _| {},
419                )
420                .absolute()
421                .inset_0(),
422            );
423        let mut root =
424            div()
425                .id(self.id.clone())
426                .relative()
427                .child(trigger)
428                .when(open && !label, |root| {
429                    root.key_context("MaterialTooltip").on_action(
430                        move |_: &DismissTooltip, window, cx| {
431                            on_escape.request(window, cx);
432                        },
433                    )
434                });
435        let (Some(motion), Some(anchor)) =
436            (OverlayMotion::sample(&self.id, open, window, cx), anchor)
437        else {
438            return root;
439        };
440        let last = geometry.placed.get();
441        if !open && last.size.width <= px(0.) {
442            return root;
443        }
444
445        let viewport = window.viewport_size();
446        let theme = current_material_theme(window, cx);
447        let direction = theme.layout.direction;
448        let style = self.appearance.resolve(self.rich, viewport, motion, &theme);
449        let view = tooltip_surface(&mut self, open || label, style, motion, window, cx);
450        let margin = self.appearance.margin(viewport);
451        let view = if label {
452            // The overlay owns the accessible text for its decorative children.
453            div()
454                .id("label-content")
455                .role(Role::Group)
456                .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
457                .child(
458                    view.max_h((viewport.height - margin * 2.) * motion.scale)
459                        .overflow_hidden(),
460                )
461                .into_any_element()
462        } else {
463            view.into_any_element()
464        };
465        let caret = self.appearance.caret.take();
466        let resolved_side = geometry.side.clone();
467        let shift_tab = first.clone();
468        let return_focus = self.trigger_focus;
469        let anchor_bounds = geometry.anchor.clone();
470        let tip = div()
471            .id(match (label, open) {
472                (true, true) => "label",
473                (true, false) => "label-exit",
474                (false, true) => "tooltip",
475                (false, false) => "tooltip-exit",
476            })
477            .relative()
478            .test_support()
479            .opacity(motion.alpha)
480            .when(open, |tip| {
481                tip.role(Role::Tooltip)
482                    .aria_label(self.text)
483                    .when(!label, |tip| {
484                        tip.track_focus(&surface)
485                            .key_context("MaterialTooltipContent")
486                            .on_action(move |_: &FocusTooltipTrigger, window, cx| {
487                                if let Some(trigger) = &return_focus
488                                    && shift_tab
489                                        .as_ref()
490                                        .is_some_and(|first| first.is_focused(window))
491                                {
492                                    trigger.focus(window, cx);
493                                } else {
494                                    cx.propagate();
495                                }
496                            })
497                    })
498                    .when(transient, |tip| {
499                        tip.on_hover(move |hovering, window, cx| {
500                            state.update(cx, |state, cx| state.hover(true, *hovering, window, cx));
501                        })
502                    })
503                    .when(!label && dismiss.persistent.is_some(), |tip| {
504                        tip.on_mouse_down_out(move |event, window, cx| {
505                            if !anchor_bounds
506                                .get()
507                                .is_some_and(|anchor| anchor.contains(&event.position))
508                            {
509                                dismiss.request(window, cx);
510                            }
511                        })
512                    })
513            })
514            .child(view)
515            .children(caret.map(|caret| {
516                canvas(
517                    |_, _, _| (),
518                    move |bounds, _, window, _| {
519                        caret.paint(bounds, anchor, resolved_side.get(), style, window);
520                    },
521                )
522                .absolute()
523                .inset_0()
524            }));
525        let scaled = ScaledOverlay::new(
526            motion
527                .text(tip, window)
528                .when(!open, |tip| tip.w(last.size.width * motion.scale)),
529            motion,
530            |_| point(0.5, 0.5),
531        );
532        let positioner = if open {
533            let positioner = self.positioner.map_or_else(
534                || {
535                    TooltipPositioner::side(anchor)
536                        .placement(self.placement.physical(direction))
537                        .offset(self.offset)
538                },
539                |positioner| positioner(anchor, viewport, direction),
540            );
541            positioner
542                .margin(margin)
543                .when(!label, TooltipPositioner::occlude)
544                .on_position(move |resolved| {
545                    geometry.placed.set(resolved.bounds);
546                    geometry.side.set(resolved.placement);
547                })
548                .child(scaled)
549        } else {
550            TooltipPositioner::corner(Anchor::TopLeft, last.origin)
551                .margin(margin)
552                .child(scaled.width(last.size.width))
553        };
554        root = root.child(deferred(ThemeScope::inherit(positioner, window, cx)).with_priority(100));
555        root
556    }
557}
558
559fn tooltip_surface(
560    tooltip: &mut Tooltip,
561    open: bool,
562    style: SurfaceStyle,
563    motion: OverlayMotion,
564    window: &Window,
565    cx: &App,
566) -> gpui::Div {
567    let title = tooltip.title.take().map(IntoElement::into_any_element);
568    let title = if open {
569        tooltip.title_content.take().or(title)
570    } else {
571        title
572    };
573    let body = if open {
574        tooltip.body_content.take()
575    } else {
576        None
577    }
578    .unwrap_or_else(|| tooltip.text.clone().into_any_element());
579    let action = if open {
580        tooltip.action_content.take()
581    } else {
582        None
583    }
584    .or_else(|| {
585        tooltip
586            .action
587            .take()
588            .map(|action| render_action(action, open, style, motion, window, cx))
589    });
590    let link = tooltip.link.take().map(|(label, callback)| {
591        if open {
592            let activate = callback.clone();
593            Link::new("tooltip-link")
594                .accessibility_label(label.clone())
595                .text_color(style.action)
596                .underline()
597                .on_activate(move |_, window, cx| callback(window, cx))
598                .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
599                    activate(window, cx)
600                })
601                .child(label)
602                .into_any_element()
603        } else {
604            div()
605                .text_color(style.action)
606                .child(label)
607                .into_any_element()
608        }
609    });
610    let text_role = if tooltip.rich {
611        TypeRole::BodyMedium
612    } else {
613        TypeRole::BodySmall
614    };
615    style
616        .apply(div())
617        .children(title.map(|title| {
618            super::text_style(
619                div().text_color(style.title).child(title),
620                TypeRole::TitleSmall,
621                motion.scale,
622                window,
623                cx,
624            )
625        }))
626        .child(super::text_style(
627            div().text_color(style.content).child(body),
628            text_role,
629            motion.scale,
630            window,
631            cx,
632        ))
633        .children(action.map(|action| div().text_color(style.action).child(action)))
634        .children(link)
635}
636
637fn render_action(
638    action: TooltipAction,
639    open: bool,
640    style: SurfaceStyle,
641    motion: OverlayMotion,
642    window: &Window,
643    cx: &App,
644) -> AnyElement {
645    if open {
646        let activate = action.callback.clone();
647        return div()
648            .id("tooltip-action-keys")
649            .key_context("MaterialTooltipAction")
650            .on_action(move |_: &ActivateTooltipAction, window, cx| activate(window, cx))
651            .child(
652                Button::new("tooltip-action", action.label)
653                    .track_focus(&action.focus)
654                    .variant(ButtonVariant::Text)
655                    .scale(motion.scale)
656                    .colors(ButtonColors {
657                        content: style.action_override,
658                        ..Default::default()
659                    })
660                    .on_activate(move |window, cx| (action.callback)(window, cx)),
661            )
662            .into_any_element();
663    }
664    let density = current_material_theme(window, cx).layout.density;
665    div()
666        .min_h(motion.px(density.interactive_size(40.)))
667        .flex()
668        .items_center()
669        .justify_center()
670        .child(
671            super::text_style(
672                div().px(motion.px(16.)).min_w_0().truncate(),
673                TypeRole::LabelLarge,
674                motion.scale,
675                window,
676                cx,
677            )
678            .text_color(style.action)
679            .child(action.label),
680        )
681        .into_any_element()
682}