Skip to main content

gpui_material_components/overlay/
tooltip.rs

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