use std::{cell::RefCell, rc::Rc};
use arc_motion::{BlurFallback, arc_spring, arc_transition, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, Radii, Typography, oklab_mix};
use gpui_kit::{
App, ElementId, Hsla, IntoElement, ParentElement, RenderOnce, SharedString, Styled,
TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, component::Icon,
div, prelude::*, px,
};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum BadgeTone {
#[default]
Neutral,
Info,
Success,
Warning,
Danger,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BadgeColor {
Teal,
Sky,
Orchid,
Violet,
Rose,
Amber,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum BadgeSize {
Sm,
#[default]
Md,
Lg,
}
#[derive(Clone)]
struct BadgeInternal {
last_label: SharedString,
generation: u64,
measured_width: Rc<RefCell<Option<f32>>>,
}
#[derive(IntoElement)]
pub struct Badge {
id: ElementId,
label: SharedString,
tone: BadgeTone,
color: Option<BadgeColor>,
size: BadgeSize,
icon: Option<IconName>,
dot: bool,
outline: bool,
pill: bool,
}
impl Badge {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
tone: BadgeTone::Neutral,
color: None,
size: BadgeSize::Md,
icon: None,
dot: false,
outline: false,
pill: false,
}
}
pub fn tone(mut self, tone: BadgeTone) -> Self {
self.tone = tone;
self
}
pub fn color(mut self, color: BadgeColor) -> Self {
self.color = Some(color);
self
}
pub fn size(mut self, size: BadgeSize) -> Self {
self.size = size;
self
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
pub fn dot(mut self, dot: bool) -> Self {
self.dot = dot;
self
}
pub fn outline(mut self, outline: bool) -> Self {
self.outline = outline;
self
}
pub fn pill(mut self, pill: bool) -> Self {
self.pill = pill;
self
}
}
impl RenderOnce for Badge {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let is_dark = theme.mode.is_dark();
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-badge-state".into());
let initial_label = self.label.clone();
let internal = window.use_keyed_state(state_id, cx, |_, _| BadgeInternal {
last_label: initial_label,
generation: 0,
measured_width: Rc::new(RefCell::new(None)),
});
let changed = internal.read(cx).last_label != self.label;
if changed {
internal.update(cx, |s, _| {
s.last_label = self.label.clone();
s.generation = s.generation.wrapping_add(1);
});
}
let snap = internal.read(cx).clone();
let base_tone = match self.color {
Some(BadgeColor::Teal) => colors.tone_teal,
Some(BadgeColor::Sky) => colors.tone_sky,
Some(BadgeColor::Orchid) => colors.tone_orchid,
Some(BadgeColor::Violet) => colors.tone_violet,
Some(BadgeColor::Rose) => colors.tone_rose,
Some(BadgeColor::Amber) => colors.tone_amber,
None => match self.tone {
BadgeTone::Neutral => colors.text_secondary,
BadgeTone::Info => colors.info,
BadgeTone::Success => colors.success,
BadgeTone::Warning => colors.warning,
BadgeTone::Danger => colors.danger,
},
};
let is_amber_like = matches!(self.color, Some(BadgeColor::Amber))
|| (self.color.is_none() && self.tone == BadgeTone::Warning);
let tint_weight = if is_dark { 0.12 } else { 0.10 };
let ink_weight = if is_dark {
0.94
} else if is_amber_like {
0.76
} else {
0.84
};
let bg = oklab_mix(base_tone, colors.surface, tint_weight);
let fg = oklab_mix(base_tone, colors.foreground, ink_weight);
let mark_color = oklab_mix(base_tone, colors.foreground, 0.88);
let border_color = if self.outline {
oklab_mix(base_tone, colors.border, if is_dark { 0.22 } else { 0.14 })
} else {
Hsla::transparent_black()
};
let (height, default_radius, pad, gap, icon_sz, dot_sz, font_sz) = match self.size {
BadgeSize::Sm => (20.0, 5.0, 8.0, 4.0, 12.0, 5.0, px(11.0)),
BadgeSize::Md => (24.0, 6.0, 10.0, 5.0, 14.0, 6.0, Typography::TEXT_XS),
BadgeSize::Lg => (28.0, 7.0, 12.0, 6.0, 16.0, 7.0, Typography::TEXT_SM),
};
let radius = if self.pill {
Radii::PILL
} else {
px(default_radius)
};
let pl = if self.icon.is_some() {
pad - 2.0
} else if self.dot {
pad - 1.0
} else {
pad
};
let enter_p = if snap.generation == 0 || reduced {
1.0
} else {
arc_transition(
(self.id.clone(), format!("enter-{}", snap.generation)),
1.0,
motion.duration.standard,
motion.ease.enter,
window,
cx,
)
};
let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - enter_p), reduced);
let measured_w = *snap.measured_width.borrow();
let animated_w = if let Some(target_w) = measured_w {
if reduced || snap.generation == 0 {
None
} else {
let cur_w = arc_spring(
(self.id.clone(), "badge-width"),
target_w,
motion.spring.morph,
window,
cx,
);
if (cur_w - target_w).abs() > 0.4 {
Some(cur_w)
} else {
None
}
}
} else {
None
};
let width_ref = snap.measured_width.clone();
let measure_canvas = {
let width_ref = width_ref.clone();
canvas(
move |rect, _, _| {
let w = f32::from(rect.size.width);
if w > 1.0 {
*width_ref.borrow_mut() = Some(w);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0()
};
let content_row = |enter: f32| {
let mut row = div()
.flex()
.flex_row()
.flex_none()
.items_center()
.gap(px(gap));
if self.icon.is_none() && self.dot {
row = row.child(
div()
.w(px(dot_sz))
.h(px(dot_sz))
.rounded(Radii::PILL)
.bg(mark_color)
.flex_none(),
);
}
if let Some(icon) = self.icon {
row = row.child(
Icon::new(icon)
.text_size(px(icon_sz))
.text_color(mark_color),
);
}
row.child(
div()
.whitespace_nowrap()
.opacity((enter * blur.opacity_multiplier).clamp(0.0, 1.0))
.child(self.label.clone()),
)
};
let sizer = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"sizer".into(),
))
.test_support()
.absolute()
.left(px(0.0))
.top(px(0.0))
.opacity(0.0)
.border_1()
.border_color(Hsla::transparent_black())
.pl(px(pl))
.pr(px(pad))
.py(px(0.0))
.text_size(font_sz)
.font_medium()
.child(measure_canvas)
.child(content_row(1.0));
div()
.id(self.id)
.test_support()
.relative()
.min_h(px(height))
.when_some(animated_w, |this, w| this.w(px(w.max(height))))
.pl(px(pl))
.pr(px(pad))
.rounded(radius)
.border_1()
.border_color(border_color)
.bg(bg)
.overflow_hidden()
.flex()
.flex_row()
.items_center()
.gap(px(gap))
.text_size(font_sz)
.font_medium()
.text_color(fg)
.child(sizer)
.child(content_row(enter_p))
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
use gpui_kit::{Context, Render, TestAppContext, div, px, test::TestWindowExt as _};
use super::*;
struct BadgeHost {
label: SharedString,
tone: BadgeTone,
}
impl Render for BadgeHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.w(px(360.0))
.p(Spacing::S4)
.flex()
.gap(Spacing::S2)
.child(
Badge::new("status-badge", self.label.clone())
.tone(self.tone)
.dot(true)
.outline(true),
)
.child(
Badge::new("method-badge", "POST")
.color(BadgeColor::Violet)
.size(BadgeSize::Sm)
.pill(true),
)
}
}
#[gpui_kit::test]
fn badge_grows_to_fit_a_longer_label_without_clipping(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (view, cx) = cx.add_window_view(|_, _| BadgeHost {
label: "已部署".into(),
tone: BadgeTone::Success,
});
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
});
view.update(cx, |host, cx| {
host.label = "构建中 · 82%".into();
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
});
for _ in 0..4 {
cx.executor()
.advance_clock(std::time::Duration::from_millis(200));
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
});
}
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
let root: std::sync::Arc<ElementId> = ElementId::from("status-badge").into();
let sizer = window.find(ElementId::NamedChild(root.clone(), "sizer".into()));
let badge = window.find(ElementId::from("status-badge"));
let sizer_w = f32::from(sizer.bounds().size.width);
let badge_w = f32::from(badge.bounds().size.width);
assert!(sizer_w > 0.0, "sizer must report the natural label width");
assert!(
badge_w + 1.0 >= sizer_w,
"badge {badge_w} must grow to the natural content width {sizer_w}"
);
});
}
#[gpui_kit::test]
fn badge_renders_tones_colors_and_label_morph_without_panicking(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (view, cx) = cx.add_window_view(|_, _| BadgeHost {
label: "Queued".into(),
tone: BadgeTone::Warning,
});
cx.update(|window, cx| {
window.render_frame(cx);
view.update(cx, |v, cx| {
v.label = "Deployed".into();
v.tone = BadgeTone::Success;
cx.notify();
});
window.render_frame(cx);
});
}
}