Skip to main content

fc_ui/capabilities/effects/
number_ticker.rs

1use gpui::{prelude::FluentBuilder as _, *};
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::easings;
7
8#[derive(IntoElement)]
9pub struct NumberTicker {
10    id: ElementId,
11    base: Div,
12    value: i64,
13    separator: Option<char>,
14    prefix: Option<SharedString>,
15    suffix: Option<SharedString>,
16    duration: Duration,
17}
18
19impl NumberTicker {
20    pub fn new(id: impl Into<ElementId>, value: i64) -> Self {
21        Self {
22            id: id.into(),
23            base: div(),
24            value,
25            separator: None,
26            prefix: None,
27            suffix: None,
28            duration: Duration::from_millis(600),
29        }
30    }
31
32    pub fn separator(mut self, sep: char) -> Self {
33        self.separator = Some(sep);
34        self
35    }
36
37    pub fn prefix(mut self, prefix: impl Into<SharedString>) -> Self {
38        self.prefix = Some(prefix.into());
39        self
40    }
41
42    pub fn suffix(mut self, suffix: impl Into<SharedString>) -> Self {
43        self.suffix = Some(suffix.into());
44        self
45    }
46
47    pub fn duration(mut self, duration: Duration) -> Self {
48        self.duration = duration;
49        self
50    }
51}
52
53impl Styled for NumberTicker {
54    fn style(&mut self) -> &mut StyleRefinement {
55        self.base.style()
56    }
57}
58
59fn format_with_separator(value: i64, separator: Option<char>) -> Vec<DigitOrSeparator> {
60    let is_negative = value < 0;
61    let abs_str = value.unsigned_abs().to_string();
62    let mut result = Vec::new();
63
64    if is_negative {
65        result.push(DigitOrSeparator::Separator('-'));
66    }
67
68    let digits: Vec<u8> = abs_str.bytes().map(|b| b - b'0').collect();
69    let len = digits.len();
70
71    for (i, &digit) in digits.iter().enumerate() {
72        result.push(DigitOrSeparator::Digit(digit));
73        if let Some(sep) = separator {
74            let remaining = len - 1 - i;
75            if remaining > 0 && remaining.is_multiple_of(3) {
76                result.push(DigitOrSeparator::Separator(sep));
77            }
78        }
79    }
80
81    result
82}
83
84#[derive(Clone, Copy)]
85enum DigitOrSeparator {
86    Digit(u8),
87    Separator(char),
88}
89
90impl RenderOnce for NumberTicker {
91    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
92        let theme = use_theme(cx);
93        let chars = format_with_separator(self.value, self.separator);
94        let duration = self.duration;
95        let digit_height = px(24.0);
96        let column_height = digit_height * 10.0;
97
98        self.base
99            .id(self.id)
100            .flex()
101            .flex_row()
102            .items_center()
103            .text_color(theme.tokens.foreground)
104            .font_family(mono_font_family())
105            .when_some(self.prefix.clone(), |el, prefix| {
106                el.child(div().child(prefix))
107            })
108            .children(chars.iter().enumerate().map(move |(pos, item)| {
109                match *item {
110                    DigitOrSeparator::Separator(ch) => div()
111                        .flex_shrink_0()
112                        .child(SharedString::from(String::from(ch)))
113                        .into_any_element(),
114                    DigitOrSeparator::Digit(digit) => {
115                        let target_offset = -(digit_height * digit as f32);
116
117                        div()
118                            .flex_shrink_0()
119                            .h(digit_height)
120                            .overflow_hidden()
121                            .child(
122                                div()
123                                    .id(("digit-col", pos as u32))
124                                    .flex()
125                                    .flex_col()
126                                    .h(column_height)
127                                    .children((0..10u8).map(|d| {
128                                        div()
129                                            .h(digit_height)
130                                            .flex()
131                                            .items_center()
132                                            .justify_center()
133                                            .child(SharedString::from(d.to_string()))
134                                    }))
135                                    .with_animation(
136                                        ("digit-roll", pos as u32),
137                                        Animation::new(duration)
138                                            .with_easing(easings::ease_out_cubic),
139                                        move |el, delta| {
140                                            let offset = target_offset * delta;
141                                            el.top(offset)
142                                        },
143                                    ),
144                            )
145                            .into_any_element()
146                    }
147                }
148            }))
149            .when_some(self.suffix, |el, suffix| el.child(div().child(suffix)))
150    }
151}