use crate::{
theme::color,
tokens::{self, ColorRole, TypeStyle},
typography::TypeStyled as _,
};
use gpui_kit::{
AnyElement, App, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window, div, px,
rems,
};
pub const COUNT_INSET: tokens::TokenLength = tokens::SPACING_02;
pub const COUNT_PADDING_X: tokens::TokenLength = tokens::SPACING_02;
pub const COUNT_HEIGHT_REM: f32 = 1.;
pub const COUNT_MIN_WIDTH_REM: f32 = 0.5;
pub const DOT: (f32, f32) = (6., 6.);
pub fn count_text(count: u32) -> SharedString {
if count > 999 {
"999+".into()
} else {
count.to_string().into()
}
}
pub fn colors() -> (gpui_kit::Hsla, gpui_kit::Hsla) {
(
color(ColorRole::SupportError),
color(ColorRole::TextOnColor),
)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BadgeIndicator {
Count(u32),
Dot,
}
impl BadgeIndicator {
pub fn element(self) -> AnyElement {
let (bg, fg) = colors();
match self {
Self::Count(n) => div()
.absolute()
.top(COUNT_INSET)
.right(COUNT_INSET)
.flex()
.items_center()
.h(rems(COUNT_HEIGHT_REM))
.min_w(rems(COUNT_MIN_WIDTH_REM))
.px(COUNT_PADDING_X)
.overflow_hidden()
.rounded_full()
.bg(bg)
.type_style(TypeStyle::HelperText01)
.text_color(fg)
.child(count_text(n))
.into_any_element(),
Self::Dot => div()
.absolute()
.top(px(DOT.0))
.right(px(DOT.0))
.size(px(DOT.1))
.rounded_full()
.bg(bg)
.into_any_element(),
}
}
}
#[derive(IntoElement)]
pub struct Badged {
button: AnyElement,
badge: Option<BadgeIndicator>,
}
impl Badged {
pub fn new(button: impl IntoElement, badge: Option<BadgeIndicator>) -> Self {
Self {
button: button.into_any_element(),
badge,
}
}
}
impl RenderOnce for Badged {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div()
.relative()
.flex()
.flex_none()
.child(self.button)
.children(self.badge.map(BadgeIndicator::element))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
#[test]
fn counts_cap_at_three_digits() {
assert_eq!(count_text(4), "4");
assert_eq!(count_text(999), "999");
assert_eq!(count_text(1200), "999+");
}
#[test]
fn geometry_follows_the_css() {
assert_eq!(COUNT_INSET.px_value(), 4.);
assert_eq!(COUNT_PADDING_X.px_value(), 4.);
assert_eq!(DOT, (6., 6.));
}
#[test]
fn badges_are_support_error() {
crate::theme::tests_set(CarbonTheme::White);
let (bg, fg) = colors();
assert_eq!(
bg,
crate::theme::color_in(CarbonTheme::White, ColorRole::SupportError)
);
assert_eq!(
fg,
crate::theme::color_in(CarbonTheme::White, ColorRole::TextOnColor)
);
}
}