use std::{cell::RefCell, rc::Rc};
use arc_motion::{
BlurFallback, CubicBezier, arc_spring_with_options, is_reduced_motion, motion_now,
spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, ElementId, Hsla, IntoElement, ParentElement, RenderOnce, Role, SharedString,
Styled, Window, div, prelude::*, px,
};
use crate::text::animated_counter::AnimatedCounter;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricTrend {
Up,
Down,
Neutral,
}
pub fn metric_card_trend(change: &str) -> MetricTrend {
let trimmed = change.trim();
if trimmed.starts_with('+') {
MetricTrend::Up
} else if trimmed.starts_with('-') || trimmed.starts_with('−') {
MetricTrend::Down
} else {
MetricTrend::Neutral
}
}
pub fn metric_card_extract_number(text: &str) -> Option<f64> {
let cleaned = text.replace(',', "").replace('−', "-");
let bytes = cleaned.as_bytes();
let mut i = 0;
while i < bytes.len() {
let ch = bytes[i] as char;
let is_sign = (ch == '-' || ch == '+')
&& i + 1 < bytes.len()
&& (bytes[i + 1] as char).is_ascii_digit();
if is_sign || ch.is_ascii_digit() {
let start = i;
if ch == '-' || ch == '+' {
i += 1;
}
let mut seen_dot = false;
while i < bytes.len() {
let c = bytes[i] as char;
if c.is_ascii_digit() {
i += 1;
} else if c == '.' && !seen_dot {
seen_dot = true;
i += 1;
} else {
break;
}
}
if let Ok(v) = cleaned[start..i].parse::<f64>() {
return Some(v);
}
}
i += 1;
}
None
}
pub fn metric_card_swap_direction(prev: &str, next: &str) -> i8 {
match (
metric_card_extract_number(prev),
metric_card_extract_number(next),
) {
(Some(a), Some(b)) if b < a => -1,
_ => 1,
}
}
pub fn metric_card_swap_sample(
elapsed_secs: f64,
direction: i8,
reduced: bool,
) -> (f32, f32, f32, f32) {
let dir = direction as f32;
if reduced {
let t = (elapsed_secs / 0.12).clamp(0.0, 1.0) as f32;
return ((1.0 - t).clamp(0.0, 1.0), 0.0, t, 0.0);
}
let out_t = (elapsed_secs / 0.16).clamp(0.0, 1.0) as f32;
let out_eased = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(out_t);
let out_blur = BlurFallback::evaluate(px(out_eased * 2.0), false);
let old_alpha = ((1.0 - out_eased) * out_blur.opacity_multiplier).clamp(0.0, 1.0);
let old_y = -4.2 * dir * out_eased;
let in_t = (elapsed_secs / 0.24).clamp(0.0, 1.0) as f32;
let in_eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(in_t);
let in_blur = BlurFallback::evaluate(px((1.0 - in_eased) * 4.0), false);
let new_alpha = (in_eased * in_blur.opacity_multiplier).clamp(0.0, 1.0);
let new_y = 4.2 * dir * (1.0 - in_eased);
(old_alpha, old_y, new_alpha, new_y)
}
#[derive(Clone)]
struct SwapTrack {
current: SharedString,
previous: Option<SharedString>,
direction: i8,
changed_at: f64,
}
impl SwapTrack {
fn new(initial: SharedString, now: f64) -> Self {
Self {
current: initial,
previous: None,
direction: 1,
changed_at: now - 1.0,
}
}
fn sync(&mut self, next: &SharedString, now: f64) -> bool {
if &self.current != next {
self.direction = metric_card_swap_direction(self.current.as_ref(), next.as_ref());
self.previous = Some(self.current.clone());
self.current = next.clone();
self.changed_at = now;
}
let elapsed = (now - self.changed_at).max(0.0);
if self.previous.is_some() && elapsed >= 0.28 {
self.previous = None;
}
self.previous.is_some()
}
}
#[derive(Clone)]
struct MetricCardInternal {
label: SwapTrack,
change: SwapTrack,
context: SwapTrack,
measured_pill_w: Rc<RefCell<f32>>,
}
#[derive(IntoElement)]
pub struct MetricCard {
id: ElementId,
label: SharedString,
value: f64,
decimals: usize,
prefix: Option<SharedString>,
suffix: Option<SharedString>,
context: SharedString,
change: Option<SharedString>,
}
impl MetricCard {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
value: f64,
context: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
value,
decimals: 0,
prefix: None,
suffix: None,
context: context.into(),
change: None,
}
}
pub fn decimals(mut self, decimals: usize) -> Self {
self.decimals = decimals.min(6);
self
}
pub fn prefix(mut self, prefix: impl Into<SharedString>) -> Self {
self.prefix = Some(prefix.into());
self
}
pub fn suffix(mut self, suffix: impl Into<SharedString>) -> Self {
self.suffix = Some(suffix.into());
self
}
pub fn change(mut self, change: impl Into<SharedString>) -> Self {
self.change = Some(change.into());
self
}
}
fn render_swapped_text(
track: &SwapTrack,
now: f64,
color: Hsla,
reduced: bool,
nowrap: bool,
) -> AnyElement {
let elapsed = (now - track.changed_at).max(0.0);
let (old_alpha, old_y, new_alpha, new_y) = if track.previous.is_some() {
metric_card_swap_sample(elapsed, track.direction, reduced)
} else {
(0.0, 0.0, 1.0, 0.0)
};
let outgoing = track.previous.as_ref().and_then(|prev| {
if old_alpha <= 0.01 {
None
} else {
let mut el = div()
.absolute()
.left_0()
.top(px(old_y))
.opacity(old_alpha)
.text_size(Typography::TEXT_SM)
.text_color(color)
.child(prev.clone());
if nowrap {
el = el.whitespace_nowrap();
}
Some(el)
}
});
let mut incoming = div()
.relative()
.top(px(new_y))
.opacity(new_alpha)
.text_size(Typography::TEXT_SM)
.text_color(color)
.child(track.current.clone());
if nowrap {
incoming = incoming.whitespace_nowrap();
}
div()
.relative()
.min_w(px(0.0))
.when_some(outgoing, |el, out| el.child(out))
.child(incoming)
.into_any_element()
}
fn estimate_pill_width(text: &str) -> f32 {
let text_w: f32 = text
.chars()
.map(|c| if c.is_ascii() { 7.8 } else { 13.5 })
.sum();
(text_w + 18.0).max(40.0)
}
impl RenderOnce for MetricCard {
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 now = motion_now(cx);
let initial_change = self.change.clone().unwrap_or_default();
let state_cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("mc-state")),
cx,
|_, _| {
Rc::new(RefCell::new(MetricCardInternal {
label: SwapTrack::new(self.label.clone(), now),
change: SwapTrack::new(initial_change.clone(), now),
context: SwapTrack::new(self.context.clone(), now),
measured_pill_w: Rc::new(RefCell::new(estimate_pill_width(
initial_change.as_ref(),
))),
}))
},
)
.read(cx)
.clone();
let (label_track, change_track, context_track, pill_w_ref, animating) = {
let mut st = state_cell.borrow_mut();
let a1 = st.label.sync(&self.label, now);
let a2 = st.change.sync(&initial_change, now);
let a3 = st.context.sync(&self.context, now);
(
st.label.clone(),
st.change.clone(),
st.context.clone(),
st.measured_pill_w.clone(),
a1 || a2 || a3,
)
};
if animating && !reduced {
window.request_animation_frame();
}
let change_pill: Option<AnyElement> = self.change.as_ref().map(|chg| {
let trend = metric_card_trend(chg.as_ref());
let (pill_bg, pill_border, pill_fg) = match trend {
MetricTrend::Up => (
oklab_mix(colors.success, colors.surface, 0.11),
gpui_kit::transparent_black(),
colors.success,
),
MetricTrend::Down => (
oklab_mix(colors.danger, colors.surface, 0.11),
gpui_kit::transparent_black(),
colors.danger,
),
MetricTrend::Neutral => (colors.surface, colors.border, colors.text_secondary),
};
let target_w = {
let est = estimate_pill_width(chg.as_ref());
let m = *pill_w_ref.borrow();
if (m - est).abs() < 40.0 && m > 24.0 {
m
} else {
est
}
};
let animated_w = if reduced {
target_w
} else {
arc_spring_with_options(
ElementId::NamedChild(
self.id.clone().into(),
SharedString::from("change-pill-w"),
),
target_w,
SpringOptions::new(motion.spring.morph).with_initial_value(target_w),
window,
cx,
)
.value
.max(36.0)
};
let measure_w = pill_w_ref.clone();
div()
.flex_shrink_0()
.w(px(animated_w))
.px(px(8.0))
.py(px(3.0))
.rounded(Radii::PILL)
.border_1()
.border_color(pill_border)
.bg(pill_bg)
.overflow_hidden()
.flex()
.items_center()
.justify_center()
.child(render_swapped_text(
&change_track,
now,
pill_fg,
reduced,
true,
))
.on_children_prepainted(move |bounds, window, _| {
if let Some(b) = bounds.first() {
let w = f32::from(b.size.width) + 18.0;
let prev = *measure_w.borrow();
if w > 24.0 && (prev - w).abs() > 1.0 {
*measure_w.borrow_mut() = w;
window.request_animation_frame();
}
}
})
.into_any_element()
});
let mut counter = AnimatedCounter::new(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("counter")),
self.value,
)
.decimals(self.decimals)
.animate_on_view(true);
if let Some(prefix) = self.prefix {
counter = counter.prefix(prefix);
}
if let Some(suffix) = self.suffix {
counter = counter.suffix(suffix);
}
div()
.id(self.id)
.role(Role::Region)
.w_full()
.min_w(px(0.0))
.p(Spacing::S6)
.rounded(Radii::SURFACE)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.shadow(Shadows::resting(theme.mode))
.flex()
.flex_col()
.child(
div()
.w_full()
.mb(Spacing::S6)
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(Spacing::S3)
.child(div().flex_1().min_w(px(0.0)).child(render_swapped_text(
&label_track,
now,
colors.text_secondary,
reduced,
false,
)))
.when_some(change_pill, |el, pill| el.child(pill)),
)
.child(counter)
.child(div().w_full().mt(Spacing::S4).child(render_swapped_text(
&context_track,
now,
colors.text_muted,
reduced,
false,
)))
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn metric_card_trend_and_number_direction_detection() {
assert_eq!(metric_card_trend("+14.2%"), MetricTrend::Up);
assert_eq!(metric_card_trend("-3.8%"), MetricTrend::Down);
assert_eq!(metric_card_trend("−1.2%"), MetricTrend::Down);
assert_eq!(metric_card_trend("flat"), MetricTrend::Neutral);
assert_eq!(metric_card_extract_number("+1,240.5 ms"), Some(1240.5));
assert_eq!(metric_card_extract_number("−12%"), Some(-12.0));
assert_eq!(metric_card_swap_direction("+8.2%", "+12.4%"), 1);
assert_eq!(metric_card_swap_direction("+12.4%", "+8.2%"), -1);
}
}