Skip to main content

rust_glass/widgets/
popup.rs

1//! Popups and tooltips. A popup grows out of the control that opened it.
2
3use crate::animation::{Spring, SpringRect, Tuning};
4use crate::context::{Context, Id, Order, Response, Sense};
5use crate::geometry::{Rect, Vec2, lerp, smoothstep, vec2};
6use crate::input::Key;
7use crate::material::{Corner, Glass, Material};
8use crate::paint::Painter;
9use crate::text::{TextStyle, Weight};
10use crate::ui::Ui;
11
12#[derive(Clone, Copy, Default)]
13struct PopupState {
14    shape: SpringRect,
15    t: Spring,
16    size: Vec2,
17    live: bool,
18    anchor: Vec2,
19    /// Frame in which it opened, so the opening click does not close it.
20    born: u64,
21}
22
23/// How far a popup has formed, 0 to 1. The anchor fades out with it.
24pub fn popup_progress(ctx: &mut Context, id: Id) -> f32 {
25    let s: PopupState = ctx.get(id.with("popup"));
26    if s.live { s.t.value.clamp(0.0, 1.0) } else { 0.0 }
27}
28
29/// Glass bubble that grows out of `anchor` while [`Context::popup_open`] is set
30/// for `id`, and flows back when it closes.
31pub fn popup(ctx: &mut Context, id: Id, anchor: Rect, width: f32, f: impl FnOnce(&mut Ui)) {
32    let open = ctx.popup_open(id);
33    let key = id.with("popup");
34    let mut s: PopupState = ctx.get(key);
35    if !open && !s.live {
36        return;
37    }
38    if open && !s.live {
39        s = PopupState {
40            shape: SpringRect::new(anchor),
41            t: Spring::new(0.0),
42            size: s.size,
43            live: true,
44            anchor: anchor.min,
45            born: ctx.frame,
46        };
47    }
48    // Stay glued to an anchor that scrolls or moves with its window.
49    let carried = anchor.min - s.anchor;
50    s.anchor = anchor.min;
51    s.shape.center.x.value += carried.x;
52    s.shape.center.y.value += carried.y;
53    let dt = ctx.dt;
54    let size = if s.size == Vec2::ZERO { vec2(width, 60.0) } else { s.size };
55    let full = place(anchor, size, ctx.screen);
56    let target = if open { full } else { anchor };
57    let (pt, st) = if open {
58        (ctx.tuning(Tuning::new(0.36, 0.80)), ctx.tuning(Tuning::new(0.40, 0.72)))
59    } else {
60        (ctx.tuning(Tuning::new(0.30, 0.95)), ctx.tuning(Tuning::new(0.30, 0.95)))
61    };
62    let mut moving = s.shape.step(target, pt, st, dt);
63    moving |= s.t.step(open as u32 as f32, ctx.tuning(Tuning::new(if open { 0.30 } else { 0.24 }, 1.0)), dt);
64    // A closing popup is gone once it has faded out, even if its shape is
65    // still a fraction of a point from the anchor.
66    if !open && (!moving || s.t.value < 0.01) {
67        s.live = false;
68        ctx.set(key, s);
69        ctx.request_repaint();
70        return;
71    }
72    if moving {
73        ctx.request_repaint();
74    }
75    let t = s.t.value.clamp(0.0, 1.0);
76    let shape = s.shape.rect();
77    let layer = ctx.layer(key, Order::Popup);
78    ctx.interact(key.with("block"), shape, Rect::EVERYTHING, layer, Sense::Hover);
79
80    let m = ctx.theme.regular.lerp(&ctx.theme.thick, t);
81    let radius = lerp(anchor.height() * 0.5, 22.0, t).min(shape.height() * 0.5);
82    // The bubble fades in and out over the same stretch in which the
83    // control that opened it fades the other way, so the two cross over
84    // instead of the bubble lingering on top.
85    let presence = popup_presence(t);
86    let mut g = Glass::new(shape, Corner::Radius(radius), m).presence(presence);
87    let a = ctx.prepare_glass(key, &mut g, false);
88    ctx.painter(layer, Rect::EVERYTHING).glass(&g);
89
90    // Content is laid out at full size and revealed as the bubble opens.
91    let show = smoothstep(0.30, 0.85, t);
92    let mut used = size;
93    if open || show > 0.01 {
94        let clip = shape.shrink(1.0);
95        let offset = (shape.center() - full.center()) * 0.6;
96        let r = full.translate(offset);
97        let mut ui =
98            Ui::new(ctx, layer, key, Rect { min: r.min + vec2(8.0, 8.0), max: r.max - vec2(8.0, 8.0) });
99        ui.max_rect.max.y = 1.0e5;
100        ui.clip = clip;
101        ui.opacity = show;
102        ui.surface = a.surface();
103        ui.spacing = 2.0;
104        f(&mut ui);
105        used = vec2(width, ui.used().height() + 16.0);
106    }
107    // The content comes into focus as the bubble opens. The blur fades with
108    // the bubble, so it never outlasts it.
109    let blur = BLUR_WHILE_FORMING * (1.0 - smoothstep(0.30, 0.95, t));
110    let inside = Corner::Radius((radius - 1.0).max(0.0));
111    forming_blur(&mut ctx.painter(layer, Rect::EVERYTHING), shape.shrink(1.0), inside, blur, presence);
112    if (used - s.size).length() > 0.5 {
113        s.size = used;
114        ctx.request_repaint();
115    }
116    let young = ctx.frame <= s.born + 1;
117    ctx.set(key, s);
118    if open && !young {
119        let outside = ctx.pressed_outside(shape.union(anchor));
120        if outside || ctx.input.take_key(Key::Escape) {
121            ctx.set_popup(id, false);
122        }
123    }
124}
125
126/// Blur radius of the content of an overlay that has just started to form.
127pub(crate) const BLUR_WHILE_FORMING: f32 = 10.0;
128
129/// How present the glass of a popup is at progress `t`. A menu button fades
130/// its own glass with `1 - popup_presence(t)`.
131pub(crate) fn popup_presence(t: f32) -> f32 {
132    smoothstep(0.0, 0.4, t)
133}
134
135/// Blurs what is under `rect` by `radius`, mixed in at `presence`, so the
136/// blur of an overlay fades out together with the overlay.
137pub(crate) fn forming_blur(p: &mut Painter, rect: Rect, corner: Corner, radius: f32, presence: f32) {
138    if radius < 0.5 || presence <= 0.001 {
139        return;
140    }
141    let opacity = std::mem::replace(&mut p.opacity, 1.0);
142    p.glass(&Glass::new(rect, corner, Material::blur(radius)).presence(presence));
143    p.opacity = opacity;
144}
145
146/// Below the anchor if it fits, otherwise above, always inside the screen.
147fn place(anchor: Rect, size: Vec2, screen: Rect) -> Rect {
148    let below = anchor.max.y + 6.0 + size.y <= screen.max.y - 8.0;
149    let y = if below || anchor.min.y - size.y < 8.0 { anchor.min.y } else { anchor.max.y - size.y };
150    let x = if anchor.center().x > screen.center().x { anchor.max.x - size.x } else { anchor.min.x };
151    Rect::from_min_size(vec2(x, y), size).clamp_inside(screen.shrink(8.0))
152}
153
154/// Shows `text` in a small bubble above `anchor` after the pointer rests on
155/// it. Call it every frame the anchor is hovered.
156pub fn tooltip(ctx: &mut Context, id: Id, anchor: Rect, text: &str) {
157    if text.is_empty() {
158        return;
159    }
160    let key = id.with("tooltip");
161    #[derive(Clone, Copy, Default)]
162    struct Since {
163        t: f64,
164        frame: u64,
165    }
166    let mut s: Since = ctx.get(key);
167    if s.frame + 1 < ctx.frame {
168        s.t = ctx.time;
169    }
170    s.frame = ctx.frame;
171    ctx.set(key, s);
172    let wait = 0.45;
173    if ctx.input.down {
174        return;
175    }
176    let t = ((ctx.time - s.t - wait) / 0.16).clamp(0.0, 1.0) as f32;
177    if t < 1.0 {
178        ctx.request_repaint();
179    }
180    if t <= 0.0 {
181        return;
182    }
183    let l = ctx.text.layout(text, &TextStyle::new(12.0).weight(Weight::Medium));
184    let size = l.size + vec2(22.0, 13.0);
185    let mut c = vec2(anchor.center().x, anchor.min.y - 8.0 - size.y * 0.5);
186    if c.y - size.y * 0.5 < 6.0 {
187        c.y = anchor.max.y + 8.0 + size.y * 0.5;
188    }
189    let r = Rect::from_center_size(c, size).clamp_inside(ctx.screen.shrink(6.0));
190    let e = smoothstep(0.0, 1.0, t);
191    let r = r.scale_from_center(0.9 + 0.1 * e, 0.9 + 0.1 * e);
192    let layer = ctx.layer(Id::new("tooltip"), Order::Tooltip);
193    let mut g = Glass::new(r, Corner::Capsule, ctx.theme.thick).presence(e);
194    g.material.shadow_radius = 14.0;
195    g.material.shadow_y = 5.0;
196    let a = ctx.prepare_glass(key, &mut g, false);
197    let mut p = ctx.painter(layer, Rect::EVERYTHING);
198    p.glass(&g);
199    p.text_centered(r, &l, a.surface().text_color().fade(e), 1.0);
200}
201
202impl Response {
203    /// Show a tooltip while hovered.
204    pub fn on_hover_text(self, ui: &mut Ui, text: &str) -> Response {
205        if self.hovered {
206            tooltip(ui.ctx, self.id, self.rect, text);
207        }
208        self
209    }
210}