Skip to main content

rlvgl_ui/
icon.rs

1// SPDX-License-Identifier: MIT
2//! Icon font helpers and Button extension for rlvgl-ui.
3//!
4//! Maps human-readable icon names to LVGL symbol codepoints and extends the
5//! [`rlvgl_widgets::button::Button`] widget with a fluent `icon` method.
6
7use alloc::string::{String, ToString};
8use core::fmt::Write;
9use rlvgl_widgets::button::Button;
10
11/// Resolve a human-friendly icon name to an LVGL symbol string.
12pub fn lookup(name: &str) -> Option<&'static str> {
13    match name {
14        "save" => Some("\u{f0c7}"),
15        "edit" => Some("\u{f304}"),
16        "close" => Some("\u{f00d}"),
17        "gear" => Some("\u{f013}"),
18        _ => None,
19    }
20}
21
22/// Extension trait adding an `icon` method to buttons.
23pub trait Icon {
24    /// Prefix the button label with the specified icon, if known.
25    fn icon(self, name: &str) -> Self;
26}
27
28impl Icon for Button {
29    fn icon(mut self, name: &str) -> Self {
30        if let Some(sym) = lookup(name) {
31            let text = self.text().to_string();
32            let mut buf = String::new();
33            // Write formatted text into the buffer; writing to a String cannot fail.
34            let _ = write!(&mut buf, "{sym} {text}");
35            self.set_text(&buf);
36        }
37        self
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use rlvgl_core::widget::Rect;
45
46    #[test]
47    fn icon_prefixes_label() {
48        let btn = Button::new(
49            "Save",
50            Rect {
51                x: 0,
52                y: 0,
53                width: 10,
54                height: 10,
55            },
56        )
57        .icon("save");
58        assert!(btn.text().starts_with(lookup("save").unwrap()));
59    }
60}