Skip to main content

tablo_ui/components/composites/
badge.rs

1//! Tablo's badge: a short label set apart, `data-slot="badge"` and `data-tone` in its markup.
2
3use topcoat::{
4    Result,
5    context::Cx,
6    view::{Attributes, Child, Class, StaticClass, View, class, component, view},
7};
8
9/// How loud a badge is.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum BadgeVariant {
12    /// A tint of the primary color.
13    #[default]
14    Primary,
15    /// A gray tint.
16    Secondary,
17    /// A border and no fill.
18    Outline,
19    /// A tint of the destructive color.
20    Destructive,
21}
22
23impl BadgeVariant {
24    const fn name(self) -> &'static str {
25        match self {
26            Self::Primary => "primary",
27            Self::Secondary => "secondary",
28            Self::Outline => "outline",
29            Self::Destructive => "destructive",
30        }
31    }
32
33    fn classes(self) -> StaticClass {
34        match self {
35            Self::Primary => class!("bg-primary/10 text-primary ring-primary/25"),
36            Self::Secondary => class!("bg-muted text-muted-foreground ring-foreground/10"),
37            Self::Outline => class!("text-foreground ring-input"),
38            Self::Destructive => class!("bg-destructive/10 text-destructive ring-destructive/25"),
39        }
40    }
41}
42
43const BASE: StaticClass = class!(
44    "inline-flex w-fit shrink-0 items-center justify-center gap-1 rounded-sm px-1.5 py-0.5",
45    "text-xs font-medium whitespace-nowrap ring-1 ring-inset [&>svg]:size-3.5 [&>svg]:shrink-0",
46);
47
48/// A badge's classes, for an element that reads as one.
49#[must_use]
50pub fn badge_variants(variant: BadgeVariant) -> Class<(StaticClass, StaticClass)> {
51    class!(BASE, variant.classes())
52}
53
54/// A `<span>` badge.
55#[component]
56pub async fn badge(
57    cx: &Cx,
58    #[default] variant: BadgeVariant,
59    #[default] mut attrs: Attributes,
60    #[default] child: Child<'_>,
61) -> Result<impl View> {
62    Ok(view! {
63        <span
64            class=(class!(BASE, variant.classes(), attrs.remove("class")))
65            data-slot="badge"
66            data-tone=(variant.name())
67            (attrs)
68        >
69            (child)
70        </span>
71    })
72}