yew_bootstrap/component/
badge.rs

1use yew::prelude::*;
2
3use crate::util::{Color, ArrangeX, ArrangeY};
4
5/// # Badge component
6/// Used alongside [crate::util::Color] to create Badge components
7///
8/// See [BadgeProps] for a listing of properties
9///
10/// ## Example
11/// ```rust
12/// use yew::prelude::*;
13/// use yew_bootstrap::component::Badge;
14/// use yew_bootstrap::util::Color;
15/// fn test() -> Html {
16///     html!{
17///         <Badge style={Color::Primary}>
18///             {"This is a primary badge!"}
19///         </Badge>
20///     }
21/// }
22/// ```
23pub struct Badge {}
24
25/// # Properties of [Badge]
26#[derive(Properties, Clone, PartialEq)]
27pub struct BadgeProps {
28    /// CSS class
29    #[prop_or_default]
30    pub class: String,
31
32    /// Inner components
33    #[prop_or_default]
34    pub children: Children,
35
36    /// Show badge more rounded as pill
37    #[prop_or_default]
38    pub pill: bool,
39
40    /// Show badge positioned
41    #[prop_or_default]
42    pub position: Option<(ArrangeX, ArrangeY)>,
43
44    /// Color style, default [Color::Primary]
45    #[prop_or(Color::Primary)]
46    pub style: Color,
47
48    /// Optional text placed before the children
49    #[prop_or_default]
50    pub text: String,
51}
52
53impl Component for Badge {
54    type Message = ();
55    type Properties = BadgeProps;
56
57    fn create(_ctx: &Context<Self>) -> Self {
58        Self {}
59    }
60
61    fn view(&self, ctx: &Context<Self>) -> Html {
62        let props = ctx.props();
63        let mut classes = Classes::new();
64        match &props.position {
65            Some(position) => {
66                classes.push("position-absolute".to_string());
67                classes.push(format!("{}", position.0));
68                classes.push(format!("{}", position.1));
69                classes.push("translate-middle".to_string());
70            }
71            None => {}
72        }
73        classes.push("badge");
74        if props.pill {
75            classes.push("rounded-pill");
76        }
77        classes.push(format!("bg-{}", props.style));
78        if [Color::Warning, Color::Info, Color::Light].contains(&props.style) {
79            classes.push("text-dark");
80        }
81        classes.push(props.class.clone());
82
83        html! {
84            <span
85                class={classes}
86            >
87                { &props.text }
88                { for props.children.iter() }
89            </span>
90        }
91    }
92}