Skip to main content

rust_glass/widgets/
button.rs

1//! Buttons, button groups, split buttons and links.
2
3use crate::accessibility::Role;
4use crate::animation::Tuning;
5use crate::color::Color;
6use crate::context::{Context, Cursor, Id, Response, Sense};
7use crate::geometry::{Rect, Vec2, vec2};
8use crate::icon::Icon;
9use crate::material::{Corner, Glass, GlassShape, Material};
10use crate::text::{TextStyle, Weight};
11use crate::ui::{Ui, Widget};
12use crate::widgets::press::PressEffect;
13
14/// The surface of a button.
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub enum ButtonKind {
17    /// Regular glass.
18    Glass,
19    /// Glass in the accent color, for the main action.
20    Prominent,
21    /// Clear glass, for buttons over photos and video.
22    Clear,
23    /// Glass tinted with a color.
24    Tinted(Color),
25    /// No surface until hovered, with the label in the accent color.
26    Plain,
27}
28
29/// The size of a button.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum ButtonSize {
32    /// 80 percent of the control height.
33    Small,
34    /// The control height of the theme.
35    Regular,
36    /// 136 percent of the control height.
37    Large,
38}
39
40/// A button with a label, an icon or both. It swells and stretches towards
41/// the pointer while pressed.
42///
43/// ```
44/// # use rust_glass::prelude::*;
45/// # fn f(ui: &mut Ui) {
46/// if ui.add(Button::new("Share").icon(Icon::Share).prominent()).clicked() {
47///     // Share.
48/// }
49/// # }
50/// ```
51#[derive(Clone, Debug)]
52pub struct Button<'a> {
53    label: &'a str,
54    icon: Option<Icon>,
55    kind: ButtonKind,
56    size: ButtonSize,
57    corner: Corner,
58    min_width: f32,
59    width: Option<f32>,
60    selected: bool,
61    id: Option<Id>,
62}
63
64impl<'a> Button<'a> {
65    /// Creates a glass button with a text label.
66    pub fn new(label: &'a str) -> Self {
67        Self {
68            label,
69            icon: None,
70            kind: ButtonKind::Glass,
71            size: ButtonSize::Regular,
72            corner: Corner::Capsule,
73            min_width: 0.0,
74            width: None,
75            selected: false,
76            id: None,
77        }
78    }
79    /// Round button with only an icon.
80    pub fn icon_only(icon: Icon) -> Self {
81        Self { icon: Some(icon), ..Self::new("") }
82    }
83    /// Shows `icon` before the label.
84    pub fn icon(mut self, icon: Icon) -> Self {
85        self.icon = Some(icon);
86        self
87    }
88    /// Sets the kind of surface.
89    pub fn kind(mut self, kind: ButtonKind) -> Self {
90        self.kind = kind;
91        self
92    }
93    /// Uses the accent color, for the main action.
94    pub fn prominent(self) -> Self {
95        self.kind(ButtonKind::Prominent)
96    }
97    /// Uses clear glass, for buttons over photos and video.
98    pub fn clear(self) -> Self {
99        self.kind(ButtonKind::Clear)
100    }
101    /// Shows only the label, in the accent color, until hovered.
102    pub fn plain(self) -> Self {
103        self.kind(ButtonKind::Plain)
104    }
105    /// Uses glass tinted with `color`.
106    pub fn tinted(self, color: Color) -> Self {
107        self.kind(ButtonKind::Tinted(color))
108    }
109    /// Sets the size.
110    pub fn size(mut self, size: ButtonSize) -> Self {
111        self.size = size;
112        self
113    }
114    /// Uses the small size.
115    pub fn small(self) -> Self {
116        self.size(ButtonSize::Small)
117    }
118    /// Uses the large size.
119    pub fn large(self) -> Self {
120        self.size(ButtonSize::Large)
121    }
122    /// Sets the corners. The default is a capsule.
123    pub fn corner(mut self, corner: impl Into<Corner>) -> Self {
124        self.corner = corner.into();
125        self
126    }
127    /// Makes the button at least `width` points wide.
128    pub fn min_width(mut self, width: f32) -> Self {
129        self.min_width = width;
130        self
131    }
132    /// Makes the button exactly `width` points wide.
133    pub fn width(mut self, width: f32) -> Self {
134        self.width = Some(width);
135        self
136    }
137    /// Draw as switched on.
138    pub fn selected(mut self, on: bool) -> Self {
139        self.selected = on;
140        self
141    }
142    /// Gives the button an id of its own, for buttons that move in the layout.
143    pub fn id(mut self, id: Id) -> Self {
144        self.id = Some(id);
145        self
146    }
147
148    fn metrics(&self, ctx: &Context) -> (f32, f32, f32, f32) {
149        let h = ctx.theme.control_height;
150        match self.size {
151            ButtonSize::Small => (h * 0.8, 12.0, 14.0, 11.0),
152            ButtonSize::Regular => (h, 14.0, 17.0, 15.0),
153            ButtonSize::Large => (h * 1.36, 16.0, 21.0, 22.0),
154        }
155    }
156}
157
158impl Widget for Button<'_> {
159    fn ui(self, ui: &mut Ui) -> Response {
160        let (h, font, icon_size, pad) = self.metrics(ui.ctx);
161        let st = TextStyle::new(font).weight(Weight::Semibold);
162        let text = (!self.label.is_empty()).then(|| ui.layout_text(self.label, &st));
163        let tw = text.as_ref().map_or(0.0, |t| t.size.x);
164        let gap = if self.icon.is_some() && text.is_some() { 7.0 } else { 0.0 };
165        let iw = if self.icon.is_some() { icon_size } else { 0.0 };
166        let w = if text.is_none() { h } else { (tw + gap + iw + pad * 2.0).max(self.min_width) };
167        let w = self.width.unwrap_or(w);
168        let rect = ui.allocate(vec2(w, h));
169        let id = match self.id {
170            Some(id) => id,
171            None => ui.next_id(),
172        };
173        let r = ui.interact(id, rect, Sense::Click);
174        if let Some(n) = ui.access(id, Role::Button, rect) {
175            n.label(if self.label.is_empty() { self.icon.map_or("", Icon::name) } else { self.label });
176            if self.selected {
177                n.selected(true);
178            }
179        }
180        if ui.enabled {
181            ui.ctx.focusable(id);
182        }
183        if r.hovered {
184            ui.ctx.cursor = Cursor::Pointer;
185        }
186
187        let strength = if ui.enabled { 1.0 } else { 0.0 };
188        let gel = PressEffect::update(ui.ctx, &r, strength);
189        let on_glass = ui.surface.is_glass();
190        let accent = ui.ctx.theme.accent;
191        let fill = match self.kind {
192            ButtonKind::Prominent => Some(accent),
193            ButtonKind::Tinted(c) => Some(c),
194            _ if self.selected => Some(accent),
195            _ => None,
196        };
197        let mut color = ui.surface.text_color();
198        let theme_regular = ui.ctx.theme.regular;
199        let theme_clear = ui.ctx.theme.clear;
200        match (self.kind, on_glass) {
201            (ButtonKind::Plain, _) => {
202                color = accent;
203                let a = gel.hover * 0.8 + gel.amount * 0.8;
204                let f = ui.surface.fill_color().fade(a);
205                ui.painter().fill(gel.rect, self.corner, f);
206            }
207            // Glass on glass muddies both. On a glass surface buttons are fills.
208            (_, true) => {
209                let base = fill.unwrap_or(ui.surface.fill_color());
210                let lit = Color::white(0.05 * gel.hover + 0.08 * gel.amount.max(0.0));
211                let mut p = ui.painter();
212                p.fill(gel.rect, self.corner, base);
213                p.fill(gel.rect, self.corner, lit);
214                if fill.is_some() {
215                    color = Color::WHITE;
216                }
217            }
218            (kind, false) => {
219                let mut m = if kind == ButtonKind::Clear { theme_clear } else { theme_regular };
220                if let Some(c) = fill {
221                    m = tinted(m, c);
222                }
223                let mut g = Glass::new(gel.rect, self.corner, m);
224                let a = ui.ctx.prepare_glass(id, &mut g, true);
225                gel.apply(&mut g);
226                color = if fill.is_some() { Color::WHITE } else { a.surface().text_color() };
227                ui.painter().glass(&g);
228            }
229        }
230
231        let c = gel.rect.center();
232        let total = (tw + gap + iw) * gel.scale;
233        let mut x = c.x - total * 0.5;
234        let mut p = ui.painter();
235        if let Some(i) = self.icon {
236            p.icon(vec2(x + iw * gel.scale * 0.5, c.y), icon_size * gel.scale, i, color);
237            x += (iw + gap) * gel.scale;
238        }
239        if let Some(t) = &text {
240            let tr = Rect::from_center_size(vec2(x + tw * gel.scale * 0.5, c.y), t.size);
241            p.text_centered(tr, t, color, gel.scale);
242        }
243        ui.focus_ring(id, gel.rect, self.corner);
244        r
245    }
246}
247
248/// Colored glass: denser and less blurred through than the neutral material.
249pub fn tinted(mut m: Material, c: Color) -> Material {
250    m.tint = Some(c.alpha(0.86));
251    m.inner_glow = 0.15;
252    m.rim = 0.8;
253    m.shadow_tint = 0.7;
254    m
255}
256
257/// A row of icon buttons on one piece of glass.
258pub struct ButtonGroup<'a> {
259    items: &'a [(Icon, &'a str)],
260}
261
262impl<'a> ButtonGroup<'a> {
263    /// Icon and tooltip per button.
264    pub fn new(items: &'a [(Icon, &'a str)]) -> Self {
265        Self { items }
266    }
267
268    /// Returns the clicked index.
269    pub fn show(self, ui: &mut Ui) -> Option<usize> {
270        let h = ui.ctx.theme.control_height + 4.0;
271        let cell = h + 4.0;
272        let n = self.items.len() as f32;
273        let rect = ui.allocate(vec2(cell * n, h));
274        let id = ui.next_id();
275        let mut clicked = None;
276        let mut gels = Vec::with_capacity(self.items.len());
277        let mut bar = rect;
278        let mut press: f32 = 0.0;
279        for (i, item) in self.items.iter().enumerate() {
280            let r = Rect::from_min_size(vec2(rect.min.x + cell * i as f32, rect.min.y), vec2(cell, h));
281            let res = ui.interact(id.with(i), r, Sense::Click);
282            if let Some(n) = ui.access(res.id, Role::Button, r) {
283                n.label(item.1);
284            }
285            ui.ctx.focusable(res.id);
286            if res.clicked {
287                clicked = Some(i);
288            }
289            let g = PressEffect::update(ui.ctx, &res, 1.0);
290            press = press.max(g.amount);
291            if g.amount.abs() > 0.001 {
292                // The whole bar swells around the pressed item.
293                bar = bar.union(g.rect.shrink2(vec2(0.0, 1.0)));
294            }
295            if res.hovered {
296                crate::widgets::popup::tooltip(ui.ctx, res.id, r, item.1);
297            }
298            gels.push((g, r));
299        }
300        let m = ui.ctx.theme.regular;
301        let mut glass = Glass::new(bar, Corner::Capsule, m);
302        let a = ui.ctx.prepare_glass(id, &mut glass, true);
303        glass.brightness = 0.04 * press;
304        let color = a.surface().text_color();
305        let hl = a.surface().fill_color();
306        let mut p = ui.painter();
307        p.glass(&glass);
308        for (i, (g, r)) in gels.iter().enumerate() {
309            p.fill(r.shrink(4.0), Corner::Capsule, hl.fade(g.hover * 0.8));
310            p.icon(g.rect.center(), 18.0 * g.scale, self.items[i].0, color);
311        }
312        clicked
313    }
314}
315
316/// A floating action button that splits into several when pressed. The pieces
317/// are one fused glass surface, so they part and merge like drops.
318pub struct SplitButton<'a> {
319    icon: Icon,
320    items: &'a [(Icon, Color)],
321}
322
323impl<'a> SplitButton<'a> {
324    /// Creates a button showing `icon` that splits into one tinted drop per
325    /// item.
326    pub fn new(icon: Icon, items: &'a [(Icon, Color)]) -> Self {
327        Self { icon, items }
328    }
329
330    /// Shows the button and returns the index of the item that was clicked.
331    pub fn show(self, ui: &mut Ui) -> Option<usize> {
332        let d = 52.0;
333        let gap = 12.0;
334        let n = self.items.len();
335        let rect = ui.allocate(vec2(d + (d + gap) * n as f32, d));
336        let id = ui.next_id();
337        let mut open: bool = ui.ctx.get(id);
338        let home = Rect::from_min_size(rect.min, Vec2::splat(d));
339        let main = ui.interact(id.with("main"), home, Sense::Click);
340        if main.clicked {
341            open = !open;
342        }
343        if let Some(n) = ui.access(main.id, Role::Button, home) {
344            n.label(self.icon.name()).expanded(open);
345        }
346        ui.ctx.set(id, open);
347        let gel = PressEffect::update(ui.ctx, &main, 1.0);
348        let mut clicked = None;
349        let mut shapes = vec![GlassShape::new(gel.rect, Corner::Capsule)];
350        let mut faces = Vec::new();
351        let (mut lead, mut tail) = (0.0f32, 1.0f32);
352        for (i, item) in self.items.iter().enumerate() {
353            // Each drop leaves a little later than the one before.
354            let t = ui.ctx.animate(
355                id.with(("drop", i)),
356                open as u32 as f32,
357                Tuning::new(0.40 + 0.055 * i as f32, 0.72),
358            );
359            lead = lead.max(t.clamp(0.0, 1.0));
360            tail = tail.min(t.clamp(0.0, 1.0));
361            let x = home.min.x + (d + gap) * (i + 1) as f32 * t;
362            let size = d * (0.45 + 0.55 * t.clamp(0.0, 1.0));
363            let r = Rect::from_center_size(vec2(x + d * 0.5, home.center().y), Vec2::splat(size));
364            let hit = if open { r } else { Rect::NOTHING };
365            let res = ui.interact(id.with(("item", i)), hit, if open { Sense::Click } else { Sense::Hover });
366            if open && let Some(n) = ui.access(res.id, Role::Button, r) {
367                n.label(item.0.name());
368            }
369            let g = PressEffect::update(ui.ctx, &Response { rect: r, ..res }, if open { 1.0 } else { 0.0 });
370            if res.clicked {
371                clicked = Some(i);
372                ui.ctx.set(id, false);
373            }
374            shapes.push(
375                GlassShape::new(g.rect, Corner::Capsule).tint(Some(item.1.alpha(0.62 * t.clamp(0.0, 1.0)))),
376            );
377            faces.push((g, item.0, t));
378        }
379        // The pull between drops exists only while they are in motion: none
380        // while they sit inside the main one, none once they have parted.
381        let part = crate::geometry::smoothstep(0.55, 0.96, tail);
382        let fuse = 22.0 * crate::geometry::smoothstep(0.0, 0.25, lead) * (1.0 - part);
383        let m = ui.ctx.theme.regular;
384        let mut glass = Glass::group(shapes, m).fuse(fuse);
385        let a = ui.ctx.prepare_glass(id, &mut glass, true);
386        glass.brightness = 0.05 * gel.amount.max(0.0);
387        let color = a.surface().text_color();
388        let t = ui.ctx.animate(id.with("rot"), open as u32 as f32, Tuning::BOUNCY);
389        let mut p = ui.painter();
390        p.glass(&glass);
391        let c = gel.rect.center();
392        // Plus that turns into a cross.
393        let a0 = t * std::f32::consts::FRAC_PI_4;
394        if self.icon == Icon::Plus {
395            for k in 0..2 {
396                let a = a0 + k as f32 * std::f32::consts::FRAC_PI_2;
397                let v = vec2(a.cos(), a.sin()) * 8.5 * gel.scale;
398                p.line(c - v, c + v, 2.4, color);
399            }
400        } else {
401            p.icon(c, 22.0 * gel.scale, self.icon, color);
402        }
403        for (g, icon, t) in &faces {
404            let k = ((t - 0.35) / 0.5).clamp(0.0, 1.0);
405            p.icon(g.rect.center(), 22.0 * g.scale * (0.6 + 0.4 * k), *icon, Color::white(k));
406        }
407        clicked
408    }
409}
410
411impl Ui<'_> {
412    /// Adds a glass button. Check [`Response::clicked`] on the result.
413    pub fn button(&mut self, label: &str) -> Response {
414        self.add(Button::new(label))
415    }
416    /// Adds a button in the accent color, for the main action.
417    pub fn prominent_button(&mut self, label: &str) -> Response {
418        self.add(Button::new(label).prominent())
419    }
420    /// Adds a round button with only an icon.
421    pub fn icon_button(&mut self, icon: Icon) -> Response {
422        self.add(Button::icon_only(icon))
423    }
424
425    /// Text that behaves like a link.
426    pub fn link(&mut self, label: &str) -> Response {
427        let st = TextStyle::new(self.ctx.theme.body_size).weight(Weight::Medium);
428        let l = self.layout_text(label, &st);
429        let r = self.allocate_response(l.size, Sense::Click);
430        if let Some(n) = self.access(r.id, Role::Link, r.rect) {
431            n.label(label);
432        }
433        let c = self.ctx.theme.accent;
434        let u = self.ctx.animate_bool(r.id.with("u"), r.hovered, Tuning::SNAP);
435        if r.hovered {
436            self.ctx.cursor = Cursor::Pointer;
437        }
438        self.ctx.focusable(r.id);
439        let mut p = self.painter();
440        p.text(r.rect.min, &l, c);
441        let y = r.rect.max.y - 1.0;
442        let w = r.rect.width();
443        p.line(vec2(r.rect.min.x, y), vec2(r.rect.min.x + w * u, y), 1.2, c.fade(u));
444        self.focus_ring(r.id, r.rect, 4.0);
445        r
446    }
447
448    /// Adds a link that opens `url` in the browser when clicked.
449    pub fn hyperlink(&mut self, label: &str, url: &str) -> Response {
450        let r = self.link(label);
451        if r.clicked {
452            self.ctx.host_commands.push(crate::context::HostCommand::OpenUrl(url.into()));
453        }
454        r
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461    use crate::context::{Context, Order};
462    use crate::input::Event;
463
464    #[test]
465    fn drops_part_completely() {
466        let mut ctx = Context::new();
467        let mut frame = |i: usize, ev: &[Event]| {
468            ctx.begin_frame(vec2(600.0, 200.0), 1.0, i as f64 / 60.0, ev);
469            let layer = ctx.layer(Id::new("l"), Order::Content);
470            let mut ui =
471                Ui::new(&mut ctx, layer, Id::new("u"), crate::geometry::rect(20.0, 20.0, 500.0, 100.0));
472            SplitButton::new(Icon::Plus, &[(Icon::Star, Color::RED), (Icon::Heart, Color::BLUE)])
473                .show(&mut ui);
474            ctx.end_frame();
475            ctx.paint.data.glasses[0].fuse
476        };
477        assert_eq!(frame(0, &[]), 0.0);
478        frame(1, &[Event::PointerMoved(vec2(45.0, 45.0))]);
479        frame(2, &[Event::PointerDown]);
480        frame(3, &[Event::PointerUp]);
481        let fuse: Vec<f32> = (4..120).map(|i| frame(i, &[])).collect();
482        assert!(fuse.iter().cloned().fold(0.0, f32::max) > 10.0, "they pull while parting");
483        assert_eq!(*fuse.last().unwrap(), 0.0);
484    }
485}