Skip to main content

gpui_material_components/overlay/
tooltip.rs

1use std::{cell::Cell, rc::Rc, time::Duration};
2
3use gpui::{
4    Anchor, AnyElement, App, Bounds, Context, ElementId, FocusHandle, InteractiveElement,
5    IntoElement, KeyBinding, ParentElement, RenderOnce, Role, SharedString,
6    StatefulInteractiveElement, Styled, Subscription, Task, Window, div, point,
7    prelude::FluentBuilder, px,
8};
9use gpui_base::{Popup, TestSupportExt};
10use gpui_material_foundation::{Surface, color, window_material_theme};
11use gpui_material_theme::{ColorRole, Elevation, TypeRole, TypographyEmphasis};
12
13use crate::{
14    Button, ButtonVariant,
15    motion::{OverlayMotion, ScaledOverlay},
16};
17
18gpui::actions!(
19    material_tooltip,
20    [
21        FocusTooltipAction,
22        FocusTooltipTrigger,
23        DismissTooltip,
24        ActivateTooltipAction
25    ]
26);
27
28pub(crate) fn init(cx: &mut App) {
29    cx.bind_keys([
30        KeyBinding::new("tab", FocusTooltipAction, Some("MaterialTooltipTrigger")),
31        KeyBinding::new(
32            "shift-tab",
33            FocusTooltipTrigger,
34            Some("MaterialTooltipAction"),
35        ),
36        KeyBinding::new("escape", DismissTooltip, Some("MaterialTooltip")),
37        KeyBinding::new(
38            "enter",
39            ActivateTooltipAction,
40            Some("MaterialTooltipAction"),
41        ),
42        KeyBinding::new(
43            "space",
44            ActivateTooltipAction,
45            Some("MaterialTooltipAction"),
46        ),
47    ]);
48}
49
50/// A delayed plain or interactive rich Material tooltip anchored to a trigger.
51#[derive(IntoElement)]
52pub struct Tooltip {
53    id: ElementId,
54    trigger: AnyElement,
55    text: SharedString,
56    title: Option<SharedString>,
57    action: Option<TooltipAction>,
58    rich: bool,
59    trigger_focus: Option<FocusHandle>,
60}
61
62type TooltipCallback = std::rc::Rc<dyn Fn(&mut Window, &mut App)>;
63
64struct TooltipAction {
65    label: SharedString,
66    focus: FocusHandle,
67    callback: TooltipCallback,
68}
69
70impl Tooltip {
71    pub fn plain(
72        id: impl Into<ElementId>,
73        trigger: impl IntoElement,
74        text: impl Into<SharedString>,
75    ) -> Self {
76        Self {
77            id: id.into(),
78            trigger: trigger.into_any_element(),
79            text: text.into(),
80            title: None,
81            action: None,
82            rich: false,
83            trigger_focus: None,
84        }
85    }
86
87    pub fn rich(
88        id: impl Into<ElementId>,
89        trigger: impl IntoElement,
90        title: impl Into<SharedString>,
91        text: impl Into<SharedString>,
92    ) -> Self {
93        Self {
94            title: Some(title.into()),
95            rich: true,
96            ..Self::plain(id, trigger, text)
97        }
98    }
99
100    /// Adds a control to a rich tooltip.
101    pub fn action(
102        mut self,
103        label: impl Into<SharedString>,
104        focus: &FocusHandle,
105        callback: impl Fn(&mut Window, &mut App) + 'static,
106    ) -> Self {
107        self.rich = true;
108        self.action = Some(TooltipAction {
109            label: label.into(),
110            focus: focus.clone(),
111            callback: std::rc::Rc::new(callback),
112        });
113        self
114    }
115
116    /// Uses the focus handle associated with the trigger for keyboard activation.
117    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
118        self.trigger_focus = Some(focus.clone());
119        self
120    }
121}
122
123#[derive(Default)]
124struct TooltipState {
125    open: bool,
126    trigger_hover: bool,
127    surface_hover: bool,
128    keyboard: bool,
129    suppress_focus: bool,
130    surface_focus: bool,
131    task: Option<Task<()>>,
132    focus: Option<TooltipFocus>,
133}
134
135struct TooltipFocus {
136    trigger: FocusHandle,
137    surface: FocusHandle,
138    _subscriptions: [Subscription; 4],
139}
140
141impl TooltipState {
142    fn schedule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
143        let open = self.trigger_hover || self.surface_hover || self.keyboard || self.surface_focus;
144        self.task = None;
145        if open == self.open {
146            return;
147        }
148        if self.keyboard && open {
149            self.open = true;
150            window.refresh();
151            return;
152        }
153        let delay = if open {
154            Duration::from_millis(500)
155        } else {
156            Duration::from_millis(200)
157        };
158        self.task = Some(cx.spawn_in(window, async move |state, cx| {
159            cx.background_executor().timer(delay).await;
160            let _ = state.update_in(cx, |state, window, _| {
161                state.task = None;
162                state.open = open;
163                window.refresh();
164            });
165        }));
166    }
167
168    fn dismiss(&mut self, window: &mut Window) {
169        self.open = false;
170        self.task = None;
171        self.surface_hover = false;
172        self.keyboard = false;
173        self.surface_focus = false;
174        self.suppress_focus = true;
175        window.refresh();
176    }
177}
178
179impl RenderOnce for Tooltip {
180    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
181        let width = window.viewport_size().width * 0.75;
182        let role = if self.rich {
183            ColorRole::SurfaceContainer
184        } else {
185            ColorRole::InverseSurface
186        };
187        let state = window.use_keyed_state((self.id.clone(), "tooltip-state"), cx, |_, _| {
188            TooltipState::default()
189        });
190        if let Some(focus) = self.trigger_focus {
191            state.update(cx, |state, cx| {
192                if state
193                    .focus
194                    .as_ref()
195                    .is_some_and(|previous| previous.trigger == focus)
196                {
197                    return;
198                }
199                let enter = cx.entity().downgrade();
200                let leave = enter.clone();
201                let enter_surface = enter.clone();
202                let leave_surface = enter.clone();
203                let surface = cx.focus_handle();
204                let on_enter = window.on_focus_in(&focus, cx, move |window, cx| {
205                    let _ = enter.update(cx, |state, cx| {
206                        state.keyboard = !state.suppress_focus;
207                        state.schedule(window, cx);
208                    });
209                });
210                let on_leave = window.on_focus_out(&focus, cx, move |_, window, cx| {
211                    let _ = leave.update(cx, |state, cx| {
212                        state.keyboard = false;
213                        state.suppress_focus = false;
214                        state.schedule(window, cx);
215                    });
216                });
217                let on_enter_surface = window.on_focus_in(&surface, cx, move |window, cx| {
218                    let _ = enter_surface.update(cx, |state, cx| {
219                        state.surface_focus = true;
220                        state.schedule(window, cx);
221                    });
222                });
223                let on_leave_surface = window.on_focus_out(&surface, cx, move |_, window, cx| {
224                    let _ = leave_surface.update(cx, |state, cx| {
225                        state.surface_focus = false;
226                        state.schedule(window, cx);
227                    });
228                });
229                state.focus = Some(TooltipFocus {
230                    trigger: focus,
231                    surface,
232                    _subscriptions: [on_enter, on_leave, on_enter_surface, on_leave_surface],
233                });
234            });
235        }
236        let observed = state.read(cx);
237        let open = observed.open
238            || (!observed.suppress_focus
239                && observed.focus.as_ref().is_some_and(|focus| {
240                    focus.trigger.is_focused(window) || focus.surface.contains_focused(window, cx)
241                }))
242            || self
243                .action
244                .as_ref()
245                .is_some_and(|action| action.focus.is_focused(window));
246        let surface_focus = observed.focus.as_ref().map(|focus| focus.surface.clone());
247        let trigger_focus = observed.focus.as_ref().map(|focus| focus.trigger.clone());
248        let action_focus = self.action.as_ref().map(|action| action.focus.clone());
249        let dismiss_action = action_focus.clone();
250        let action_callback = self.action.as_ref().map(|action| action.callback.clone());
251        let hover = state.clone();
252        let dismiss = state.clone();
253        let to_action = action_focus;
254        let to_trigger = trigger_focus.clone();
255        let motion = OverlayMotion::sample(&self.id, open, window, cx);
256        let placement = window
257            .use_keyed_state((self.id.clone(), "last-tooltip-bounds"), cx, |_, _| {
258                Rc::new(Cell::new(Bounds::default()))
259            })
260            .read(cx)
261            .clone();
262        let last_bounds = placement.get();
263        let trigger_bounds = window
264            .use_keyed_state((self.id.clone(), "tooltip-anchor"), cx, |_, _| {
265                Rc::new(Cell::new(Bounds::default()))
266            })
267            .read(cx)
268            .clone();
269        let memory = trigger_bounds.clone();
270        let frame = trigger_bounds.get();
271        let surface_measurement = window
272            .use_keyed_state((self.id.clone(), "tooltip-height"), cx, |_, _| {
273                Rc::new(Cell::new(px(0.)))
274            })
275            .read(cx)
276            .clone();
277        let height = surface_measurement.get();
278        let preferred_height = if height > px(0.) {
279            height
280        } else {
281            px(if self.rich { 120. } else { 28. })
282        };
283        let above = frame.top() >= preferred_height + px(4.);
284
285        let pivot = point(0.5, 0.5);
286        let popup = Popup::new(
287            self.id.clone(),
288            div()
289                .id("tooltip-trigger")
290                .when(open && to_action.is_some(), |trigger| {
291                    trigger.key_context("MaterialTooltipTrigger").on_action(
292                        move |_: &FocusTooltipAction, window, cx| {
293                            if let Some(action) = &to_action {
294                                action.focus(window, cx);
295                            }
296                        },
297                    )
298                })
299                .role(Role::Group)
300                .aria_description(self.text.clone())
301                .on_hover(move |hovering, window, cx| {
302                    hover.update(cx, |state, cx| {
303                        state.trigger_hover = *hovering;
304                        state.schedule(window, cx);
305                    });
306                })
307                .relative()
308                .child(self.trigger)
309                .child(
310                    gpui::canvas(
311                        move |bounds, window, _| {
312                            if memory.replace(bounds) != bounds && open {
313                                window.refresh();
314                            }
315                        },
316                        |_, _, _, _| {},
317                    )
318                    .absolute()
319                    .inset_0(),
320                ),
321        )
322        .anchor(if above {
323            Anchor::BottomCenter
324        } else {
325            Anchor::TopCenter
326        })
327        .offset(px(4.))
328        .on_position(move |resolved, _| placement.set(resolved.bounds))
329        .when(open, |popup| {
330            popup
331                .key_context("MaterialTooltip")
332                .on_action(move |_: &DismissTooltip, window, cx| {
333                    let return_to = dismiss.read(cx).focus.as_ref().and_then(|focus| {
334                        (focus.surface.contains_focused(window, cx)
335                            || dismiss_action
336                                .as_ref()
337                                .is_some_and(|action| action.is_focused(window)))
338                        .then(|| focus.trigger.clone())
339                    });
340                    if let Some(trigger) = return_to {
341                        trigger.focus(window, cx);
342                    }
343                    dismiss.update(cx, |state, _| state.dismiss(window));
344                })
345        });
346        let content = motion.map(|motion| {
347            let spacing = motion.px(16.);
348            let dp = |value| motion.px(value);
349            let theme = window_material_theme(window, cx);
350            let tint = color(theme.colors.color(ColorRole::OnSurfaceVariant));
351            let corner = if self.rich {
352                gpui_material_theme::CornerRole::Medium
353            } else {
354                gpui_material_theme::CornerRole::ExtraSmall
355            }
356            .shape()
357            .radii(40., 24., theme.layout.direction)[0];
358            let label_type = TypeRole::LabelLarge.style(TypographyEmphasis::Baseline);
359            let content = div()
360                .relative()
361                .when(open, |tip| {
362                    tip.child(
363                        gpui::canvas(
364                            move |bounds, window, _| {
365                                let height = bounds.size.height / motion.scale;
366                                let fits_above = trigger_bounds.get().top() >= height + px(4.);
367                                let previous = surface_measurement.replace(height);
368                                if above != fits_above && (previous - height).abs() > px(1.) {
369                                    window.refresh();
370                                }
371                            },
372                            |_, _, _, _| {},
373                        )
374                        .absolute()
375                        .inset_0(),
376                    )
377                })
378                .opacity(motion.alpha)
379                .id(if open { "tooltip" } else { "tooltip-exit" })
380                .test_support()
381                .when(open, |tip| {
382                    tip.role(Role::Tooltip)
383                        .key_context("MaterialTooltipAction")
384                        .on_action(move |_: &FocusTooltipTrigger, window, cx| {
385                            if let Some(trigger) = &to_trigger {
386                                trigger.focus(window, cx);
387                            } else {
388                                cx.propagate();
389                            }
390                        })
391                        .on_action(move |_: &ActivateTooltipAction, window, cx| {
392                            if let Some(action) = &action_callback {
393                                action(window, cx);
394                            } else {
395                                cx.propagate();
396                            }
397                        })
398                        .when_some(surface_focus, |tip, focus| tip.track_focus(&focus))
399                        .aria_label(self.text.clone())
400                        .on_hover(move |hovering, window, cx| {
401                            state.update(cx, |state, cx| {
402                                state.surface_hover = *hovering;
403                                state.schedule(window, cx);
404                            });
405                        })
406                })
407                .child(
408                    Surface::new(role)
409                        .flex()
410                        .flex_col()
411                        .rounded(dp(corner))
412                        .min_w(px(40.).min(width) * motion.scale)
413                        .min_h(dp(24.))
414                        .max_w(width.min(px(if self.rich { 320. } else { 200. })) * motion.scale)
415                        .when_else(
416                            self.rich,
417                            |surface| {
418                                surface
419                                    .gap(spacing * 0.5)
420                                    .p(spacing)
421                                    .shadow_elevation(Elevation::Level2)
422                                    .shadow_scale(motion.scale)
423                            },
424                            |surface| {
425                                surface
426                                    .px(spacing * 0.5)
427                                    .py(spacing * 0.25)
428                                    .justify_center()
429                                    .text_size(dp(12.))
430                                    .line_height(dp(16.))
431                            },
432                        )
433                        .children(self.title.map(|title| {
434                            super::text_style(
435                                div().text_color(tint).child(title),
436                                TypeRole::TitleSmall,
437                                motion.scale,
438                                window,
439                                cx,
440                            )
441                        }))
442                        .child(super::text_style(
443                            div()
444                                .text_color(if self.rich {
445                                    tint
446                                } else {
447                                    color(theme.colors.color(ColorRole::InverseOnSurface))
448                                })
449                                .child(self.text),
450                            if self.rich {
451                                TypeRole::BodyMedium
452                            } else {
453                                TypeRole::BodySmall
454                            },
455                            motion.scale,
456                            window,
457                            cx,
458                        ))
459                        .children(self.action.map(|action| {
460                            if open {
461                                Button::new("tooltip-action", action.label)
462                                    .track_focus(&action.focus)
463                                    .variant(ButtonVariant::Text)
464                                    .scale(motion.scale)
465                                    .on_activate(move |window, cx| (action.callback)(window, cx))
466                                    .into_any_element()
467                            } else {
468                                div()
469                                    .min_h(dp(theme.layout.density.interactive_size(40.)))
470                                    .flex()
471                                    .items_center()
472                                    .justify_center()
473                                    .child(
474                                        div()
475                                            .px(dp(16.))
476                                            .min_w_0()
477                                            .truncate()
478                                            .text_size(dp(label_type.size))
479                                            .line_height(dp(label_type.line_height))
480                                            .text_color(color(
481                                                theme.colors.color(ColorRole::Primary),
482                                            ))
483                                            .child(action.label),
484                                    )
485                                    .into_any_element()
486                            }
487                        })),
488                );
489            let content = motion.text(content, window);
490            let scaled = ScaledOverlay::new(
491                content.when(!open, |content| {
492                    content.w(last_bounds.size.width * motion.scale)
493                }),
494                motion,
495                move |_| pivot,
496            );
497            if open {
498                scaled
499            } else {
500                scaled.width(last_bounds.size.width)
501            }
502        });
503        if open {
504            return div().child(popup.content(content.expect("open tooltip")));
505        }
506        let exit = content
507            .filter(|_| last_bounds.size.width > px(0.))
508            .map(|content| {
509                gpui::deferred(
510                    gpui_base::Positioner::corner(Anchor::TopLeft, last_bounds.origin)
511                        .child(content),
512                )
513                .with_priority(100)
514            });
515        div().child(popup).children(exit)
516    }
517}