arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/animated-counter/animated-counter.tsx` & `.module.css`
//!
//! P2 Component #29: `animated-counter`
//!
//! - Every digit is a clipped 10-glyph wheel. A single position value per place decides each
//!   glyph's offset, so 9 → 0 wraps like an odometer and the whole number always turns in the
//!   direction it moved.
//! - The first roll ever (or the roll when the counter scrolls into view with `animate_on_view`)
//!   uses Motion's `visualDuration = 0.48s, bounce = 0` spring; later changes use `spring.smooth`.
//! - Glyphs fade and micro-blur by `|offset|`; columns added later fade in over `spring.morph`.
//! - Local design: no Intl locale formatting (Arc's default `en-US` grouping `.` / `,` only), no
//!   per-digit blur shader (unified `BlurFallback` opacity attenuation), no `mask-image` feather
//!   padding on the wheel window, and no width-collapse of removed columns.

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,
};

/// One formatted fragment: a wheel column or fixed punctuation.
#[derive(Clone, Debug, PartialEq)]
pub enum CounterPart {
    Digit {
        key: String,
        digit: u8,
        /// Left-to-right index used for the reveal stagger.
        order: usize,
    },
    Text {
        key: String,
        text: String,
    },
}

/// Signed octal-style wheel offset for `digit` at `position` (`-5.0..=5.0`, wrapping at 10).
pub fn wheel_offset(digit: u8, position: f32) -> f32 {
    let digit = f32::from(digit);
    ((((digit - position) % 10.0) + 15.0) % 10.0) - 5.0
}

/// Glyph opacity from its wheel offset (`1` in the window, `0` one full step away).
pub fn glyph_alpha(offset: f32) -> f32 {
    (1.0 - offset.abs()).clamp(0.0, 1.0)
}

/// Target delta for one wheel step; negative direction walks the long way back so the
/// odometer keeps turning the way the whole number moved.
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
    }
}

/// Splits `value` into digit columns keyed by place value so growth keeps columns stable
/// (`999` → `1,000` keeps `i0` on the ones place).
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
}

/// Plain rendered text (visually hidden equivalent / accessibility name).
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),
        }
    }
}

/// Arc `AnimatedCounter` — odometer-style digits that roll toward the new value.
#[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
    }

    /// Rolls every digit up from zero the first time the counter enters the viewport.
    pub fn animate_on_view(mut self, animate_on_view: bool) -> Self {
        self.animate_on_view = animate_on_view;
        self
    }

    /// Overrides the display size (`--text-3xl` = 36px by default).
    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 {
                                    // Stagger hold: the wheel has not been released yet.
                                    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)
                            // Hidden sizer keeps the column one digit wide (tabular numerals).
                            .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);

        // Viewport probe: `animateOnView` arms the wheels until the counter is 60% visible.
        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;
                    // A flip on the first measurement also needs a follow-up frame, otherwise the
                    // wheels stay at zero until something else repaints the window.
                    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);
        // 9 -> 0 rolling up sits just above the window, 0 -> 9 just below.
        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%");

        // Reduced motion: the wheel lands on its target immediately.
        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);
    }
}