Skip to main content

gpui_material_components/overlay/
tooltip.rs

1mod appearance;
2mod interaction;
3mod label;
4mod render;
5mod surface;
6
7use std::{rc::Rc, time::Duration};
8
9use gpui::{
10    Anchor, AnyElement, App, Bounds, ElementId, Entity, FocusHandle, IntoElement, KeyBinding,
11    Pixels, Point, SharedString, Size, Window, px,
12};
13use gpui_material_theme::{CornerShape, Direction, Elevation};
14
15use appearance::Appearance;
16
17pub use appearance::{TooltipCaret, TooltipColors, TooltipPlacement};
18pub use interaction::TooltipState;
19pub use label::Label;
20
21use crate::control_style::finite_length;
22
23#[derive(Clone, Copy, Debug, PartialEq)]
24enum PositionerStrategy {
25    Corner {
26        anchor: Anchor,
27        position: Point<Pixels>,
28    },
29    Side {
30        trigger_bounds: Bounds<Pixels>,
31        placement: Option<TooltipPlacement>,
32        offset: Pixels,
33    },
34}
35
36/// Positioning specification returned from [`Tooltip::positioner`].
37///
38/// Choose [`TooltipPositioner::side`] to place the tooltip along a side of a
39/// trigger with automatic viewport flipping, or [`TooltipPositioner::corner`]
40/// to anchor a corner of the tooltip at an explicit window coordinate. The
41/// tooltip host applies viewport margins and pointer occlusion automatically.
42#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct TooltipPositioner {
44    strategy: PositionerStrategy,
45}
46
47impl TooltipPositioner {
48    /// Places the tooltip on a side of `trigger_bounds`, flipping when needed.
49    pub fn side(trigger_bounds: Bounds<Pixels>) -> Self {
50        Self {
51            strategy: PositionerStrategy::Side {
52                trigger_bounds,
53                placement: None,
54                offset: px(0.),
55            },
56        }
57    }
58
59    /// Places `anchor`'s corner of the tooltip at `position`, clamping to the viewport.
60    pub fn corner(anchor: Anchor, position: Point<Pixels>) -> Self {
61        Self {
62            strategy: PositionerStrategy::Corner { anchor, position },
63        }
64    }
65
66    /// Updates the requested corner position. Has no effect on a side-positioned tooltip.
67    pub fn position(mut self, position: Point<Pixels>) -> Self {
68        if let PositionerStrategy::Corner {
69            position: current, ..
70        } = &mut self.strategy
71        {
72            *current = position;
73        }
74        self
75    }
76
77    /// Sets the preferred side. Only meaningful for [`TooltipPositioner::side`].
78    pub fn placement(mut self, placement: TooltipPlacement) -> Self {
79        if let PositionerStrategy::Side {
80            placement: slot, ..
81        } = &mut self.strategy
82        {
83            *slot = Some(placement);
84        }
85        self
86    }
87
88    /// Sets the gap between the trigger and the tooltip in logical pixels.
89    /// Only meaningful for [`TooltipPositioner::side`].
90    pub fn offset(mut self, offset: Pixels) -> Self {
91        if let PositionerStrategy::Side { offset: slot, .. } = &mut self.strategy {
92            *slot = finite_length(offset);
93        }
94        self
95    }
96
97    pub(super) fn into_base(self, direction: Direction) -> gpui_base::Positioner {
98        match self.strategy {
99            PositionerStrategy::Corner { anchor, position } => {
100                gpui_base::Positioner::corner(anchor, position)
101            }
102            PositionerStrategy::Side {
103                trigger_bounds,
104                placement,
105                offset,
106            } => {
107                let mut base = gpui_base::Positioner::side(trigger_bounds).offset(offset);
108                if let Some(placement) = placement {
109                    base = base.placement(placement.physical(direction));
110                }
111                base
112            }
113        }
114    }
115}
116
117gpui::actions!(
118    material_tooltip,
119    [
120        FocusTooltipAction,
121        FocusTooltipTrigger,
122        DismissTooltip,
123        ActivateTooltipAction
124    ]
125);
126
127pub(crate) fn init(cx: &mut App) {
128    cx.bind_keys([
129        KeyBinding::new("tab", FocusTooltipAction, Some("MaterialTooltipTrigger")),
130        KeyBinding::new(
131            "shift-tab",
132            FocusTooltipTrigger,
133            Some("MaterialTooltipContent"),
134        ),
135        KeyBinding::new("escape", DismissTooltip, Some("MaterialTooltip")),
136        KeyBinding::new(
137            "enter",
138            ActivateTooltipAction,
139            Some("MaterialTooltipAction"),
140        ),
141        KeyBinding::new(
142            "space",
143            ActivateTooltipAction,
144            Some("MaterialTooltipAction"),
145        ),
146    ]);
147}
148
149pub(super) type TooltipCallback = Rc<dyn Fn(&mut Window, &mut App)>;
150pub(super) type PositionProvider =
151    Box<dyn Fn(Bounds<Pixels>, Size<Pixels>, Direction) -> TooltipPositioner>;
152
153pub(super) struct TooltipAction {
154    pub(super) label: SharedString,
155    pub(super) focus: FocusHandle,
156    pub(super) callback: TooltipCallback,
157}
158
159/// A transient plain or rich Material tooltip, or a persistent rich tooltip
160/// with caller-owned visibility.
161#[derive(IntoElement)]
162pub struct Tooltip {
163    pub(super) id: ElementId,
164    pub(super) trigger: Option<AnyElement>,
165    pub(super) text: SharedString,
166    pub(super) title: Option<SharedString>,
167    pub(super) shortcut: Option<SharedString>,
168    pub(super) action: Option<TooltipAction>,
169    pub(super) title_content: Option<AnyElement>,
170    pub(super) body_content: Option<AnyElement>,
171    pub(super) action_content: Option<AnyElement>,
172    pub(super) link: Option<(SharedString, TooltipCallback)>,
173    pub(super) rich: bool,
174    pub(super) trigger_focus: Option<FocusHandle>,
175    pub(super) focus_target: Option<FocusHandle>,
176    pub(super) focusable: bool,
177    pub(super) enable_user_input: bool,
178    pub(super) persistent: Option<Entity<TooltipState>>,
179    pub(super) label_visible: Option<bool>,
180    pub(super) on_dismiss_request: Option<TooltipCallback>,
181    pub(super) placement: TooltipPlacement,
182    pub(super) offset: Pixels,
183    positioner: Option<PositionProvider>,
184    appearance: Appearance,
185    show_delay: Duration,
186    pub(super) hide_delay: Duration,
187}
188
189impl Tooltip {
190    /// Creates a plain tooltip anchored to `trigger` with the given descriptive text.
191    pub fn plain(
192        id: impl Into<ElementId>,
193        trigger: impl IntoElement,
194        text: impl Into<SharedString>,
195    ) -> Self {
196        Self {
197            id: id.into(),
198            trigger: Some(trigger.into_any_element()),
199            text: text.into(),
200            title: None,
201            shortcut: None,
202            action: None,
203            title_content: None,
204            body_content: None,
205            action_content: None,
206            link: None,
207            rich: false,
208            trigger_focus: None,
209            focus_target: None,
210            focusable: false,
211            enable_user_input: true,
212            persistent: None,
213            label_visible: None,
214            on_dismiss_request: None,
215            placement: TooltipPlacement::Above,
216            offset: px(4.),
217            positioner: None,
218            appearance: Appearance::default(),
219            show_delay: Duration::from_millis(500),
220            hide_delay: Duration::from_millis(200),
221        }
222    }
223
224    /// Creates a rich tooltip anchored to `trigger` with a title and body text.
225    pub fn rich(
226        id: impl Into<ElementId>,
227        trigger: impl IntoElement,
228        title: impl Into<SharedString>,
229        text: impl Into<SharedString>,
230    ) -> Self {
231        Self {
232            title: Some(title.into()),
233            rich: true,
234            ..Self::plain(id, trigger, text)
235        }
236    }
237
238    /// Appends a subtle formatted desktop shortcut hint beside plain tooltip
239    /// text or in a rich tooltip header/body while keeping the constructor's
240    /// text as the accessible description.
241    pub fn shortcut(mut self, text: impl Into<SharedString>) -> Self {
242        self.shortcut = Some(text.into());
243        self
244    }
245
246    /// Adds a text button to a rich tooltip.
247    pub fn action(
248        mut self,
249        label: impl Into<SharedString>,
250        focus: &FocusHandle,
251        callback: impl Fn(&mut Window, &mut App) + 'static,
252    ) -> Self {
253        self.rich = true;
254        self.action = Some(TooltipAction {
255            label: label.into(),
256            focus: focus.clone(),
257            callback: Rc::new(callback),
258        });
259        self
260    }
261
262    /// Replaces the rich tooltip title with custom content.
263    pub fn title_content(mut self, content: impl IntoElement) -> Self {
264        self.rich = true;
265        self.title_content = Some(content.into_any_element());
266        self
267    }
268
269    /// Replaces the tooltip body text with custom content while keeping the constructor text as the accessible description.
270    pub fn body_content(mut self, content: impl IntoElement) -> Self {
271        self.body_content = Some(content.into_any_element());
272        self
273    }
274
275    /// Replaces the standard action with caller-authored interactive content.
276    pub fn action_content(mut self, content: impl IntoElement) -> Self {
277        self.rich = true;
278        self.action_content = Some(content.into_any_element());
279        self
280    }
281
282    /// Adds a semantic link. The callback owns the destination and navigation.
283    pub fn link(
284        mut self,
285        label: impl Into<SharedString>,
286        callback: impl Fn(&mut Window, &mut App) + 'static,
287    ) -> Self {
288        self.rich = true;
289        self.link = Some((label.into(), Rc::new(callback)));
290        self
291    }
292
293    /// Overrides the pointer hover delay before showing a transient tooltip (default 500 ms).
294    pub fn show_delay(mut self, delay: Duration) -> Self {
295        self.show_delay = delay;
296        self
297    }
298
299    /// Overrides the pointer leave grace delay before hiding a transient tooltip (default 200 ms).
300    pub fn hide_delay(mut self, delay: Duration) -> Self {
301        self.hide_delay = delay;
302        self
303    }
304
305    /// Uses the trigger's focus handle for keyboard activation and restoration.
306    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
307        self.trigger_focus = Some(focus.clone());
308        self
309    }
310
311    /// Uses the caller's first focus target inside the tooltip.
312    pub fn focus_target(mut self, focus: &FocusHandle) -> Self {
313        self.focus_target = Some(focus.clone());
314        self
315    }
316
317    /// Moves focus to the tooltip when it opens. The default preserves focus.
318    pub fn focusable(mut self, focusable: bool) -> Self {
319        self.focusable = focusable;
320        self
321    }
322
323    /// Enables automatic trigger input for the chosen visibility mode.
324    pub fn enable_user_input(mut self, enable: bool) -> Self {
325        self.enable_user_input = enable;
326        self
327    }
328
329    /// Uses caller-owned visibility for a persistent rich tooltip.
330    pub fn persistent(mut self, state: &Entity<TooltipState>) -> Self {
331        self.rich = true;
332        self.persistent = Some(state.clone());
333        self
334    }
335
336    /// Handles Escape or a persistent tooltip's outside press. A persistent
337    /// tooltip with a handler closes when the owner accepts the request.
338    pub fn on_dismiss_request(
339        mut self,
340        callback: impl Fn(&mut Window, &mut App) + 'static,
341    ) -> Self {
342        self.on_dismiss_request = Some(Rc::new(callback));
343        self
344    }
345
346    /// Sets the preferred side relative to the trigger (default [`TooltipPlacement::Above`]).
347    pub fn placement(mut self, placement: TooltipPlacement) -> Self {
348        self.placement = placement;
349        self
350    }
351
352    /// Gap between the trigger and surface in logical pixels.
353    pub fn offset(mut self, offset: Pixels) -> Self {
354        self.offset = finite_length(offset);
355        self
356    }
357
358    /// Replaces the standard placement with a positioner built from the trigger
359    /// bounds, viewport size, and direction. The host applies viewport margins.
360    pub fn positioner(
361        mut self,
362        positioner: impl Fn(Bounds<Pixels>, Size<Pixels>, Direction) -> TooltipPositioner + 'static,
363    ) -> Self {
364        self.positioner = Some(Box::new(positioner));
365        self
366    }
367
368    /// Renders a pointer caret pointing toward the trigger.
369    pub fn caret(mut self, caret: TooltipCaret) -> Self {
370        self.appearance.caret = Some(caret);
371        self
372    }
373
374    /// Overrides the maximum width of the tooltip surface in logical pixels.
375    pub fn max_width(mut self, width: Pixels) -> Self {
376        self.appearance.max_width = Some(finite_length(width));
377        self
378    }
379
380    /// Overrides the corner shape of the tooltip surface.
381    pub fn shape(mut self, shape: CornerShape) -> Self {
382        self.appearance.shape = Some(shape);
383        self
384    }
385
386    /// Overrides the tooltip's container, content, title, and action colors.
387    pub fn colors(mut self, colors: TooltipColors) -> Self {
388        self.appearance.colors = colors;
389        self
390    }
391
392    /// Sets the tonal elevation used to tint the tooltip surface.
393    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
394        self.appearance.tonal_elevation = elevation;
395        self
396    }
397
398    /// Overrides the shadow elevation cast by the tooltip surface.
399    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
400        self.appearance.shadow_elevation = Some(elevation);
401        self
402    }
403}
404
405#[cfg(test)]
406mod positioner_tests {
407    use super::*;
408    use gpui::{point, size};
409
410    #[test]
411    fn tooltip_positioner_is_material_owned_and_sanitizes_builders() {
412        assert_ne!(
413            std::any::TypeId::of::<TooltipPositioner>(),
414            std::any::TypeId::of::<gpui_base::Positioner>()
415        );
416        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(80.), px(30.)));
417        let side = TooltipPositioner::side(bounds)
418            .placement(TooltipPlacement::Start)
419            .offset(px(12.));
420        let invalid_offset = TooltipPositioner::side(bounds)
421            .placement(TooltipPlacement::Start)
422            .offset(px(f32::NAN));
423        assert_ne!(side, invalid_offset);
424        assert_eq!(
425            invalid_offset,
426            TooltipPositioner::side(bounds)
427                .placement(TooltipPlacement::Start)
428                .offset(px(0.))
429        );
430        let corner = TooltipPositioner::corner(Anchor::TopLeft, point(px(1.), px(2.)))
431            .position(point(px(30.), px(40.)));
432        assert_eq!(
433            corner,
434            TooltipPositioner::corner(Anchor::TopLeft, point(px(30.), px(40.)))
435        );
436        // Ensure conversion succeeds for both LTR and RTL without panicking.
437        let _ = side.into_base(Direction::Ltr);
438        let _ = side.into_base(Direction::Rtl);
439        let _ = corner.into_base(Direction::Ltr);
440    }
441}