1use std::{cell::RefCell, rc::Rc};
15
16use arc_motion::{BlurFallback, arc_spring, arc_transition, is_reduced_motion};
17use arc_tokens::{ActiveArcTheme as _, Radii, Typography, oklab_mix};
18use gpui_kit::{
19 App, ElementId, Hsla, IntoElement, ParentElement, RenderOnce, SharedString, Styled,
20 TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, component::Icon,
21 div, prelude::*, px,
22};
23
24#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub enum BadgeTone {
27 #[default]
28 Neutral,
29 Info,
30 Success,
31 Warning,
32 Danger,
33}
34
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37pub enum BadgeColor {
38 Teal,
39 Sky,
40 Orchid,
41 Violet,
42 Rose,
43 Amber,
44}
45
46#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
48pub enum BadgeSize {
49 Sm,
50 #[default]
51 Md,
52 Lg,
53}
54
55#[derive(Clone)]
56struct BadgeInternal {
57 last_label: SharedString,
58 generation: u64,
59 measured_width: Rc<RefCell<Option<f32>>>,
60}
61
62#[derive(IntoElement)]
64pub struct Badge {
65 id: ElementId,
66 label: SharedString,
67 tone: BadgeTone,
68 color: Option<BadgeColor>,
69 size: BadgeSize,
70 icon: Option<IconName>,
71 dot: bool,
72 outline: bool,
73 pill: bool,
74}
75
76impl Badge {
77 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
78 Self {
79 id: id.into(),
80 label: label.into(),
81 tone: BadgeTone::Neutral,
82 color: None,
83 size: BadgeSize::Md,
84 icon: None,
85 dot: false,
86 outline: false,
87 pill: false,
88 }
89 }
90
91 pub fn tone(mut self, tone: BadgeTone) -> Self {
92 self.tone = tone;
93 self
94 }
95
96 pub fn color(mut self, color: BadgeColor) -> Self {
97 self.color = Some(color);
98 self
99 }
100
101 pub fn size(mut self, size: BadgeSize) -> Self {
102 self.size = size;
103 self
104 }
105
106 pub fn icon(mut self, icon: IconName) -> Self {
107 self.icon = Some(icon);
108 self
109 }
110
111 pub fn dot(mut self, dot: bool) -> Self {
112 self.dot = dot;
113 self
114 }
115
116 pub fn outline(mut self, outline: bool) -> Self {
117 self.outline = outline;
118 self
119 }
120
121 pub fn pill(mut self, pill: bool) -> Self {
122 self.pill = pill;
123 self
124 }
125}
126
127impl RenderOnce for Badge {
128 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
129 let theme = cx.arc_theme().clone();
130 let colors = theme.colors;
131 let motion = theme.motion;
132 let reduced = is_reduced_motion(cx);
133 let is_dark = theme.mode.is_dark();
134
135 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-badge-state".into());
136 let initial_label = self.label.clone();
137 let internal = window.use_keyed_state(state_id, cx, |_, _| BadgeInternal {
138 last_label: initial_label,
139 generation: 0,
140 measured_width: Rc::new(RefCell::new(None)),
141 });
142
143 let changed = internal.read(cx).last_label != self.label;
144 if changed {
145 internal.update(cx, |s, _| {
146 s.last_label = self.label.clone();
147 s.generation = s.generation.wrapping_add(1);
148 });
149 }
150 let snap = internal.read(cx).clone();
151
152 let base_tone = match self.color {
153 Some(BadgeColor::Teal) => colors.tone_teal,
154 Some(BadgeColor::Sky) => colors.tone_sky,
155 Some(BadgeColor::Orchid) => colors.tone_orchid,
156 Some(BadgeColor::Violet) => colors.tone_violet,
157 Some(BadgeColor::Rose) => colors.tone_rose,
158 Some(BadgeColor::Amber) => colors.tone_amber,
159 None => match self.tone {
160 BadgeTone::Neutral => colors.text_secondary,
161 BadgeTone::Info => colors.info,
162 BadgeTone::Success => colors.success,
163 BadgeTone::Warning => colors.warning,
164 BadgeTone::Danger => colors.danger,
165 },
166 };
167
168 let is_amber_like = matches!(self.color, Some(BadgeColor::Amber))
169 || (self.color.is_none() && self.tone == BadgeTone::Warning);
170 let tint_weight = if is_dark { 0.12 } else { 0.10 };
171 let ink_weight = if is_dark {
172 0.94
173 } else if is_amber_like {
174 0.76
175 } else {
176 0.84
177 };
178
179 let bg = oklab_mix(base_tone, colors.surface, tint_weight);
180 let fg = oklab_mix(base_tone, colors.foreground, ink_weight);
181 let mark_color = oklab_mix(base_tone, colors.foreground, 0.88);
182 let border_color = if self.outline {
183 oklab_mix(base_tone, colors.border, if is_dark { 0.22 } else { 0.14 })
184 } else {
185 Hsla::transparent_black()
186 };
187
188 let (height, default_radius, pad, gap, icon_sz, dot_sz, font_sz) = match self.size {
189 BadgeSize::Sm => (20.0, 5.0, 8.0, 4.0, 12.0, 5.0, px(11.0)),
190 BadgeSize::Md => (24.0, 6.0, 10.0, 5.0, 14.0, 6.0, Typography::TEXT_XS),
191 BadgeSize::Lg => (28.0, 7.0, 12.0, 6.0, 16.0, 7.0, Typography::TEXT_SM),
192 };
193 let radius = if self.pill {
194 Radii::PILL
195 } else {
196 px(default_radius)
197 };
198 let pl = if self.icon.is_some() {
199 pad - 2.0
200 } else if self.dot {
201 pad - 1.0
202 } else {
203 pad
204 };
205
206 let enter_p = if snap.generation == 0 || reduced {
207 1.0
208 } else {
209 arc_transition(
210 (self.id.clone(), format!("enter-{}", snap.generation)),
211 1.0,
212 motion.duration.standard,
213 motion.ease.enter,
214 window,
215 cx,
216 )
217 };
218 let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - enter_p), reduced);
219
220 let measured_w = *snap.measured_width.borrow();
221 let animated_w = if let Some(target_w) = measured_w {
222 if reduced || snap.generation == 0 {
223 None
224 } else {
225 let cur_w = arc_spring(
226 (self.id.clone(), "badge-width"),
227 target_w,
228 motion.spring.morph,
229 window,
230 cx,
231 );
232 if (cur_w - target_w).abs() > 0.4 {
233 Some(cur_w)
234 } else {
235 None
236 }
237 }
238 } else {
239 None
240 };
241
242 let width_ref = snap.measured_width.clone();
246 let measure_canvas = {
247 let width_ref = width_ref.clone();
248 canvas(
249 move |rect, _, _| {
250 let w = f32::from(rect.size.width);
251 if w > 1.0 {
252 *width_ref.borrow_mut() = Some(w);
253 }
254 },
255 |_, _, _, _| {},
256 )
257 .absolute()
258 .inset_0()
259 };
260
261 let content_row = |enter: f32| {
262 let mut row = div()
263 .flex()
264 .flex_row()
265 .flex_none()
266 .items_center()
267 .gap(px(gap));
268 if self.icon.is_none() && self.dot {
269 row = row.child(
270 div()
271 .w(px(dot_sz))
272 .h(px(dot_sz))
273 .rounded(Radii::PILL)
274 .bg(mark_color)
275 .flex_none(),
276 );
277 }
278 if let Some(icon) = self.icon {
279 row = row.child(
280 Icon::new(icon)
281 .text_size(px(icon_sz))
282 .text_color(mark_color),
283 );
284 }
285 row.child(
286 div()
287 .whitespace_nowrap()
288 .opacity((enter * blur.opacity_multiplier).clamp(0.0, 1.0))
289 .child(self.label.clone()),
290 )
291 };
292
293 let sizer = div()
296 .id(ElementId::NamedChild(
297 self.id.clone().into(),
298 "sizer".into(),
299 ))
300 .test_support()
301 .absolute()
302 .left(px(0.0))
303 .top(px(0.0))
304 .opacity(0.0)
305 .border_1()
306 .border_color(Hsla::transparent_black())
307 .pl(px(pl))
308 .pr(px(pad))
309 .py(px(0.0))
310 .text_size(font_sz)
311 .font_medium()
312 .child(measure_canvas)
313 .child(content_row(1.0));
314
315 div()
316 .id(self.id)
317 .test_support()
318 .relative()
319 .min_h(px(height))
320 .when_some(animated_w, |this, w| this.w(px(w.max(height))))
321 .pl(px(pl))
322 .pr(px(pad))
323 .rounded(radius)
324 .border_1()
325 .border_color(border_color)
326 .bg(bg)
327 .overflow_hidden()
328 .flex()
329 .flex_row()
330 .items_center()
331 .gap(px(gap))
332 .text_size(font_sz)
333 .font_medium()
334 .text_color(fg)
335 .child(sizer)
336 .child(content_row(enter_p))
337 }
338}
339
340#[cfg(test)]
341mod tests {
342 use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
343 use gpui_kit::{Context, Render, TestAppContext, div, px, test::TestWindowExt as _};
344
345 use super::*;
346
347 struct BadgeHost {
348 label: SharedString,
349 tone: BadgeTone,
350 }
351
352 impl Render for BadgeHost {
353 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
354 div()
355 .w(px(360.0))
356 .p(Spacing::S4)
357 .flex()
358 .gap(Spacing::S2)
359 .child(
360 Badge::new("status-badge", self.label.clone())
361 .tone(self.tone)
362 .dot(true)
363 .outline(true),
364 )
365 .child(
366 Badge::new("method-badge", "POST")
367 .color(BadgeColor::Violet)
368 .size(BadgeSize::Sm)
369 .pill(true),
370 )
371 }
372 }
373
374 #[gpui_kit::test]
375 fn badge_grows_to_fit_a_longer_label_without_clipping(cx: &mut TestAppContext) {
376 cx.update(|cx| {
377 gpui_kit::init(cx);
378 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
379 });
380 let (view, cx) = cx.add_window_view(|_, _| BadgeHost {
381 label: "已部署".into(),
382 tone: BadgeTone::Success,
383 });
384 cx.update(|window, cx| {
385 window.render_frame(cx);
386 window.render_frame(cx);
387 });
388 view.update(cx, |host, cx| {
389 host.label = "构建中 · 82%".into();
390 cx.notify();
391 });
392 cx.update(|window, cx| {
395 window.render_frame(cx);
396 window.render_frame(cx);
397 });
398 for _ in 0..4 {
399 cx.executor()
400 .advance_clock(std::time::Duration::from_millis(200));
401 cx.update(|window, cx| {
402 window.render_frame(cx);
403 window.render_frame(cx);
404 });
405 }
406 cx.update(|window, cx| {
407 window.render_frame(cx);
408 window.render_frame(cx);
409 let root: std::sync::Arc<ElementId> = ElementId::from("status-badge").into();
410 let sizer = window.find(ElementId::NamedChild(root.clone(), "sizer".into()));
411 let badge = window.find(ElementId::from("status-badge"));
412 let sizer_w = f32::from(sizer.bounds().size.width);
413 let badge_w = f32::from(badge.bounds().size.width);
414 assert!(sizer_w > 0.0, "sizer must report the natural label width");
415 assert!(
416 badge_w + 1.0 >= sizer_w,
417 "badge {badge_w} must grow to the natural content width {sizer_w}"
418 );
419 });
420 }
421
422 #[gpui_kit::test]
423 fn badge_renders_tones_colors_and_label_morph_without_panicking(cx: &mut TestAppContext) {
424 cx.update(|cx| {
425 gpui_kit::init(cx);
426 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
427 });
428 let (view, cx) = cx.add_window_view(|_, _| BadgeHost {
429 label: "Queued".into(),
430 tone: BadgeTone::Warning,
431 });
432
433 cx.update(|window, cx| {
434 window.render_frame(cx);
435 view.update(cx, |v, cx| {
436 v.label = "Deployed".into();
437 v.tone = BadgeTone::Success;
438 cx.notify();
439 });
440 window.render_frame(cx);
441 });
442 }
443}