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