Skip to main content

rlvgl_ui/
button.rs

1// SPDX-License-Identifier: MIT
2//! Button helpers and [`IconButton`] component for rlvgl-ui.
3//!
4//! Wraps the [`rlvgl_widgets::button::Button`] widget from `rlvgl-widgets` to
5//! render glyph-only controls.
6
7use crate::icon::Icon;
8use rlvgl_core::{
9    event::Event,
10    renderer::Renderer,
11    widget::{Rect, Widget},
12};
13use rlvgl_widgets::button::Button as BaseButton;
14
15/// Icon-only button wrapper.
16pub struct IconButton {
17    inner: BaseButton,
18}
19
20impl IconButton {
21    /// Create a new icon button using the named glyph.
22    pub fn new(icon: &str, bounds: Rect) -> Self {
23        let inner = BaseButton::new("", bounds).icon(icon);
24        Self { inner }
25    }
26
27    /// Register a click handler executed when the button is released.
28    pub fn on_click<F: FnMut(&mut BaseButton) + 'static>(mut self, handler: F) -> Self {
29        self.inner.set_on_click(handler);
30        self
31    }
32
33    /// Immutable access to the button style.
34    pub fn style(&self) -> &rlvgl_core::style::Style {
35        self.inner.style()
36    }
37
38    /// Mutable access to the button style.
39    pub fn style_mut(&mut self) -> &mut rlvgl_core::style::Style {
40        self.inner.style_mut()
41    }
42}
43
44impl Widget for IconButton {
45    fn bounds(&self) -> Rect {
46        self.inner.bounds()
47    }
48
49    fn draw(&self, renderer: &mut dyn Renderer) {
50        self.inner.draw(renderer);
51    }
52
53    fn handle_event(&mut self, event: &Event) -> bool {
54        self.inner.handle_event(event)
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use crate::icon::lookup;
62    use rlvgl_core::widget::Rect;
63
64    #[test]
65    fn icon_button_uses_symbol() {
66        let btn = IconButton::new(
67            "save",
68            Rect {
69                x: 0,
70                y: 0,
71                width: 10,
72                height: 10,
73            },
74        );
75        assert!(btn.inner.text().starts_with(lookup("save").unwrap()));
76    }
77}