Skip to main content

bhoo/systems/material/
badge.rs

1use crate::*;
2
3/// Badge appearance; the accessible description is supplied separately.
4#[derive(Clone, Copy, Debug)]
5pub enum BadgeContent<'a> {
6    Dot,
7    Label(&'a str),
8    /// Shorten long text to at most `max_graphemes`, including an ellipsis.
9    Text { text: &'a str, max_graphemes: usize },
10    /// Show a number, or the configured maximum followed by `+` when exceeded.
11    Number { value: u32, max: u32 },
12    /// Format digits and optionally derive the overflow maximum from a character limit.
13    FormattedNumber { value: u32, limit: BadgeNumberLimit, format: BadgeNumberFormat<'a> },
14}
15/// The numeric overflow threshold. A character limit reserves one character for the suffix.
16#[derive(Clone, Copy, Debug)]
17pub enum BadgeNumberLimit { Unlimited, Max(u32), MaxCharacters(u8) }
18/// Caller-supplied number formatting; grouping is disabled when `group_size` is zero.
19#[derive(Clone, Copy, Debug)]
20pub struct BadgeNumberFormat<'a> {
21    pub digits: [&'a str; 10],
22    pub group_separator: &'a str,
23    pub group_size: u8,
24    pub overflow_suffix: &'a str,
25}
26impl Default for BadgeNumberFormat<'_> {
27    fn default() -> Self { Self { digits: ["0","1","2","3","4","5","6","7","8","9"], group_separator: ",", group_size: 3, overflow_suffix: "+" } }
28}
29fn format_badge_number(value: u32, format: BadgeNumberFormat<'_>, grouping: bool) -> String {
30    let ascii = value.to_string();
31    let mut result = String::new();
32    for (index, digit) in ascii.bytes().enumerate() {
33        if grouping && format.group_size > 0 && index > 0 && (ascii.len()-index) % usize::from(format.group_size) == 0 { result.push_str(format.group_separator); }
34        result.push_str(format.digits[usize::from(digit-b'0')]);
35    }
36    result
37}
38/// Logical badge corner relative to its icon.
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum BadgeGravity {
41    TopStart,
42    #[default]
43    TopEnd,
44    BottomStart,
45    BottomEnd,
46}
47/// Badge placement offsets are in dp, positive toward the anchor center.
48#[derive(Clone, Copy, Debug, Default, PartialEq)]
49pub struct BadgeOptions {
50    pub gravity: BadgeGravity,
51    pub rtl: bool,
52    pub horizontal_offset: f32,
53    pub vertical_offset: f32,
54}
55
56impl Frame<'_> {
57    pub fn badge(&mut self, label: &str) {
58        let anchor = self.allocate(28.0);
59        let style = TextStyle {
60            size: 11.0,
61            weight: 500,
62            align: 1,
63            ..TextStyle::default()
64        };
65        let b = Rect {
66            x: anchor.x + 36.0,
67            y: anchor.y - 4.0,
68            width: (self.text_width(label, style) + 8.0).max(16.0),
69            height: 16.0,
70        };
71        self.rect(b, 8.0, self.ui.theme.error);
72        self.styled_text(b, label, self.ui.theme.on_error, style);
73    }
74    /// Overlay a Material badge on an icon without changing its layout or
75    /// adding a focus target. Call after the owner so its semantics can receive
76    /// the localized description; `rtl` mirrors the placement.
77    pub fn badge_at(
78        &mut self,
79        owner: u64,
80        icon: Rect,
81        content: BadgeContent<'_>,
82        description: &str,
83        rtl: bool,
84    ) -> bool {
85        self.badge_at_gravity(owner,icon,content,description,BadgeGravity::TopEnd,rtl)
86    }
87    /// Overlay a badge at a logical corner; start and end mirror in RTL.
88    pub fn badge_at_gravity(
89        &mut self,
90        owner: u64,
91        icon: Rect,
92        content: BadgeContent<'_>,
93        description: &str,
94        gravity: BadgeGravity,
95        rtl: bool,
96    ) -> bool {
97        self.badge_at_with_options(owner,icon,content,description,BadgeOptions{gravity,rtl,..BadgeOptions::default()})
98    }
99    /// Overlay a badge with logical corner and offsets toward the icon center.
100    pub fn badge_at_with_options(
101        &mut self,
102        owner: u64,
103        icon: Rect,
104        content: BadgeContent<'_>,
105        description: &str,
106        options: BadgeOptions,
107    ) -> bool {
108        if !icon.x.is_finite()
109            || !icon.y.is_finite()
110            || !icon.width.is_finite()
111            || !icon.height.is_finite()
112            || !options.horizontal_offset.is_finite()
113            || !options.vertical_offset.is_finite()
114            || icon.width <= 0.0
115            || icon.height <= 0.0
116        {
117            return false;
118        }
119        let style = TextStyle {
120            size: 11.0,
121            weight: 500,
122            align: 1,
123            ..TextStyle::default()
124        };
125        let owned_label;
126        let (width, height, x_offset, y_offset, label) = match content {
127            BadgeContent::Dot => (6.0, 6.0, 6.0, 6.0, None),
128            BadgeContent::Label(label) if !label.is_empty() && label.chars().count() <= 4 => (
129                (self.text_width(label, style) + 8.0).clamp(16.0, 34.0),
130                16.0,
131                12.0,
132                14.0,
133                Some(label),
134            ),
135            BadgeContent::Label(_) => return false,
136            BadgeContent::Text { text, max_graphemes } => {
137                if text.is_empty() || max_graphemes==0 {return false;}
138                let label=if text.grapheme_indices(true).nth(max_graphemes).is_some() {
139                    let end=text.grapheme_indices(true).nth(max_graphemes-1).map_or(text.len(),|(index,_)|index);
140                    owned_label=format!("{}…",&text[..end]);owned_label.as_str()
141                } else {text};
142                ((self.text_width(label,style)+8.0).max(16.0),16.0,12.0,14.0,Some(label))
143            }
144            BadgeContent::Number { value, max } => {
145                owned_label = if value > max { format!("{max}+") } else { value.to_string() };
146                let label=owned_label.as_str();
147                ((self.text_width(label, style)+8.0).max(16.0),16.0,12.0,14.0,Some(label))
148            }
149            BadgeContent::FormattedNumber { value, limit, format } => {
150                if format.digits.iter().any(|digit| digit.is_empty()) { return false; }
151                let max = match limit {
152                    BadgeNumberLimit::Unlimited => u32::MAX,
153                    BadgeNumberLimit::Max(max) => max,
154                    BadgeNumberLimit::MaxCharacters(0) => return false,
155                    BadgeNumberLimit::MaxCharacters(chars) => 10u32.checked_pow(u32::from(chars)-1).map_or(u32::MAX, |n| n-1),
156                };
157                owned_label = if value > max { let mut label = format_badge_number(max, format, false); label.push_str(format.overflow_suffix); label } else { format_badge_number(value, format, true) };
158                let label = owned_label.as_str();
159                ((self.text_width(label, style)+8.0).max(16.0),16.0,12.0,14.0,Some(label))
160            }
161        };
162        let start=matches!(options.gravity,BadgeGravity::TopStart|BadgeGravity::BottomStart);
163        let left=start!=options.rtl;
164        let bottom=matches!(options.gravity,BadgeGravity::BottomStart|BadgeGravity::BottomEnd);
165        let x = if left {
166            icon.x + x_offset - width
167        } else {
168            icon.x + icon.width - x_offset
169        };
170        let b = Rect {
171            x: x+if left {options.horizontal_offset}else{-options.horizontal_offset},
172            y: if bottom {icon.y+icon.height-y_offset-options.vertical_offset}else{icon.y-height+y_offset+options.vertical_offset},
173            width,
174            height,
175        };
176        self.rect(b, height / 2.0, self.ui.theme.error);
177        if let Some(label) = label {
178            self.styled_text(b, label, self.ui.theme.on_error, style);
179        }
180        if !description.is_empty()
181            && let Some(node) = self
182                .ui
183                .semantics
184                .iter_mut()
185                .rev()
186                .find(|node| node.id == owner)
187        {
188            node.label = format!("{}, {}", node.label, description).into();
189        }
190        true
191    }
192}
193
194#[cfg(test)]
195#[path = "badge.spec.rs"]
196mod tests;