Skip to main content

bhoo/systems/material/
tooltip.rs

1use crate::*;
2
3impl Frame<'_> {
4    fn angular_tooltip(&mut self, id: u64, response: Response, text: &str) {
5        use crate::timing::{Easing, TweenSpec};
6        let viewport = self.viewport();
7        let style = TextStyle {
8            size: 12.0,
9            padding: 8.0,
10            letter_spacing: 0.4,
11            align: 1,
12            ..TextStyle::default()
13        };
14        let width = (self.text_width(text, style) + style.letter_spacing + 16.0)
15            .clamp(40.0, 200.0)
16            .min((viewport.width - 16.0).max(0.0));
17        let x = (response.bounds.x + (response.bounds.width - width) * 0.5).clamp(
18            viewport.x + 8.0,
19            (viewport.x + viewport.width - width - 8.0).max(viewport.x + 8.0),
20        );
21        let below = response.bounds.y + response.bounds.height + 8.0;
22        let y = if below + 24.0 <= viewport.y + viewport.height - 8.0 {
23            below
24        } else {
25            (response.bounds.y - 32.0).max(viewport.y + 8.0)
26        };
27        let bounds = Rect {
28            x,
29            y,
30            width,
31            height: 24.0,
32        };
33        let bridge = Rect {
34            y: if y >= response.bounds.y { y - 8.0 } else { y },
35            height: 32.0,
36            ..bounds
37        };
38        let on_tooltip = self.ui.tooltip_showing == Some(response.id)
39            && self.input.pointer.is_some_and(|p| bridge.contains(p));
40        let eligible = response.enabled
41            && (response.hovered || response.focused && self.ui.keyboard_focus || on_tooltip);
42        if eligible && self.pressed_key(Key::Escape) {
43            self.ui.tooltip_dismissed = Some(response.id);
44        }
45        if !eligible && self.ui.tooltip_dismissed == Some(response.id) {
46            self.ui.tooltip_dismissed = None;
47        }
48        let suppressed = self.ui.tooltip_dismissed == Some(response.id);
49        if eligible && !suppressed {
50            if !self
51                .ui
52                .tooltip_started
53                .is_some_and(|(owner, _)| owner == response.id)
54            {
55                self.ui.tooltip_started = Some((response.id, self.ui.time));
56            }
57        } else if self
58            .ui
59            .tooltip_started
60            .is_some_and(|(owner, _)| owner == response.id)
61        {
62            self.ui.tooltip_started = None;
63        }
64        let deadline = self.ui.tooltip_started.map(|(_, start)| start + 0.5);
65        let show =
66            eligible && !suppressed && deadline.is_some_and(|deadline| self.ui.time >= deadline);
67        if eligible
68            && !suppressed
69            && !show
70            && let Some(deadline) = deadline
71        {
72            self.ui.wakeup = Some(self.ui.wakeup.map_or(deadline, |old| old.min(deadline)));
73        }
74        if show {
75            self.ui.tooltip_showing = Some(response.id);
76        } else if self.ui.tooltip_showing == Some(response.id) {
77            self.ui.tooltip_showing = None;
78        }
79        self.ui.tooltip_visible |= show;
80        let amount = self.ui.motion.tween(
81            id,
82            4,
83            f32::from(show),
84            0.0,
85            TweenSpec::new(0.150, Easing::StandardDecelerate),
86            TweenSpec::new(0.075, Easing::Cubic([0.4, 0.0, 1.0, 1.0])),
87        );
88        if amount <= 0.001 {
89            return;
90        }
91        let scale = 0.8 + 0.2 * amount;
92        let visual = Rect {
93            x: bounds.x + bounds.width * (1.0 - scale) * 0.5,
94            // CDK anchors a below tooltip at its top edge (and an above tooltip at its bottom edge).
95            y: bounds.y
96                + if y < response.bounds.y {
97                    bounds.height * (1.0 - scale)
98                } else {
99                    0.0
100                },
101            width: bounds.width * scale,
102            height: bounds.height * scale,
103        };
104        let label = self.ui.text(text);
105        let theme = self.ui.theme;
106        self.ui.overlays.push(DrawCommand::RoundedRect {
107            bounds: visual,
108            radius: 4.0 * scale,
109            color: theme.inverse_surface.opacity(amount),
110        });
111        self.ui.overlays.push(DrawCommand::Text {
112            bounds: visual,
113            text: label,
114            color: theme.inverse_on_surface.opacity(amount),
115            style: TextStyle {
116                size: style.size * scale,
117                padding: style.padding * scale,
118                letter_spacing: style.letter_spacing * scale,
119                ..style
120            },
121        });
122        if show {
123            self.semantic(
124                Response {
125                    id,
126                    bounds,
127                    enabled: true,
128                    ..Response::default()
129                },
130                Role::Tooltip,
131                text,
132                false,
133                None,
134                None,
135                None,
136            );
137        }
138    }
139
140    /// Hover delay uses an idle deadline, not a spinning frame loop. Call after the owner.
141    pub fn tooltip(&mut self, id: u64, response: Response, text: &str) {
142        if self.ui.ripple_style == RippleStyle::AngularMaterial {
143            self.angular_tooltip(id, response, text);
144            return;
145        }
146        let eligible =
147            response.enabled && (response.hovered || (response.focused && self.ui.keyboard_focus));
148        if eligible && self.pressed_key(Key::Escape) {
149            self.ui.tooltip_dismissed = Some(response.id);
150        }
151        if !eligible && self.ui.tooltip_dismissed == Some(response.id) {
152            self.ui.tooltip_dismissed = None;
153        }
154        let suppressed = self.ui.tooltip_dismissed == Some(response.id);
155        let deadline = self.ui.hover_start + 0.5;
156        let show = eligible
157            && !suppressed
158            && (response.focused && self.ui.keyboard_focus || self.ui.time >= deadline);
159        self.ui.tooltip_visible |= show;
160        if eligible && !suppressed && !show && deadline > self.ui.time {
161            self.ui.wakeup = Some(self.ui.wakeup.map_or(deadline, |old| old.min(deadline)));
162        }
163        let alpha = self.animate(id, 4, if show { 1.0 } else { 0.0 }, 0.0);
164        if alpha <= 0.001 {
165            return;
166        }
167        let width = (text.chars().count() as f32 * 10.0 + 24.0)
168            .min(300.0)
169            .min(self.bounds.width.max(0.0));
170        let x = response
171            .bounds
172            .x
173            .min((self.bounds.x + self.bounds.width - width).max(self.bounds.x));
174        let y = (response.bounds.y + response.bounds.height + 4.0)
175            .min((self.bounds.y + self.bounds.height - 32.0).max(self.bounds.y));
176        let b = Rect {
177            x,
178            y,
179            width,
180            height: 32.0,
181        };
182        let label = self.ui.text(text);
183        let t = self.ui.theme;
184        self.ui.overlays.push(DrawCommand::RoundedRect {
185            bounds: b,
186            radius: 4.0,
187            color: t.inverse_surface.opacity(alpha),
188        });
189        self.ui.overlays.push(DrawCommand::Text {
190            bounds: b,
191            text: Arc::clone(&label),
192            color: t.inverse_on_surface.opacity(alpha),
193            style: TextStyle {
194                size: 12.0,
195                padding: 8.0,
196                letter_spacing: 0.4,
197                ..TextStyle::default()
198            },
199        });
200        if show {
201            self.semantic(
202                Response {
203                    id,
204                    bounds: b,
205                    enabled: true,
206                    ..Response::default()
207                },
208                Role::Tooltip,
209                text,
210                false,
211                None,
212                None,
213                None,
214            );
215        }
216    }
217
218    /// Material 3 Rich Tooltip: 12dp radius, level-2 elevation, `surface_low` container,
219    /// bold 14sp subhead, 14sp body text, and an optional interactive primary text action
220    /// button returning `true` when clicked.
221    pub fn rich_tooltip(
222        &mut self,
223        id: u64,
224        anchor: Response,
225        subhead: &str,
226        body: &str,
227        action_label: Option<&str>,
228    ) -> bool {
229        let viewport = self.viewport();
230        let subhead_style = TextStyle {
231            size: 14.0,
232            weight: 700,
233            align: 0,
234            padding: 0.0,
235            letter_spacing: 0.1,
236            ..TextStyle::default()
237        };
238        let body_style = TextStyle {
239            size: 14.0,
240            weight: 400,
241            align: 0,
242            padding: 0.0,
243            letter_spacing: 0.25,
244            ..TextStyle::default()
245        };
246        let action_style = TextStyle {
247            size: 14.0,
248            weight: 500,
249            align: 1,
250            padding: 8.0,
251            letter_spacing: 0.1,
252            ..TextStyle::default()
253        };
254        let action = action_label.filter(|s| !s.is_empty());
255        let pad_x = 16.0;
256        let pad_top = 12.0;
257        let pad_bottom = if action.is_some() { 8.0 } else { 12.0 };
258        let max_w = (viewport.width - 16.0).clamp(0.0, 312.0);
259        let subhead_w = if subhead.is_empty() {
260            0.0
261        } else {
262            self.text_width(subhead, subhead_style)
263        };
264        let body_w = if body.is_empty() {
265            0.0
266        } else {
267            self.text_width(body, body_style)
268        };
269        let action_w = action.map_or(0.0, |a| self.text_width(a, action_style) + 16.0);
270        let natural_w = subhead_w.max(body_w).max(action_w) + pad_x * 2.0;
271        let width = natural_w.clamp(200.0_f32.min(max_w), max_w);
272        let content_w = (width - pad_x * 2.0).max(1.0);
273        let metrics = self.ui.text_metrics;
274        let body_lines = if body.is_empty() {
275            0
276        } else {
277            metrics.lines(body, content_w, body_style, |_| {}).max(1)
278        };
279        let subhead_h = if subhead.is_empty() { 0.0 } else { 20.0 };
280        let subhead_gap = if !subhead.is_empty() && body_lines > 0 {
281            4.0
282        } else {
283            0.0
284        };
285        let body_h = body_lines as f32 * 20.0;
286        let action_gap = if action.is_some() && (subhead_h > 0.0 || body_h > 0.0) {
287            12.0
288        } else {
289            0.0
290        };
291        let action_h = if action.is_some() { 32.0 } else { 0.0 };
292        let height = pad_top + subhead_h + subhead_gap + body_h + action_gap + action_h + pad_bottom;
293        let x = anchor.bounds.x.clamp(
294            viewport.x + 8.0,
295            (viewport.x + viewport.width - width - 8.0).max(viewport.x + 8.0),
296        );
297        let below = anchor.bounds.y + anchor.bounds.height + 8.0;
298        let y = if below + height <= viewport.y + viewport.height - 8.0 {
299            below
300        } else {
301            (anchor.bounds.y - height - 8.0).max(viewport.y + 8.0)
302        };
303        let bounds = Rect {
304            x,
305            y,
306            width,
307            height,
308        };
309        let bridge = Rect {
310            x: bounds.x.min(anchor.bounds.x),
311            y: if y >= anchor.bounds.y {
312                anchor.bounds.y + anchor.bounds.height
313            } else {
314                y + height
315            },
316            width: (bounds.x + bounds.width)
317                .max(anchor.bounds.x + anchor.bounds.width)
318                - bounds.x.min(anchor.bounds.x),
319            height: 8.0,
320        };
321        let action_id = id.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ 0x7269_6368_5f61_6374;
322        let on_tooltip = self.ui.tooltip_showing == Some(anchor.id)
323            && self
324                .input
325                .pointer
326                .is_some_and(|p| bounds.contains(p) || bridge.contains(p));
327        let action_engaged = self.ui.active == Some(action_id)
328            || (self.ui.focused == Some(action_id) && self.ui.keyboard_focus);
329        let eligible = anchor.enabled
330            && (anchor.hovered
331                || (anchor.focused && self.ui.keyboard_focus)
332                || on_tooltip
333                || action_engaged);
334        if eligible && self.pressed_key(Key::Escape) {
335            self.ui.tooltip_dismissed = Some(anchor.id);
336        }
337        if !eligible && self.ui.tooltip_dismissed == Some(anchor.id) {
338            self.ui.tooltip_dismissed = None;
339        }
340        let suppressed = self.ui.tooltip_dismissed == Some(anchor.id);
341        if eligible && !suppressed {
342            if !self
343                .ui
344                .tooltip_started
345                .is_some_and(|(owner, _)| owner == anchor.id)
346            {
347                self.ui.tooltip_started = Some((anchor.id, self.ui.time));
348            }
349        } else if self
350            .ui
351            .tooltip_started
352            .is_some_and(|(owner, _)| owner == anchor.id)
353        {
354            self.ui.tooltip_started = None;
355        }
356        let deadline = self
357            .ui
358            .tooltip_started
359            .filter(|(owner, _)| *owner == anchor.id)
360            .map(|(_, start)| start + 0.5);
361        let show = eligible
362            && !suppressed
363            && (self.ui.tooltip_showing == Some(anchor.id)
364                || (anchor.focused && self.ui.keyboard_focus)
365                || action_engaged
366                || deadline.is_some_and(|d| self.ui.time >= d));
367        if eligible
368            && !suppressed
369            && !show
370            && let Some(deadline) = deadline
371            && deadline > self.ui.time
372        {
373            self.ui.wakeup = Some(self.ui.wakeup.map_or(deadline, |old| old.min(deadline)));
374        }
375        if show {
376            self.ui.tooltip_showing = Some(anchor.id);
377        } else if self.ui.tooltip_showing == Some(anchor.id) {
378            self.ui.tooltip_showing = None;
379        }
380        self.ui.tooltip_visible |= show;
381        let alpha = self.animate(id, 4, f32::from(show), 0.0);
382        if alpha <= 0.001 {
383            return false;
384        }
385        let t = self.ui.theme;
386        let black = Color(0, 0, 0, 255);
387        // Elevation level 2 shadows on the overlay layer.
388        for (ox, oy, blur, spread, sa) in [
389            (0.0, 3.0, 1.0, -2.0, 0.2),
390            (0.0, 2.0, 2.0, 0.0, 0.14),
391            (0.0, 1.0, 5.0, 0.0, 0.12),
392        ] {
393            self.ui.overlays.push(DrawCommand::Shadow {
394                bounds,
395                radius: 12.0,
396                offset: [ox, oy],
397                blur,
398                spread,
399                color: black.opacity(sa * alpha),
400            });
401        }
402        self.ui.overlays.push(DrawCommand::RoundedRect {
403            bounds,
404            radius: 12.0,
405            color: t.surface_low.opacity(alpha),
406        });
407        let mut cursor_y = bounds.y + pad_top;
408        if !subhead.is_empty() {
409            let subhead_text = self.ui.text(subhead);
410            self.ui.overlays.push(DrawCommand::Text {
411                bounds: Rect {
412                    x: bounds.x + pad_x,
413                    y: cursor_y,
414                    width: content_w,
415                    height: subhead_h,
416                },
417                text: subhead_text,
418                color: t.text.opacity(alpha),
419                style: subhead_style,
420            });
421            cursor_y += subhead_h + subhead_gap;
422        }
423        if !body.is_empty() {
424            let mut line_index = 0usize;
425            let mut line_strings = Vec::new();
426            metrics.lines(body, content_w, body_style, |line| {
427                line_strings.push(line.to_owned());
428            });
429            for line in line_strings {
430                let cached = self.ui.text(&line);
431                self.ui.overlays.push(DrawCommand::Text {
432                    bounds: Rect {
433                        x: bounds.x + pad_x,
434                        y: cursor_y + line_index as f32 * 20.0,
435                        width: content_w,
436                        height: 20.0,
437                    },
438                    text: cached,
439                    color: t.on_surface_variant.opacity(alpha),
440                    style: body_style,
441                });
442                line_index += 1;
443            }
444            cursor_y += body_h;
445        }
446        let mut action_clicked = false;
447        if let Some(action_label) = action {
448            cursor_y += action_gap;
449            let btn_w = (self.text_width(action_label, action_style) + 16.0)
450                .clamp(48.0_f32.min(content_w), content_w);
451            let btn_rect = Rect {
452                x: bounds.x + pad_x - 8.0,
453                y: cursor_y,
454                width: btn_w,
455                height: action_h,
456            };
457            if show {
458                let btn_resp = self.interact(action_id, btn_rect, true);
459                action_clicked = btn_resp.clicked;
460                let state_alpha = if btn_resp.pressed {
461                    0.12
462                } else if btn_resp.focused && self.ui.keyboard_focus {
463                    0.12
464                } else if btn_resp.hovered {
465                    0.08
466                } else {
467                    0.0
468                };
469                if state_alpha > 0.0 {
470                    self.ui.overlays.push(DrawCommand::RoundedRect {
471                        bounds: btn_rect,
472                        radius: 16.0,
473                        color: t.primary.opacity(state_alpha * alpha),
474                    });
475                }
476                self.semantic(
477                    btn_resp,
478                    Role::Button,
479                    action_label,
480                    false,
481                    None,
482                    None,
483                    None,
484                );
485            }
486            let cached_action = self.ui.text(action_label);
487            self.ui.overlays.push(DrawCommand::Text {
488                bounds: btn_rect,
489                text: cached_action,
490                color: t.primary.opacity(alpha),
491                style: action_style,
492            });
493        }
494        if show {
495            let semantic_label = match (subhead.is_empty(), body.is_empty()) {
496                (false, false) => format!("{subhead}: {body}"),
497                (false, true) => subhead.to_owned(),
498                (true, false) => body.to_owned(),
499                (true, true) => String::new(),
500            };
501            self.semantic(
502                Response {
503                    id,
504                    bounds,
505                    enabled: true,
506                    ..Response::default()
507                },
508                Role::Tooltip,
509                &semantic_label,
510                false,
511                None,
512                None,
513                None,
514            );
515        }
516        action_clicked
517    }
518}
519
520#[cfg(test)]
521#[path = "tooltip.spec.rs"]
522mod tests;