Skip to main content

egui_pop_core/
tooltip.rs

1//! Tooltips drawn with the kit's `tooltip` component: its fill, border,
2//! radius, padding, shadow, text colour and size, and its placement
3//! (`tooltip.placement`: `widget`, under the hovered widget from its
4//! start edge as egui's; `pointer`, under the pointer from its position)
5//! with `tooltip.offset` between them. At the pointer, `tooltip.offset-x`
6//! moves it towards the end side too (its corner `offset-x` across and
7//! `offset` down from the pointer), and where the window lacks room on
8//! the end side or below, it goes to the pointer's other side, the same
9//! distance away, rather than being pushed back under the pointer.
10//!
11//! <div class="warning">Experimental: may change in any release
12//! (docs/stability.md).</div>
13//!
14//! egui's own [`egui::Response::on_hover_text`] keeps the popup's look:
15//! [`TooltipExt::tip`] is its kit counterpart, with egui's timing (the
16//! delay, the grace between neighbours), its accessibility (the text
17//! describes the widget) and its tooltip layer.
18//!
19//! ```
20//! use egui_pop_core::tooltip::TooltipExt as _;
21//!
22//! fn toolbar(ui: &mut egui::Ui) {
23//!     ui.button("+ New").tip("Create a ticket");
24//! }
25//! ```
26
27use egui::{
28    Align, Align2, Context, InnerResponse, Pos2, Rect, RectAlign, Response, Style, Ui, Vec2,
29    WidgetText, pos2, vec2,
30};
31
32use crate::kit::{Kit, State};
33use crate::theme::Tokens;
34
35/// Where a tooltip goes (`tooltip.placement`).
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37pub enum TooltipPlacement {
38    /// Under the hovered widget, from its start edge (egui's).
39    #[default]
40    Widget,
41    /// Under the pointer, from its position.
42    Pointer,
43}
44
45impl TooltipPlacement {
46    /// The theme's (`tooltip.placement`); `widget` when it gives none or
47    /// an unknown word.
48    pub fn of(ctx: &Context) -> TooltipPlacement {
49        match Tokens::of(ctx).resolved().value("tooltip.placement") {
50            Some(egui_pop_tokens::Value::Other(serde_json::Value::String(s))) if s == "pointer" => {
51                TooltipPlacement::Pointer
52            }
53            _ => TooltipPlacement::Widget,
54        }
55    }
56}
57
58/// Kit tooltips on a widget's response.
59pub trait TooltipExt: Sized {
60    /// Shows `text` in the kit's tooltip while the widget is hovered and
61    /// enabled, as [`Response::on_hover_text`] does with egui's.
62    ///
63    /// Need (help): a tooltip.
64    fn tip(self, text: impl Into<WidgetText>) -> Self;
65    /// Shows `text` in the kit's tooltip while the widget is hovered and
66    /// disabled (the reason it is), as
67    /// [`Response::on_disabled_hover_text`].
68    ///
69    /// Need (help): why a control is disabled.
70    fn disabled_tip(self, text: impl Into<WidgetText>) -> Self;
71    /// Shows `add` in the kit's tooltip while the widget is hovered and
72    /// enabled, as [`Response::on_hover_ui`].
73    fn tip_ui(self, add: impl FnOnce(&mut Ui)) -> Self;
74}
75
76impl TooltipExt for Response {
77    fn tip(self, text: impl Into<WidgetText>) -> Self {
78        let text = text.into();
79        describe(&self, text.text());
80        show(&self, true, |ui| text_ui(ui, text));
81        self
82    }
83
84    fn disabled_tip(self, text: impl Into<WidgetText>) -> Self {
85        let text = text.into();
86        describe(&self, text.text());
87        show(&self, false, |ui| text_ui(ui, text));
88        self
89    }
90
91    fn tip_ui(self, add: impl FnOnce(&mut Ui)) -> Self {
92        show(&self, true, add);
93        self
94    }
95}
96
97/// Shows `add` in the kit's tooltip for `response` when egui would show
98/// a tooltip for it (`enabled`: for an enabled widget, else for a
99/// disabled one); its content's result while shown.
100pub fn show<R>(
101    response: &Response,
102    enabled: bool,
103    add: impl FnOnce(&mut Ui) -> R,
104) -> Option<InnerResponse<R>> {
105    let ctx = &response.ctx;
106    let kit = Kit::of(ctx);
107    let tooltip = egui::containers::Tooltip::for_widget(response);
108    let open = response.enabled() == enabled
109        && egui::containers::Tooltip::should_show_tooltip(response, true);
110    if !open {
111        return None;
112    }
113    let data = &kit.tooltip.data;
114    let mut tooltip = tooltip.gap(data.offset);
115    if TooltipPlacement::of(ctx) == TooltipPlacement::Pointer {
116        let pointer = ctx.pointer_hover_pos()?;
117        let offset = vec2(offset_x(ctx), data.offset);
118        // The size it had last pass (egui sizes it on its first).
119        let size =
120            egui::AreaState::load(ctx, egui::containers::Tooltip::tooltip_id(response.id, 0))
121                .and_then(|s| s.size)
122                .unwrap_or(Vec2::ZERO);
123        let (pos, corner) = at_pointer(ctx.content_rect(), pointer, offset, size);
124        tooltip.popup = tooltip
125            .popup
126            .anchor(egui::PopupAnchor::Position(pos))
127            .align(RectAlign {
128                parent: corner,
129                child: corner,
130            })
131            .align_alternatives(&[])
132            .gap(0.0);
133    }
134    // egui frames a tooltip with its popup's look, read from the style
135    // its layer starts with: the kit's for the time it is laid out.
136    let before = ctx.global_style();
137    ctx.set_global_style(styled(&before, &kit, ctx.pixels_per_point()));
138    let size = data.font_size;
139    let shown = tooltip.show(|ui| {
140        if size > 0.0 {
141            for font in ui.style_mut().text_styles.values_mut() {
142                font.size = size;
143            }
144        }
145        ui.visuals_mut().override_text_color = Some(kit.tooltip.style(State::REST).text);
146        add(ui)
147    });
148    ctx.set_global_style(before);
149    shown
150}
151
152/// The theme's `tooltip.offset-x`: how far right of the pointer a
153/// tooltip at the pointer starts; 0 when not given.
154fn offset_x(ctx: &Context) -> f32 {
155    Tokens::of(ctx)
156        .resolved()
157        .dimension("tooltip.offset-x")
158        .unwrap_or(0.0)
159}
160
161/// Where a tooltip of `size` at `pointer` goes in `window`: the point
162/// and which of its corners sits there. Its top left corner `offset`
163/// right of and below the pointer; on the pointer's left (its right
164/// edge `offset.x` before it) when it would pass the window's right
165/// edge and fits on the left, above it likewise.
166fn at_pointer(window: Rect, pointer: Pos2, offset: Vec2, size: Vec2) -> (Pos2, Align2) {
167    let left = pointer.x + offset.x + size.x > window.right()
168        && pointer.x - offset.x - size.x >= window.left();
169    let up = pointer.y + offset.y + size.y > window.bottom()
170        && pointer.y - offset.y - size.y >= window.top();
171    let x = if left {
172        pointer.x - offset.x
173    } else {
174        pointer.x + offset.x
175    };
176    let y = if up {
177        pointer.y - offset.y
178    } else {
179        pointer.y + offset.y
180    };
181    let corner = Align2([
182        if left { Align::Max } else { Align::Min },
183        if up { Align::Max } else { Align::Min },
184    ]);
185    (pos2(x, y), corner)
186}
187
188/// The style a tooltip's layer starts with: `base`, its popup's look the
189/// kit's `tooltip`.
190fn styled(base: &Style, kit: &Kit, ppp: f32) -> Style {
191    let mut s = base.clone();
192    let component = &kit.tooltip;
193    let frame = component.frame(State::REST, ppp);
194    s.visuals.window_fill = frame.fill;
195    s.visuals.window_stroke = frame.stroke;
196    s.visuals.menu_corner_radius = frame.corner_radius;
197    s.visuals.popup_shadow = component.data.shadow;
198    s.spacing.menu_margin = frame.inner_margin;
199    s
200}
201
202fn text_ui(ui: &mut Ui, text: WidgetText) {
203    // As egui's: Area's sizing must not shrink a tooltip's text.
204    ui.set_max_width(ui.spacing().tooltip_width);
205    ui.add(egui::Label::new(text));
206}
207
208/// The text describes the widget for assistive technology (its name too
209/// when it has none), as egui's `on_hover_text`.
210fn describe(response: &Response, text: &str) {
211    if response.ctx.has_accesskit_node(response.id) {
212        response.ctx.accesskit_node_builder(response.id, |node| {
213            if node.description().is_none() {
214                node.set_description(text);
215            }
216            if node.label().is_none() {
217                node.set_label(text);
218            }
219        });
220    }
221}