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    AnyElement, App, Bounds, ElementId, Entity, FocusHandle, IntoElement, KeyBinding, Pixels,
11    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 gpui_base::Positioner as TooltipPositioner;
19pub use interaction::TooltipState;
20pub use label::Label;
21
22use crate::control_style::finite_length;
23
24gpui::actions!(
25    material_tooltip,
26    [
27        FocusTooltipAction,
28        FocusTooltipTrigger,
29        DismissTooltip,
30        ActivateTooltipAction
31    ]
32);
33
34pub(crate) fn init(cx: &mut App) {
35    cx.bind_keys([
36        KeyBinding::new("tab", FocusTooltipAction, Some("MaterialTooltipTrigger")),
37        KeyBinding::new(
38            "shift-tab",
39            FocusTooltipTrigger,
40            Some("MaterialTooltipContent"),
41        ),
42        KeyBinding::new("escape", DismissTooltip, Some("MaterialTooltip")),
43        KeyBinding::new(
44            "enter",
45            ActivateTooltipAction,
46            Some("MaterialTooltipAction"),
47        ),
48        KeyBinding::new(
49            "space",
50            ActivateTooltipAction,
51            Some("MaterialTooltipAction"),
52        ),
53    ]);
54}
55
56pub(super) type TooltipCallback = Rc<dyn Fn(&mut Window, &mut App)>;
57pub(super) type PositionProvider =
58    Box<dyn Fn(Bounds<Pixels>, Size<Pixels>, Direction) -> TooltipPositioner>;
59
60pub(super) struct TooltipAction {
61    pub(super) label: SharedString,
62    pub(super) focus: FocusHandle,
63    pub(super) callback: TooltipCallback,
64}
65
66/// A transient plain or rich Material tooltip, or a persistent rich tooltip
67/// with caller-owned visibility.
68#[derive(IntoElement)]
69pub struct Tooltip {
70    pub(super) id: ElementId,
71    pub(super) trigger: Option<AnyElement>,
72    pub(super) text: SharedString,
73    pub(super) title: Option<SharedString>,
74    pub(super) shortcut: Option<SharedString>,
75    pub(super) action: Option<TooltipAction>,
76    pub(super) title_content: Option<AnyElement>,
77    pub(super) body_content: Option<AnyElement>,
78    pub(super) action_content: Option<AnyElement>,
79    pub(super) link: Option<(SharedString, TooltipCallback)>,
80    pub(super) rich: bool,
81    pub(super) trigger_focus: Option<FocusHandle>,
82    pub(super) focus_target: Option<FocusHandle>,
83    pub(super) focusable: bool,
84    pub(super) enable_user_input: bool,
85    pub(super) persistent: Option<Entity<TooltipState>>,
86    pub(super) label_visible: Option<bool>,
87    pub(super) on_dismiss_request: Option<TooltipCallback>,
88    pub(super) placement: TooltipPlacement,
89    pub(super) offset: Pixels,
90    positioner: Option<PositionProvider>,
91    appearance: Appearance,
92    show_delay: Duration,
93    pub(super) hide_delay: Duration,
94}
95
96impl Tooltip {
97    /// Creates a plain tooltip anchored to `trigger` with the given descriptive text.
98    pub fn plain(
99        id: impl Into<ElementId>,
100        trigger: impl IntoElement,
101        text: impl Into<SharedString>,
102    ) -> Self {
103        Self {
104            id: id.into(),
105            trigger: Some(trigger.into_any_element()),
106            text: text.into(),
107            title: None,
108            shortcut: None,
109            action: None,
110            title_content: None,
111            body_content: None,
112            action_content: None,
113            link: None,
114            rich: false,
115            trigger_focus: None,
116            focus_target: None,
117            focusable: false,
118            enable_user_input: true,
119            persistent: None,
120            label_visible: None,
121            on_dismiss_request: None,
122            placement: TooltipPlacement::Above,
123            offset: px(4.),
124            positioner: None,
125            appearance: Appearance::default(),
126            show_delay: Duration::from_millis(500),
127            hide_delay: Duration::from_millis(200),
128        }
129    }
130
131    /// Creates a rich tooltip anchored to `trigger` with a title and body text.
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    /// Replaces the rich tooltip title with custom content.
170    pub fn title_content(mut self, content: impl IntoElement) -> Self {
171        self.rich = true;
172        self.title_content = Some(content.into_any_element());
173        self
174    }
175
176    /// Replaces the tooltip body text with custom content while keeping the constructor text as the accessible description.
177    pub fn body_content(mut self, content: impl IntoElement) -> Self {
178        self.body_content = Some(content.into_any_element());
179        self
180    }
181
182    /// Replaces the standard action with caller-authored interactive content.
183    pub fn action_content(mut self, content: impl IntoElement) -> Self {
184        self.rich = true;
185        self.action_content = Some(content.into_any_element());
186        self
187    }
188
189    /// Adds a semantic link. The callback owns the destination and navigation.
190    pub fn link(
191        mut self,
192        label: impl Into<SharedString>,
193        callback: impl Fn(&mut Window, &mut App) + 'static,
194    ) -> Self {
195        self.rich = true;
196        self.link = Some((label.into(), Rc::new(callback)));
197        self
198    }
199
200    /// Overrides the pointer hover delay before showing a transient tooltip (default 500 ms).
201    pub fn show_delay(mut self, delay: Duration) -> Self {
202        self.show_delay = delay;
203        self
204    }
205
206    /// Overrides the pointer leave grace delay before hiding a transient tooltip (default 200 ms).
207    pub fn hide_delay(mut self, delay: Duration) -> Self {
208        self.hide_delay = delay;
209        self
210    }
211
212    /// Uses the trigger's focus handle for keyboard activation and restoration.
213    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
214        self.trigger_focus = Some(focus.clone());
215        self
216    }
217
218    /// Uses the caller's first focus target inside the tooltip.
219    pub fn focus_target(mut self, focus: &FocusHandle) -> Self {
220        self.focus_target = Some(focus.clone());
221        self
222    }
223
224    /// Moves focus to the tooltip when it opens. The default preserves focus.
225    pub fn focusable(mut self, focusable: bool) -> Self {
226        self.focusable = focusable;
227        self
228    }
229
230    /// Enables automatic trigger input for the chosen visibility mode.
231    pub fn enable_user_input(mut self, enable: bool) -> Self {
232        self.enable_user_input = enable;
233        self
234    }
235
236    /// Uses caller-owned visibility for a persistent rich tooltip.
237    pub fn persistent(mut self, state: &Entity<TooltipState>) -> Self {
238        self.rich = true;
239        self.persistent = Some(state.clone());
240        self
241    }
242
243    /// Handles Escape or a persistent tooltip's outside press. A persistent
244    /// tooltip with a handler closes when the owner accepts the request.
245    pub fn on_dismiss_request(
246        mut self,
247        callback: impl Fn(&mut Window, &mut App) + 'static,
248    ) -> Self {
249        self.on_dismiss_request = Some(Rc::new(callback));
250        self
251    }
252
253    /// Sets the preferred side relative to the trigger (default [`TooltipPlacement::Above`]).
254    pub fn placement(mut self, placement: TooltipPlacement) -> Self {
255        self.placement = placement;
256        self
257    }
258
259    /// Gap between the trigger and surface in logical pixels.
260    pub fn offset(mut self, offset: Pixels) -> Self {
261        self.offset = finite_length(offset);
262        self
263    }
264
265    /// Replaces the standard placement with a positioner built from the trigger
266    /// bounds, viewport size, and direction. The host applies viewport margins.
267    pub fn positioner(
268        mut self,
269        positioner: impl Fn(Bounds<Pixels>, Size<Pixels>, Direction) -> TooltipPositioner + 'static,
270    ) -> Self {
271        self.positioner = Some(Box::new(positioner));
272        self
273    }
274
275    /// Renders a pointer caret pointing toward the trigger.
276    pub fn caret(mut self, caret: TooltipCaret) -> Self {
277        self.appearance.caret = Some(caret);
278        self
279    }
280
281    /// Overrides the maximum width of the tooltip surface in logical pixels.
282    pub fn max_width(mut self, width: Pixels) -> Self {
283        self.appearance.max_width = Some(finite_length(width));
284        self
285    }
286
287    /// Overrides the corner shape of the tooltip surface.
288    pub fn shape(mut self, shape: CornerShape) -> Self {
289        self.appearance.shape = Some(shape);
290        self
291    }
292
293    /// Overrides the tooltip's container, content, title, and action colors.
294    pub fn colors(mut self, colors: TooltipColors) -> Self {
295        self.appearance.colors = colors;
296        self
297    }
298
299    /// Sets the tonal elevation used to tint the tooltip surface.
300    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
301        self.appearance.tonal_elevation = elevation;
302        self
303    }
304
305    /// Overrides the shadow elevation cast by the tooltip surface.
306    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
307        self.appearance.shadow_elevation = Some(elevation);
308        self
309    }
310}