use std::{
cell::{Cell, RefCell},
collections::HashMap,
rc::Rc,
};
use arc_motion::{
BlurFallback, InViewConfig, InViewTracker, arc_spring, arc_spring_with_options,
is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, ArcMotionTokens, SpringSpec, Typography};
use gpui_kit::{
App, Bounds, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Styled,
TestSupportExt as _, Window, base::StyledExt as _, canvas, div, prelude::*, px,
};
#[derive(Clone, Debug, PartialEq)]
pub enum CounterPart {
Digit {
key: String,
digit: u8,
order: usize,
},
Text {
key: String,
text: String,
},
}
pub fn wheel_offset(digit: u8, position: f32) -> f32 {
let digit = f32::from(digit);
((((digit - position) % 10.0) + 15.0) % 10.0) - 5.0
}
pub fn glyph_alpha(offset: f32) -> f32 {
(1.0 - offset.abs()).clamp(0.0, 1.0)
}
pub fn wheel_step(current: u8, next: u8, direction: i32) -> f32 {
let current = i32::from(current);
let next = i32::from(next);
if direction < 0 {
-((current + 10 - next).rem_euclid(10)) as f32
} else {
(next + 10 - current).rem_euclid(10) as f32
}
}
pub fn counter_parts(value: f64, decimals: usize) -> Vec<CounterPart> {
let decimals = decimals.min(6);
let rounded = format!("{:.*}", decimals, value);
let (sign, rest) = match rounded.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", rounded.as_str()),
};
let (integer, fraction) = match rest.split_once('.') {
Some((i, f)) => (i, f),
None => (rest, ""),
};
let digits: Vec<char> = integer.chars().collect();
let places = digits.len();
let mut parts = Vec::with_capacity(places + 4);
let mut order = 0usize;
if !sign.is_empty() {
parts.push(CounterPart::Text {
key: "sign".into(),
text: sign.into(),
});
}
for (index, ch) in digits.iter().enumerate() {
let place = places - index - 1;
if index > 0 && place % 3 == 2 {
parts.push(CounterPart::Text {
key: format!("g{place}"),
text: ",".into(),
});
}
parts.push(CounterPart::Digit {
key: format!("i{place}"),
digit: ch.to_digit(10).unwrap_or(0) as u8,
order,
});
order += 1;
}
if !fraction.is_empty() {
parts.push(CounterPart::Text {
key: "dot".into(),
text: ".".into(),
});
for (index, ch) in fraction.chars().enumerate() {
parts.push(CounterPart::Digit {
key: format!("f{index}"),
digit: ch.to_digit(10).unwrap_or(0) as u8,
order,
});
order += 1;
}
}
parts
}
pub fn counter_text(value: f64, decimals: usize, prefix: &str, suffix: &str) -> String {
let mut out = String::from(prefix);
for part in counter_parts(value, decimals) {
match part {
CounterPart::Digit { digit, .. } => out.push(char::from(b'0' + digit)),
CounterPart::Text { text, .. } => out.push_str(&text),
}
}
out.push_str(suffix);
out
}
#[derive(Clone, Copy, Debug)]
struct Wheel {
digit: u8,
target: f32,
revealed: bool,
entering: bool,
start_at: Option<f64>,
}
struct CounterShared {
prev_value: Cell<Option<f64>>,
direction: Cell<i32>,
wheels: RefCell<HashMap<String, Wheel>>,
bootstrapped: Cell<bool>,
in_view: RefCell<InViewTracker>,
armed: Cell<bool>,
}
impl Default for CounterShared {
fn default() -> Self {
Self {
prev_value: Cell::new(None),
direction: Cell::new(1),
wheels: RefCell::new(HashMap::new()),
bootstrapped: Cell::new(false),
in_view: RefCell::new(InViewTracker::new(InViewConfig {
amount: 0.6,
once: true,
})),
armed: Cell::new(true),
}
}
}
#[derive(IntoElement)]
pub struct AnimatedCounter {
id: ElementId,
value: f64,
label: Option<SharedString>,
prefix: SharedString,
suffix: SharedString,
decimals: usize,
animate_on_view: bool,
text_size: Pixels,
}
impl AnimatedCounter {
pub fn new(id: impl Into<ElementId>, value: f64) -> Self {
Self {
id: id.into(),
value,
label: None,
prefix: SharedString::default(),
suffix: SharedString::default(),
decimals: 0,
animate_on_view: false,
text_size: Typography::TEXT_3XL,
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn prefix(mut self, prefix: impl Into<SharedString>) -> Self {
self.prefix = prefix.into();
self
}
pub fn suffix(mut self, suffix: impl Into<SharedString>) -> Self {
self.suffix = suffix.into();
self
}
pub fn decimals(mut self, decimals: usize) -> Self {
self.decimals = decimals;
self
}
pub fn animate_on_view(mut self, animate_on_view: bool) -> Self {
self.animate_on_view = animate_on_view;
self
}
pub fn text_size(mut self, size: Pixels) -> Self {
self.text_size = size;
self
}
}
impl RenderOnce for AnimatedCounter {
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 state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-counter".into());
let shared = window
.use_keyed_state(state_id, cx, |_, _| Rc::new(CounterShared::default()))
.read(cx)
.clone();
if shared.prev_value.get().is_none() {
shared.prev_value.set(Some(self.value));
shared.armed.set(self.animate_on_view);
} else {
let prev = shared.prev_value.get().unwrap_or(self.value);
if (prev - self.value).abs() > 1e-9 {
shared.direction.set(if self.value > prev { 1 } else { -1 });
shared.prev_value.set(Some(self.value));
}
}
let armed = self.animate_on_view && shared.armed.get();
let now = motion_now(cx);
let em = f32::from(self.text_size);
let parts = counter_parts(self.value, self.decimals);
let reveal_spec = SpringSpec::visual(0.48, 0.0);
let stagger = motion.stagger.item.as_secs_f32() as f64;
let direction = shared.direction.get();
let bootstrapped = shared.bootstrapped.get();
let mut value_row = div().flex().flex_row().items_start().whitespace_nowrap();
{
let mut wheels = shared.wheels.borrow_mut();
for part in &parts {
match part {
CounterPart::Digit { key, digit, order } => {
let delay = (now + (*order as f64 * stagger).min(0.25)) as f64;
let entry = wheels.entry(key.clone()).or_insert_with(|| {
if armed {
Wheel {
digit: 0,
target: 0.0,
revealed: false,
entering: false,
start_at: Some(delay),
}
} else {
Wheel {
digit: *digit,
target: f32::from(*digit),
revealed: true,
entering: bootstrapped,
start_at: None,
}
}
});
if armed {
entry.target = 0.0;
entry.digit = 0;
entry.revealed = false;
entry.start_at = Some(delay);
} else {
if let Some(at) = entry.start_at {
if now < at {
entry.target = 0.0;
} else {
entry.start_at = None;
entry.revealed = false;
entry.digit = 0;
}
}
if entry.revealed {
if entry.digit != *digit {
entry.target += wheel_step(entry.digit, *digit, direction);
entry.digit = *digit;
}
} else if entry.start_at.is_none() {
entry.target += f32::from(*digit);
entry.digit = *digit;
entry.revealed = true;
}
}
let spec = if entry.revealed {
motion.spring.smooth
} else {
reveal_spec
};
let position = if reduced {
entry.target
} else {
arc_spring(
(self.id.clone(), format!("wheel-{key}")),
entry.target,
spec,
window,
cx,
)
};
let mut alpha = 1.0;
if entry.entering {
let fade = arc_spring_with_options(
(self.id.clone(), format!("enter-{key}")),
1.0,
SpringOptions::new(motion.spring.morph).with_initial_value(0.0),
window,
cx,
);
alpha = fade.value.clamp(0.0, 1.0);
if fade.settled {
entry.entering = false;
}
}
let mut column = div()
.relative()
.flex_none()
.overflow_hidden()
.opacity(alpha)
.child(
div()
.opacity(0.0)
.child(char::from(b'0' + *digit).to_string()),
);
for glyph in 0..10u8 {
let offset = wheel_offset(glyph, position);
let glyph_alpha = glyph_alpha(offset);
if glyph_alpha <= 0.001 {
continue;
}
let blur = BlurFallback::evaluate(
px((offset.abs()
* f32::from(ArcMotionTokens::DEFAULT.blur.subtle))
.max(0.0)),
reduced,
);
column = column.child(
div()
.absolute()
.left_0()
.right_0()
.top(px(offset * em))
.text_center()
.opacity(glyph_alpha * blur.opacity_multiplier)
.child(char::from(b'0' + glyph).to_string()),
);
}
value_row = value_row.child(column);
}
CounterPart::Text { key, text } => {
value_row = value_row.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("sym-{key}")),
))
.flex_none()
.child(text.clone()),
);
}
}
}
}
shared.bootstrapped.set(true);
let label = self.label.map(|label| {
let rise = if reduced {
1.0
} else {
arc_spring_with_options(
(
self.id.clone(),
SharedString::from(format!("label-{label}")),
),
1.0,
SpringOptions::new(motion.spring.smooth).with_initial_value(0.0),
window,
cx,
)
.value
.clamp(0.0, 1.0)
};
div()
.mb(arc_tokens::Spacing::S2)
.text_size(Typography::TEXT_XS)
.font_family(Typography::body_family())
.text_color(colors.text_muted)
.opacity(rise)
.mt(px((1.0 - rise) * 0.3 * f32::from(Typography::TEXT_XS)))
.child(label)
});
let accessible = counter_text(self.value, self.decimals, &self.prefix, &self.suffix);
let probe = self.animate_on_view.then(|| {
let shared = shared.clone();
canvas(
move |rect, window, _| {
let viewport =
Bounds::new(gpui_kit::point(px(0.0), px(0.0)), window.viewport_size());
let state = shared.in_view.borrow_mut().evaluate(rect, viewport);
let should_arm = !state.in_view;
if shared.armed.get() != should_arm {
shared.armed.set(should_arm);
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0()
});
div()
.id(self.id)
.test_support()
.self_start()
.relative()
.flex()
.flex_col()
.text_color(colors.foreground)
.text_size(self.text_size)
.font_family(Typography::display_family())
.font_medium()
.line_height(self.text_size * 1.1)
.aria_label(accessible)
.children(probe)
.children(label)
.child(value_row)
}
}
#[cfg(test)]
mod tests {
use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, TestAppContext, div,
test::{TestQueryExt as _, TestWindowExt as _},
};
use super::*;
#[test]
fn wheel_offsets_wrap_like_an_odometer() {
assert_eq!(wheel_offset(3, 3.0), 0.0);
assert_eq!(wheel_offset(4, 3.0), 1.0);
assert_eq!(wheel_offset(2, 3.0), -1.0);
assert!((wheel_offset(0, 8.6) - 1.4).abs() < 1e-5);
assert!((wheel_offset(9, 0.4) + 1.4).abs() < 1e-5);
assert!(glyph_alpha(0.0) >= 0.999);
assert_eq!(glyph_alpha(1.0), 0.0);
assert_eq!(glyph_alpha(2.0), 0.0);
}
#[test]
fn counter_parts_group_thousands_and_keep_place_keys() {
let small = counter_parts(999.0, 0);
let big = counter_parts(1000.0, 0);
let digits = |parts: &[CounterPart]| {
parts
.iter()
.filter_map(|p| match p {
CounterPart::Digit { key, digit, .. } => Some((key.clone(), *digit)),
CounterPart::Text { .. } => None,
})
.collect::<Vec<_>>()
};
assert_eq!(
digits(&small),
vec![("i2".into(), 9), ("i1".into(), 9), ("i0".into(), 9)]
);
assert!(matches!(&big[0], CounterPart::Digit { digit: 1, .. }));
assert!(matches!(&big[1], CounterPart::Text { text, .. } if text == ","));
assert_eq!(
digits(&big),
vec![
("i3".into(), 1),
("i2".into(), 0),
("i1".into(), 0),
("i0".into(), 0)
]
);
assert_eq!(counter_text(1234.5, 1, "$", "k"), "$1,234.5k");
assert_eq!(counter_text(-42.0, 0, "", "%"), "-42%");
}
struct CounterHost {
value: f64,
}
impl Render for CounterHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().p(px(24.0)).child(
AnimatedCounter::new("counter", self.value)
.label("Revenue")
.prefix("$")
.suffix("k"),
)
}
}
#[gpui_kit::test]
fn animated_counter_renders_accessible_value_and_rolls(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(|_, _| CounterHost { value: 42.0 });
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
assert!(f32::from(window.find_by_label("$42k").bounds().size.width) > 0.0);
});
view.update(cx, |host, cx| {
host.value = 43.0;
cx.notify();
});
cx.update(|window, cx| {
for _ in 0..8 {
window.render_frame(cx);
}
assert!(f32::from(window.find_by_label("$43k").bounds().size.width) > 0.0);
});
}
#[test]
fn wheel_roll_follows_critically_damped_0_40s_curve() {
let spec = ArcMotionTokens::DEFAULT.spring.smooth;
let solver = SpringSolver::new(spec, 0.0, 1.0, 0.0);
let omega = std::f64::consts::TAU / (0.40 * 1.2);
let mut actual = CurveTrace::new("animated_counter", "wheel");
let mut expected = CurveTrace::new("animated_counter", "wheel");
for frame in 0..=40 {
let t_ms = frame as f64 * 16.0;
let t = t_ms / 1000.0;
expected.push(t_ms, 1.0 - (-omega * t).exp() * (1.0 + omega * t));
actual.push(t_ms, f64::from(solver.sample(t).value));
}
let err = max_curve_error_pct(&actual, &expected);
assert!(err < 5.0, "wheel roll error {err:.3}% >= 5%");
assert_eq!(wheel_offset(3, 3.0), 0.0);
}
#[test]
fn wheel_step_walks_the_long_way_back_when_decreasing() {
assert_eq!(wheel_step(5, 6, 1), 1.0);
assert_eq!(wheel_step(9, 0, 1), 1.0);
assert_eq!(wheel_step(0, 9, -1), -1.0);
assert_eq!(wheel_step(5, 4, -1), -1.0);
assert_eq!(wheel_step(5, 5, 1), 0.0);
}
}