1use std::{
17 cell::{Cell, RefCell},
18 collections::HashMap,
19 rc::Rc,
20};
21
22use arc_motion::{
23 BlurFallback, InViewConfig, InViewTracker, arc_spring, arc_spring_with_options,
24 is_reduced_motion, motion_now, spring::SpringOptions,
25};
26use arc_tokens::{ActiveArcTheme as _, ArcMotionTokens, SpringSpec, Typography};
27use gpui_kit::{
28 App, Bounds, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Styled,
29 TestSupportExt as _, Window, base::StyledExt as _, canvas, div, prelude::*, px,
30};
31
32#[derive(Clone, Debug, PartialEq)]
34pub enum CounterPart {
35 Digit {
36 key: String,
37 digit: u8,
38 order: usize,
40 },
41 Text {
42 key: String,
43 text: String,
44 },
45}
46
47pub fn wheel_offset(digit: u8, position: f32) -> f32 {
49 let digit = f32::from(digit);
50 ((((digit - position) % 10.0) + 15.0) % 10.0) - 5.0
51}
52
53pub fn glyph_alpha(offset: f32) -> f32 {
55 (1.0 - offset.abs()).clamp(0.0, 1.0)
56}
57
58pub fn wheel_step(current: u8, next: u8, direction: i32) -> f32 {
61 let current = i32::from(current);
62 let next = i32::from(next);
63 if direction < 0 {
64 -((current + 10 - next).rem_euclid(10)) as f32
65 } else {
66 (next + 10 - current).rem_euclid(10) as f32
67 }
68}
69
70pub fn counter_parts(value: f64, decimals: usize) -> Vec<CounterPart> {
73 let decimals = decimals.min(6);
74 let rounded = format!("{:.*}", decimals, value);
75 let (sign, rest) = match rounded.strip_prefix('-') {
76 Some(rest) => ("-", rest),
77 None => ("", rounded.as_str()),
78 };
79 let (integer, fraction) = match rest.split_once('.') {
80 Some((i, f)) => (i, f),
81 None => (rest, ""),
82 };
83
84 let digits: Vec<char> = integer.chars().collect();
85 let places = digits.len();
86 let mut parts = Vec::with_capacity(places + 4);
87 let mut order = 0usize;
88
89 if !sign.is_empty() {
90 parts.push(CounterPart::Text {
91 key: "sign".into(),
92 text: sign.into(),
93 });
94 }
95
96 for (index, ch) in digits.iter().enumerate() {
97 let place = places - index - 1;
98 if index > 0 && place % 3 == 2 {
99 parts.push(CounterPart::Text {
100 key: format!("g{place}"),
101 text: ",".into(),
102 });
103 }
104 parts.push(CounterPart::Digit {
105 key: format!("i{place}"),
106 digit: ch.to_digit(10).unwrap_or(0) as u8,
107 order,
108 });
109 order += 1;
110 }
111
112 if !fraction.is_empty() {
113 parts.push(CounterPart::Text {
114 key: "dot".into(),
115 text: ".".into(),
116 });
117 for (index, ch) in fraction.chars().enumerate() {
118 parts.push(CounterPart::Digit {
119 key: format!("f{index}"),
120 digit: ch.to_digit(10).unwrap_or(0) as u8,
121 order,
122 });
123 order += 1;
124 }
125 }
126
127 parts
128}
129
130pub fn counter_text(value: f64, decimals: usize, prefix: &str, suffix: &str) -> String {
132 let mut out = String::from(prefix);
133 for part in counter_parts(value, decimals) {
134 match part {
135 CounterPart::Digit { digit, .. } => out.push(char::from(b'0' + digit)),
136 CounterPart::Text { text, .. } => out.push_str(&text),
137 }
138 }
139 out.push_str(suffix);
140 out
141}
142
143#[derive(Clone, Copy, Debug)]
144struct Wheel {
145 digit: u8,
146 target: f32,
147 revealed: bool,
148 entering: bool,
149 start_at: Option<f64>,
150}
151
152struct CounterShared {
153 prev_value: Cell<Option<f64>>,
154 direction: Cell<i32>,
155 wheels: RefCell<HashMap<String, Wheel>>,
156 bootstrapped: Cell<bool>,
157 in_view: RefCell<InViewTracker>,
158 armed: Cell<bool>,
159}
160
161impl Default for CounterShared {
162 fn default() -> Self {
163 Self {
164 prev_value: Cell::new(None),
165 direction: Cell::new(1),
166 wheels: RefCell::new(HashMap::new()),
167 bootstrapped: Cell::new(false),
168 in_view: RefCell::new(InViewTracker::new(InViewConfig {
169 amount: 0.6,
170 once: true,
171 })),
172 armed: Cell::new(true),
173 }
174 }
175}
176
177#[derive(IntoElement)]
179pub struct AnimatedCounter {
180 id: ElementId,
181 value: f64,
182 label: Option<SharedString>,
183 prefix: SharedString,
184 suffix: SharedString,
185 decimals: usize,
186 animate_on_view: bool,
187 text_size: Pixels,
188}
189
190impl AnimatedCounter {
191 pub fn new(id: impl Into<ElementId>, value: f64) -> Self {
192 Self {
193 id: id.into(),
194 value,
195 label: None,
196 prefix: SharedString::default(),
197 suffix: SharedString::default(),
198 decimals: 0,
199 animate_on_view: false,
200 text_size: Typography::TEXT_3XL,
201 }
202 }
203
204 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
205 self.label = Some(label.into());
206 self
207 }
208
209 pub fn prefix(mut self, prefix: impl Into<SharedString>) -> Self {
210 self.prefix = prefix.into();
211 self
212 }
213
214 pub fn suffix(mut self, suffix: impl Into<SharedString>) -> Self {
215 self.suffix = suffix.into();
216 self
217 }
218
219 pub fn decimals(mut self, decimals: usize) -> Self {
220 self.decimals = decimals;
221 self
222 }
223
224 pub fn animate_on_view(mut self, animate_on_view: bool) -> Self {
226 self.animate_on_view = animate_on_view;
227 self
228 }
229
230 pub fn text_size(mut self, size: Pixels) -> Self {
232 self.text_size = size;
233 self
234 }
235}
236
237impl RenderOnce for AnimatedCounter {
238 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
239 let theme = cx.arc_theme().clone();
240 let colors = theme.colors;
241 let motion = theme.motion;
242 let reduced = is_reduced_motion(cx);
243
244 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-counter".into());
245 let shared = window
246 .use_keyed_state(state_id, cx, |_, _| Rc::new(CounterShared::default()))
247 .read(cx)
248 .clone();
249
250 if shared.prev_value.get().is_none() {
251 shared.prev_value.set(Some(self.value));
252 shared.armed.set(self.animate_on_view);
253 } else {
254 let prev = shared.prev_value.get().unwrap_or(self.value);
255 if (prev - self.value).abs() > 1e-9 {
256 shared.direction.set(if self.value > prev { 1 } else { -1 });
257 shared.prev_value.set(Some(self.value));
258 }
259 }
260
261 let armed = self.animate_on_view && shared.armed.get();
262 let now = motion_now(cx);
263 let em = f32::from(self.text_size);
264 let parts = counter_parts(self.value, self.decimals);
265 let reveal_spec = SpringSpec::visual(0.48, 0.0);
266 let stagger = motion.stagger.item.as_secs_f32() as f64;
267 let direction = shared.direction.get();
268 let bootstrapped = shared.bootstrapped.get();
269
270 let mut value_row = div().flex().flex_row().items_start().whitespace_nowrap();
271
272 {
273 let mut wheels = shared.wheels.borrow_mut();
274 for part in &parts {
275 match part {
276 CounterPart::Digit { key, digit, order } => {
277 let delay = (now + (*order as f64 * stagger).min(0.25)) as f64;
278 let entry = wheels.entry(key.clone()).or_insert_with(|| {
279 if armed {
280 Wheel {
281 digit: 0,
282 target: 0.0,
283 revealed: false,
284 entering: false,
285 start_at: Some(delay),
286 }
287 } else {
288 Wheel {
289 digit: *digit,
290 target: f32::from(*digit),
291 revealed: true,
292 entering: bootstrapped,
293 start_at: None,
294 }
295 }
296 });
297
298 if armed {
299 entry.target = 0.0;
300 entry.digit = 0;
301 entry.revealed = false;
302 entry.start_at = Some(delay);
303 } else {
304 if let Some(at) = entry.start_at {
305 if now < at {
306 entry.target = 0.0;
308 } else {
309 entry.start_at = None;
310 entry.revealed = false;
311 entry.digit = 0;
312 }
313 }
314 if entry.revealed {
315 if entry.digit != *digit {
316 entry.target += wheel_step(entry.digit, *digit, direction);
317 entry.digit = *digit;
318 }
319 } else if entry.start_at.is_none() {
320 entry.target += f32::from(*digit);
321 entry.digit = *digit;
322 entry.revealed = true;
323 }
324 }
325
326 let spec = if entry.revealed {
327 motion.spring.smooth
328 } else {
329 reveal_spec
330 };
331 let position = if reduced {
332 entry.target
333 } else {
334 arc_spring(
335 (self.id.clone(), format!("wheel-{key}")),
336 entry.target,
337 spec,
338 window,
339 cx,
340 )
341 };
342
343 let mut alpha = 1.0;
344 if entry.entering {
345 let fade = arc_spring_with_options(
346 (self.id.clone(), format!("enter-{key}")),
347 1.0,
348 SpringOptions::new(motion.spring.morph).with_initial_value(0.0),
349 window,
350 cx,
351 );
352 alpha = fade.value.clamp(0.0, 1.0);
353 if fade.settled {
354 entry.entering = false;
355 }
356 }
357
358 let mut column = div()
359 .relative()
360 .flex_none()
361 .overflow_hidden()
362 .opacity(alpha)
363 .child(
365 div()
366 .opacity(0.0)
367 .child(char::from(b'0' + *digit).to_string()),
368 );
369
370 for glyph in 0..10u8 {
371 let offset = wheel_offset(glyph, position);
372 let glyph_alpha = glyph_alpha(offset);
373 if glyph_alpha <= 0.001 {
374 continue;
375 }
376 let blur = BlurFallback::evaluate(
377 px((offset.abs()
378 * f32::from(ArcMotionTokens::DEFAULT.blur.subtle))
379 .max(0.0)),
380 reduced,
381 );
382 column = column.child(
383 div()
384 .absolute()
385 .left_0()
386 .right_0()
387 .top(px(offset * em))
388 .text_center()
389 .opacity(glyph_alpha * blur.opacity_multiplier)
390 .child(char::from(b'0' + glyph).to_string()),
391 );
392 }
393 value_row = value_row.child(column);
394 }
395 CounterPart::Text { key, text } => {
396 value_row = value_row.child(
397 div()
398 .id(ElementId::NamedChild(
399 self.id.clone().into(),
400 SharedString::from(format!("sym-{key}")),
401 ))
402 .flex_none()
403 .child(text.clone()),
404 );
405 }
406 }
407 }
408 }
409
410 shared.bootstrapped.set(true);
411
412 let label = self.label.map(|label| {
413 let rise = if reduced {
414 1.0
415 } else {
416 arc_spring_with_options(
417 (
418 self.id.clone(),
419 SharedString::from(format!("label-{label}")),
420 ),
421 1.0,
422 SpringOptions::new(motion.spring.smooth).with_initial_value(0.0),
423 window,
424 cx,
425 )
426 .value
427 .clamp(0.0, 1.0)
428 };
429 div()
430 .mb(arc_tokens::Spacing::S2)
431 .text_size(Typography::TEXT_XS)
432 .font_family(Typography::body_family())
433 .text_color(colors.text_muted)
434 .opacity(rise)
435 .mt(px((1.0 - rise) * 0.3 * f32::from(Typography::TEXT_XS)))
436 .child(label)
437 });
438
439 let accessible = counter_text(self.value, self.decimals, &self.prefix, &self.suffix);
440
441 let probe = self.animate_on_view.then(|| {
443 let shared = shared.clone();
444 canvas(
445 move |rect, window, _| {
446 let viewport =
447 Bounds::new(gpui_kit::point(px(0.0), px(0.0)), window.viewport_size());
448 let state = shared.in_view.borrow_mut().evaluate(rect, viewport);
449 let should_arm = !state.in_view;
450 if shared.armed.get() != should_arm {
453 shared.armed.set(should_arm);
454 window.request_animation_frame();
455 }
456 },
457 |_, _, _, _| {},
458 )
459 .absolute()
460 .inset_0()
461 });
462
463 div()
464 .id(self.id)
465 .test_support()
466 .self_start()
467 .relative()
468 .flex()
469 .flex_col()
470 .text_color(colors.foreground)
471 .text_size(self.text_size)
472 .font_family(Typography::display_family())
473 .font_medium()
474 .line_height(self.text_size * 1.1)
475 .aria_label(accessible)
476 .children(probe)
477 .children(label)
478 .child(value_row)
479 }
480}
481
482#[cfg(test)]
483mod tests {
484 use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
485 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
486 use gpui_kit::{
487 Context, Render, TestAppContext, div,
488 test::{TestQueryExt as _, TestWindowExt as _},
489 };
490
491 use super::*;
492
493 #[test]
494 fn wheel_offsets_wrap_like_an_odometer() {
495 assert_eq!(wheel_offset(3, 3.0), 0.0);
496 assert_eq!(wheel_offset(4, 3.0), 1.0);
497 assert_eq!(wheel_offset(2, 3.0), -1.0);
498 assert!((wheel_offset(0, 8.6) - 1.4).abs() < 1e-5);
500 assert!((wheel_offset(9, 0.4) + 1.4).abs() < 1e-5);
501 assert!(glyph_alpha(0.0) >= 0.999);
502 assert_eq!(glyph_alpha(1.0), 0.0);
503 assert_eq!(glyph_alpha(2.0), 0.0);
504 }
505
506 #[test]
507 fn counter_parts_group_thousands_and_keep_place_keys() {
508 let small = counter_parts(999.0, 0);
509 let big = counter_parts(1000.0, 0);
510 let digits = |parts: &[CounterPart]| {
511 parts
512 .iter()
513 .filter_map(|p| match p {
514 CounterPart::Digit { key, digit, .. } => Some((key.clone(), *digit)),
515 CounterPart::Text { .. } => None,
516 })
517 .collect::<Vec<_>>()
518 };
519 assert_eq!(
520 digits(&small),
521 vec![("i2".into(), 9), ("i1".into(), 9), ("i0".into(), 9)]
522 );
523 assert!(matches!(&big[0], CounterPart::Digit { digit: 1, .. }));
524 assert!(matches!(&big[1], CounterPart::Text { text, .. } if text == ","));
525 assert_eq!(
526 digits(&big),
527 vec![
528 ("i3".into(), 1),
529 ("i2".into(), 0),
530 ("i1".into(), 0),
531 ("i0".into(), 0)
532 ]
533 );
534 assert_eq!(counter_text(1234.5, 1, "$", "k"), "$1,234.5k");
535 assert_eq!(counter_text(-42.0, 0, "", "%"), "-42%");
536 }
537
538 struct CounterHost {
539 value: f64,
540 }
541
542 impl Render for CounterHost {
543 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
544 div().p(px(24.0)).child(
545 AnimatedCounter::new("counter", self.value)
546 .label("Revenue")
547 .prefix("$")
548 .suffix("k"),
549 )
550 }
551 }
552
553 #[gpui_kit::test]
554 fn animated_counter_renders_accessible_value_and_rolls(cx: &mut TestAppContext) {
555 cx.update(|cx| {
556 gpui_kit::init(cx);
557 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
558 });
559 let (view, cx) = cx.add_window_view(|_, _| CounterHost { value: 42.0 });
560 cx.update(|window, cx| {
561 window.render_frame(cx);
562 window.render_frame(cx);
563 assert!(f32::from(window.find_by_label("$42k").bounds().size.width) > 0.0);
564 });
565 view.update(cx, |host, cx| {
566 host.value = 43.0;
567 cx.notify();
568 });
569 cx.update(|window, cx| {
570 for _ in 0..8 {
571 window.render_frame(cx);
572 }
573 assert!(f32::from(window.find_by_label("$43k").bounds().size.width) > 0.0);
574 });
575 }
576
577 #[test]
578 fn wheel_roll_follows_critically_damped_0_40s_curve() {
579 let spec = ArcMotionTokens::DEFAULT.spring.smooth;
580 let solver = SpringSolver::new(spec, 0.0, 1.0, 0.0);
581 let omega = std::f64::consts::TAU / (0.40 * 1.2);
582 let mut actual = CurveTrace::new("animated_counter", "wheel");
583 let mut expected = CurveTrace::new("animated_counter", "wheel");
584 for frame in 0..=40 {
585 let t_ms = frame as f64 * 16.0;
586 let t = t_ms / 1000.0;
587 expected.push(t_ms, 1.0 - (-omega * t).exp() * (1.0 + omega * t));
588 actual.push(t_ms, f64::from(solver.sample(t).value));
589 }
590 let err = max_curve_error_pct(&actual, &expected);
591 assert!(err < 5.0, "wheel roll error {err:.3}% >= 5%");
592
593 assert_eq!(wheel_offset(3, 3.0), 0.0);
595 }
596
597 #[test]
598 fn wheel_step_walks_the_long_way_back_when_decreasing() {
599 assert_eq!(wheel_step(5, 6, 1), 1.0);
600 assert_eq!(wheel_step(9, 0, 1), 1.0);
601 assert_eq!(wheel_step(0, 9, -1), -1.0);
602 assert_eq!(wheel_step(5, 4, -1), -1.0);
603 assert_eq!(wheel_step(5, 5, 1), 0.0);
604 }
605}