grafix_toolbox/gui/elements/
button.rs1use super::*;
2
3#[derive(Default, Debug)]
4pub struct Button {
5 offset: Vec2,
6 size: Vec2,
7 scale: f32,
8 text: Str,
9 easing: f32,
10 last_pressed: bool,
11 pub pressed: bool,
12}
13impl Button {
14 pub fn draw<'s: 'l, 'l>(&'s mut self, r: &mut RenderLock<'l>, t: &'l Theme, layout @ Surf { pos, size }: Surf, text: &str) -> bool {
15 let (s, font, hovered) = (self, &t.font, r.hovers_in(layout));
16
17 if &*s.text != text || s.size != size {
18 ((s.offset, s.scale), s.size, s.text) = (u::fit_line(text, font, t.font_size, size), size, text.into());
19 }
20 let Self {
21 offset,
22 scale,
23 ref mut easing,
24 ref mut last_pressed,
25 ref mut pressed,
26 ..
27 } = *s;
28
29 t.ease(easing, hovered);
30
31 let clicked = *pressed && !*last_pressed;
32 *last_pressed = *pressed;
33 *pressed &= hovered;
34 r.draw_with_logic(
35 Rect { pos, size, color: t.fg(easing, *pressed) },
36 move |e, _, _| {
37 let mut press = |m: Mod| (*pressed, *last_pressed) = (m.pressed(), m.released());
38 match *e {
39 MouseButton { m, .. } => press(m),
40 Keyboard { key: Key::Space, m } => press(m),
41 _ => return Pass,
42 }
43 Accept
44 },
45 0,
46 );
47
48 r.draw(Text {
49 pos: pos.sum(offset),
50 color: t.text(hovered, clicked),
51 scale,
52 text,
53 font,
54 });
55 clicked
56 }
57}
58
59impl<'s: 'l, 'l> Lock::Button<'s, 'l, '_> {
60 pub fn draw(self, g: impl Into<Surf>, te: impl AsRef<str>) -> bool {
61 let Self { s, r, t } = self;
62 s.draw(r, t, g.into(), te.as_ref())
63 }
64}