ironhtml_bootstrap/
badge.rs

1//! Bootstrap badge components.
2//!
3//! Provides type-safe Bootstrap badges matching the
4//! [Bootstrap badge documentation](https://getbootstrap.com/docs/5.3/components/badge/).
5
6use crate::Color;
7use ironhtml::typed::Element;
8use ironhtml_elements::Span;
9
10extern crate alloc;
11use alloc::format;
12
13/// Create a Bootstrap badge.
14///
15/// ## Example
16///
17/// ```rust
18/// use ironhtml_bootstrap::{badge::badge, Color};
19///
20/// let b = badge(Color::Primary, "New");
21/// assert!(b.render().contains("text-bg-primary"));
22/// ```
23#[must_use]
24pub fn badge(color: Color, text: &str) -> Element<Span> {
25    let class = format!("badge text-bg-{}", color.as_str());
26    Element::<Span>::new().class(&class).text(text)
27}
28
29/// Create a pill badge (rounded).
30///
31/// ## Example
32///
33/// ```rust
34/// use ironhtml_bootstrap::{badge::badge_pill, Color};
35///
36/// let b = badge_pill(Color::Danger, "99+");
37/// assert!(b.render().contains("rounded-pill"));
38/// ```
39#[must_use]
40pub fn badge_pill(color: Color, text: &str) -> Element<Span> {
41    let class = format!("badge rounded-pill text-bg-{}", color.as_str());
42    Element::<Span>::new().class(&class).text(text)
43}
44
45/// Create a positioned badge (for notifications).
46///
47/// Use this inside a position-relative button.
48#[must_use]
49pub fn badge_positioned(color: Color, text: &str) -> Element<Span> {
50    let class = format!(
51        "position-absolute top-0 start-100 translate-middle badge rounded-pill bg-{}",
52        color.as_str()
53    );
54    Element::<Span>::new()
55        .class(&class)
56        .text(text)
57        .child::<Span, _>(|s| s.class("visually-hidden").text("notifications"))
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_badge() {
66        let b = badge(Color::Primary, "New");
67        assert!(b.render().contains("text-bg-primary"));
68        assert!(b.render().contains("New"));
69    }
70
71    #[test]
72    fn test_badge_pill() {
73        let b = badge_pill(Color::Success, "OK");
74        assert!(b.render().contains("rounded-pill"));
75    }
76
77    #[test]
78    fn test_all_colors() {
79        for color in [
80            Color::Primary,
81            Color::Secondary,
82            Color::Success,
83            Color::Danger,
84        ] {
85            let b = badge(color, "Test");
86            assert!(b.render().contains(&format!("text-bg-{}", color.as_str())));
87        }
88    }
89}