Skip to main content

fc_ui/capabilities/effects/
animated_counter.rs

1use gpui::*;
2use std::time::Duration;
3
4use crate::capabilities::foundation::fonts::mono_font_family;
5use crate::capabilities::foundation::theme::use_theme;
6use crate::capabilities::motion::animations::{durations, easings};
7
8pub struct AnimatedCounterState {
9    display_value: f64,
10    target_value: f64,
11    version: usize,
12    duration: Duration,
13}
14
15impl AnimatedCounterState {
16    pub fn new(initial: f64) -> Self {
17        Self {
18            display_value: initial,
19            target_value: initial,
20            version: 0,
21            duration: durations::NORMAL,
22        }
23    }
24
25    pub fn with_duration(mut self, duration: Duration) -> Self {
26        self.duration = duration;
27        self
28    }
29
30    pub fn set_value(&mut self, value: f64, cx: &mut Context<Self>) {
31        if (self.target_value - value).abs() < f64::EPSILON {
32            return;
33        }
34
35        let from = self.display_value;
36        let target = value;
37        self.target_value = value;
38        self.version += 1;
39        let version = self.version;
40
41        let frame_count = (self.duration.as_millis() as u32 / 16).clamp(1, 30);
42        let frame_dur = self.duration / frame_count;
43
44        cx.spawn(async move |this, cx| {
45            for frame in 1..=frame_count {
46                cx.background_executor().timer(frame_dur).await;
47                let t = frame as f32 / frame_count as f32;
48                let eased = easings::ease_out_cubic(t);
49                let interpolated = from + (target - from) * eased as f64;
50                let is_last = frame == frame_count;
51
52                _ = this.update(cx, |state, cx| {
53                    if state.version != version {
54                        return;
55                    }
56                    state.display_value = if is_last {
57                        state.target_value
58                    } else {
59                        interpolated
60                    };
61                    cx.notify();
62                });
63            }
64        })
65        .detach();
66
67        cx.notify();
68    }
69
70    pub fn display_value(&self) -> f64 {
71        self.display_value
72    }
73
74    pub fn target_value(&self) -> f64 {
75        self.target_value
76    }
77}
78
79#[derive(IntoElement)]
80pub struct AnimatedCounter {
81    base: Div,
82    state: Entity<AnimatedCounterState>,
83    decimal_places: usize,
84    prefix: String,
85    suffix: String,
86}
87
88impl AnimatedCounter {
89    pub fn new(_id: impl Into<ElementId>, state: Entity<AnimatedCounterState>) -> Self {
90        Self {
91            base: div(),
92            state,
93            decimal_places: 0,
94            prefix: String::new(),
95            suffix: String::new(),
96        }
97    }
98
99    pub fn decimal_places(mut self, places: usize) -> Self {
100        self.decimal_places = places;
101        self
102    }
103
104    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
105        self.prefix = prefix.into();
106        self
107    }
108
109    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
110        self.suffix = suffix.into();
111        self
112    }
113}
114
115impl RenderOnce for AnimatedCounter {
116    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
117        let theme = use_theme(cx);
118        let state = self.state.read(cx);
119        let value = state.display_value();
120
121        let number_str = if self.decimal_places > 0 {
122            format!("{:.prec$}", value, prec = self.decimal_places)
123        } else {
124            format!("{}", value.round() as i64)
125        };
126
127        let formatted = format!("{}{}{}", self.prefix, number_str, self.suffix);
128
129        self.base
130            .text_color(theme.tokens.foreground)
131            .font_family(mono_font_family())
132            .child(formatted)
133    }
134}
135
136impl Styled for AnimatedCounter {
137    fn style(&mut self) -> &mut StyleRefinement {
138        self.base.style()
139    }
140}
141
142impl InteractiveElement for AnimatedCounter {
143    fn interactivity(&mut self) -> &mut Interactivity {
144        self.base.interactivity()
145    }
146}
147
148impl StatefulInteractiveElement for AnimatedCounter {}
149
150impl ParentElement for AnimatedCounter {
151    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
152        self.base.extend(elements)
153    }
154}