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
606
607
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/slot-text/slot-text.tsx` & `.module.css`
//!
//! P2 Component #30: `slot-text`
//!
//! - Every character is a slot-machine reel. Digits count through the wheel in the direction the
//!   number moved, letters shuffle through their alphabet, everything else simply slides.
//! - All reels start together but later ones run longer (`duration + order * stagger`), so they
//!   stop left to right with the same fast-out / soft-landing easing and never overshoot.
//! - Numbers align from the end so growing a number adds reels on the left while separators and
//!   suffixes keep their own reels.
//! - Local design: the per-glyph motion-blur is omitted (no shader sample for glyph velocity),
//!   reel width and add/remove width springs are dropped (width snaps to the sizer), and
//!   `aria-live` announcements become the element's accessible name.

use std::{cell::RefCell, collections::HashMap, collections::HashSet, rc::Rc};

use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
    App, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Styled,
    TestSupportExt as _, Window, div, prelude::*, px,
};

/// Cell pitch in em — keep in sync with [`CELL_HEIGHT_EM`] usage in the reel window.
const CELL: f32 = 1.6;
/// Window height in em (`line-height: 1.15`).
const LINE: f32 = 1.15;

const DIGITS: &str = "0123456789";
const LOWER: &str = "abcdefghijklmnopqrstuvwxyz";
const UPPER: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/// `cubic-bezier(.12, .8, .16, 1)` — fast out, long soft landing, never past the target.
const LANDING: (f64, f64, f64, f64) = (0.12, 0.8, 0.16, 1.0);

/// Which end reels are matched from when the text length changes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SlotAlign {
    Start,
    End,
}

/// Value shown by [`SlotText`]; numbers are formatted, strings render as they are.
#[derive(Clone, Debug, PartialEq)]
pub enum SlotValue {
    Text(SharedString),
    Number(f64),
}

impl From<f64> for SlotValue {
    fn from(value: f64) -> Self {
        Self::Number(value)
    }
}

impl From<&str> for SlotValue {
    fn from(value: &str) -> Self {
        Self::Text(value.into())
    }
}

impl From<String> for SlotValue {
    fn from(value: String) -> Self {
        Self::Text(value.into())
    }
}

impl From<SharedString> for SlotValue {
    fn from(value: SharedString) -> Self {
        Self::Text(value)
    }
}

fn alphabet_for(ch: char) -> Option<&'static str> {
    if DIGITS.contains(ch) {
        Some(DIGITS)
    } else if LOWER.contains(ch) {
        Some(LOWER)
    } else if UPPER.contains(ch) {
        Some(UPPER)
    } else {
        None
    }
}

/// Deterministic shuffle so the same change always spins the same letters.
fn seeded(seed: u32) -> impl FnMut() -> f32 {
    let mut state = if seed == 0 { 1 } else { seed };
    move || {
        state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
        state as f32 / 4_294_967_296.0
    }
}

fn digit_of(ch: char) -> Option<i32> {
    ch.to_digit(10).map(|d| d as i32)
}

/// The reel's cells, from what is visible now to the target.
pub fn strip_for(from: char, to: char, spins: usize, rising: bool, seed: u32) -> Vec<char> {
    if from == to {
        return vec![to];
    }
    let Some(set) = alphabet_for(to) else {
        return vec![from, to];
    };
    if set == DIGITS
        && let (Some(a), Some(b)) = (digit_of(from), digit_of(to))
    {
        let steps = spins as i32 * 10
            + if rising {
                (b - a + 10) % 10
            } else {
                (a - b + 10) % 10
            };
        return (0..=steps)
            .map(|i| {
                let value = if rising { a + i } else { a - i };
                char::from_digit(((value + 100) % 10) as u32, 10).unwrap_or('0')
            })
            .collect();
    }

    let mut random = seeded(seed);
    let fillers = (0..(spins * 5 + 2).max(2))
        .map(|_| {
            let chars: Vec<char> = set.chars().collect();
            let index = ((random() * chars.len() as f32) as usize).min(chars.len() - 1);
            chars[index]
        })
        .collect::<Vec<_>>();
    let mut strip = vec![from];
    strip.extend(fillers);
    strip.push(to);
    strip
}

/// Stable reel keys: a leading run of symbols is keyed from the start and never spins into a
/// digit; the rest is keyed from the aligned end so separators/suffixes keep their own reels.
pub fn reel_keys(chars: &[char], align: SlotAlign) -> Vec<String> {
    let from_end = align == SlotAlign::End;
    let prefix = if from_end {
        chars
            .iter()
            .position(|ch| ch.is_alphanumeric())
            .unwrap_or(chars.len())
    } else {
        0
    };
    chars
        .iter()
        .enumerate()
        .map(|(index, _)| {
            if index < prefix {
                format!("p{index}")
            } else if from_end {
                format!("e{}", chars.len() - 1 - index)
            } else {
                format!("s{index}")
            }
        })
        .collect()
}

fn landing_curve() -> CubicBezier {
    CubicBezier::new(LANDING.0, LANDING.1, LANDING.2, LANDING.3)
}

struct Reel {
    char: char,
    strip: Vec<char>,
    from: f32,
    to: f32,
    started_at: f64,
    duration: f64,
    done: bool,
}

struct SlotShared {
    reels: RefCell<HashMap<String, Reel>>,
    initial_keys: RefCell<Option<HashSet<String>>>,
    prev_value: RefCell<Option<f64>>,
    rising: RefCell<bool>,
}

impl Default for SlotShared {
    fn default() -> Self {
        Self {
            reels: RefCell::new(HashMap::new()),
            initial_keys: RefCell::new(None),
            prev_value: RefCell::new(None),
            rising: RefCell::new(true),
        }
    }
}

type FormatFn = Rc<dyn Fn(f64) -> String>;

/// Arc `SlotText` — text and numbers that spin into their new value like slot reels.
#[derive(IntoElement)]
pub struct SlotText {
    id: ElementId,
    value: SlotValue,
    format: Option<FormatFn>,
    duration: f64,
    stagger: f64,
    spins: usize,
    align: Option<SlotAlign>,
    announce: bool,
    text_size: Pixels,
}

impl SlotText {
    pub fn new(id: impl Into<ElementId>, value: impl Into<SlotValue>) -> Self {
        Self {
            id: id.into(),
            value: value.into(),
            format: None,
            duration: 0.9,
            stagger: 0.07,
            spins: 1,
            align: None,
            announce: false,
            text_size: Typography::TEXT_3XL,
        }
    }

    /// Formats a numeric value (defaults to `en-US` grouping).
    pub fn format(mut self, format: impl Fn(f64) -> String + 'static) -> Self {
        self.format = Some(Rc::new(format));
        self
    }

    /// Seconds the first reel spins.
    pub fn duration(mut self, duration: f64) -> Self {
        self.duration = duration.max(0.05);
        self
    }

    /// Seconds between reels stopping, left to right.
    pub fn stagger(mut self, stagger: f64) -> Self {
        self.stagger = stagger.max(0.0);
        self
    }

    /// Extra full turns a digit makes before landing.
    pub fn spins(mut self, spins: usize) -> Self {
        self.spins = spins;
        self
    }

    pub fn align(mut self, align: SlotAlign) -> Self {
        self.align = Some(align);
        self
    }

    pub fn announce(mut self, announce: bool) -> Self {
        self.announce = announce;
        self
    }

    pub fn text_size(mut self, size: Pixels) -> Self {
        self.text_size = size;
        self
    }

    fn text(&self) -> String {
        match &self.value {
            SlotValue::Text(text) => text.to_string(),
            SlotValue::Number(value) => match &self.format {
                Some(format) => format(*value),
                None => group_en_us(*value),
            },
        }
    }
}

/// Minimal `en-US` number formatting (`12,480`) matching Arc's default.
pub fn group_en_us(value: f64) -> String {
    let rounded = if value.fract() == 0.0 {
        format!("{}", value as i64)
    } else {
        format!("{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, Some(f)),
        None => (rest, None),
    };
    let mut grouped = String::new();
    for (index, ch) in integer.chars().enumerate() {
        if index > 0 && (integer.len() - index) % 3 == 0 {
            grouped.push(',');
        }
        grouped.push(ch);
    }
    match fraction {
        Some(fraction) => format!("{sign}{grouped}.{fraction}"),
        None => format!("{sign}{grouped}"),
    }
}

impl RenderOnce for SlotText {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let reduced = is_reduced_motion(cx);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-slot-text".into());
        let shared = window
            .use_keyed_state(state_id, cx, |_, _| Rc::new(SlotShared::default()))
            .read(cx)
            .clone();

        let text = self.text();
        let chars: Vec<char> = text.chars().collect();
        let default_align = match self.value {
            SlotValue::Number(_) => SlotAlign::End,
            SlotValue::Text(_) => SlotAlign::Start,
        };
        let align = self.align.unwrap_or(default_align);
        let keys = reel_keys(&chars, align);

        let mut initial = shared.initial_keys.borrow_mut();
        if initial.is_none() {
            *initial = Some(keys.iter().cloned().collect());
        }
        let initial_keys = initial.clone().unwrap_or_default();
        drop(initial);

        // Track direction for numeric values so digits roll the way the number moved.
        {
            let mut prev = shared.prev_value.borrow_mut();
            if let SlotValue::Number(value) = self.value {
                let rising = prev.map(|p| value >= p).unwrap_or(true);
                if prev.map(|p| (p - value).abs() > 1e-9).unwrap_or(true) {
                    *shared.rising.borrow_mut() = rising;
                }
                *prev = Some(value);
            }
        }
        let rising = *shared.rising.borrow();

        let now = motion_now(cx);
        let curve = landing_curve();
        let em = f32::from(self.text_size);
        let mut reels_row = div()
            .flex()
            .flex_row()
            .items_start()
            .h(px(LINE * em))
            .whitespace_nowrap();

        let mut reels_guard = shared.reels.borrow_mut();
        for (order, (ch, key)) in chars.iter().zip(keys.iter()).enumerate() {
            let entering = !initial_keys.contains(key);
            let time = self.duration + order as f64 * self.stagger;

            let reel = reels_guard.entry(key.clone()).or_insert_with(|| {
                let strip = if entering && !reduced {
                    strip_for(' ', *ch, self.spins, rising, (*ch as u32) + order as u32)
                } else {
                    vec![*ch]
                };
                let last = strip.len().saturating_sub(1) as f32;
                Reel {
                    char: *ch,
                    strip,
                    from: 0.0,
                    to: last,
                    started_at: now,
                    duration: time,
                    done: last <= 0.0,
                }
            });

            if reel.char != *ch {
                let current = reel_progress(reel, now, &curve);
                let index = (current.round() as i32)
                    .clamp(0, reel.strip.len().saturating_sub(1) as i32)
                    as usize;
                let visible = reel.strip[index].to_string();
                let visible = visible.chars().next().unwrap_or(*ch);
                let strip = if reduced {
                    vec![*ch]
                } else {
                    strip_for(
                        visible,
                        *ch,
                        self.spins,
                        rising,
                        (*ch as u32)
                            .wrapping_mul(31)
                            .wrapping_add((visible as u32).wrapping_mul(7))
                            .wrapping_add(order as u32)
                            .wrapping_add(reel.strip.len() as u32),
                    )
                };
                let last = strip.len().saturating_sub(1) as f32;
                reel.char = *ch;
                reel.strip = strip;
                reel.from = if reduced { 0.0 } else { current - index as f32 };
                reel.to = last;
                reel.started_at = now;
                reel.duration = time;
                reel.done = last <= 0.0;
            }

            let progress = reel_progress(reel, now, &curve);
            if !reel.done {
                window.request_animation_frame();
            }
            let strip = reel.strip.clone();

            let mut strip_column = div()
                .absolute()
                .left(px(0.08 * em))
                .right(px(0.08 * em))
                .top(px((0.22 - 0.225 - progress * CELL) * em))
                .flex()
                .flex_col()
                .items_center();
            for cell in &strip {
                strip_column = strip_column.child(
                    div()
                        .h(px(CELL * em))
                        .pt(px(0.225 * em))
                        .flex_none()
                        .justify_center()
                        .text_center()
                        .line_height(self.text_size * LINE)
                        .child(cell.to_string()),
                );
            }

            let window = div()
                .absolute()
                .top(px(-0.22 * em))
                .bottom(px(-0.22 * em))
                .left(px(-0.08 * em))
                .right(px(-0.08 * em))
                .overflow_hidden()
                .child(strip_column);

            let slot = div()
                .relative()
                .flex_none()
                .h(px(LINE * em))
                .child(div().opacity(0.0).child(ch.to_string()))
                .child(window);
            reels_row = reels_row.child(slot);
        }
        drop(reels_guard);

        let announce = self.announce;
        div()
            .id(self.id)
            .test_support()
            .self_start()
            .relative()
            .flex()
            .flex_row()
            .items_start()
            .text_color(colors.foreground)
            .text_size(self.text_size)
            .line_height(self.text_size * LINE)
            .aria_label(text.clone())
            .when(announce, |this| this.text_color(colors.foreground))
            .child(reels_row)
    }
}

/// Sampling helper kept as a free function so tests can drive it without a window.
fn reel_progress(reel: &Reel, now: f64, curve: &CubicBezier) -> f32 {
    if reel.duration <= 0.0 || reel.done {
        return reel.to;
    }
    let t = ((now - reel.started_at) / reel.duration).clamp(0.0, 1.0) as f32;
    let eased = curve.sample(t);
    reel.from + (reel.to - reel.from) * eased
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, Render, TestAppContext, div,
        test::{TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    #[test]
    fn digits_roll_one_step_and_wrap_upward() {
        assert_eq!(strip_for('4', '5', 0, true, 0), vec!['4', '5']);
        assert_eq!(strip_for('9', '0', 0, true, 0), vec!['9', '0']);
        assert_eq!(strip_for('5', '4', 0, false, 0), vec!['5', '4']);
        assert_eq!(
            strip_for('8', '6', 0, false, 0),
            vec!['8', '7', '6'],
            "decreasing walks backwards"
        );
        assert_eq!(
            strip_for('4', '5', 1, true, 0).len(),
            12,
            "ten extra turns plus one step"
        );
        assert_eq!(strip_for('a', 'a', 1, true, 0), vec!['a']);
    }

    #[test]
    fn letters_shuffle_through_their_own_alphabet_deterministically() {
        let first = strip_for('a', 'b', 1, true, 42);
        let second = strip_for('a', 'b', 1, true, 42);
        assert_eq!(first, second);
        assert_eq!(first.first(), Some(&'a'));
        assert_eq!(first.last(), Some(&'b'));
        assert!(first.len() >= 4);
        assert!(first.iter().all(|ch| ch.is_ascii_lowercase()));
    }

    #[test]
    fn keys_align_from_the_end_for_numbers() {
        let chars: Vec<char> = "¥999".chars().collect();
        assert_eq!(
            reel_keys(&chars, SlotAlign::End),
            vec!["p0", "e2", "e1", "e0"]
        );
        let grown: Vec<char> = "¥1,000".chars().collect();
        let keys = reel_keys(&grown, SlotAlign::End);
        assert_eq!(keys[0], "p0");
        assert_eq!(keys.last().map(String::as_str), Some("e0"));
        assert_eq!(keys.len(), grown.len());
        let plain: Vec<char> = "ab".chars().collect();
        assert_eq!(reel_keys(&plain, SlotAlign::Start), vec!["s0", "s1"]);
    }

    #[test]
    fn en_us_grouping_matches_arc_default() {
        assert_eq!(group_en_us(12_480.0), "12,480");
        assert_eq!(group_en_us(999.0), "999");
        assert_eq!(group_en_us(1_000_000.0), "1,000,000");
        assert_eq!(group_en_us(-2_500.5), "-2,500.5");
    }

    #[test]
    fn landing_curve_approaches_one_without_overshoot() {
        let curve = landing_curve();
        let mut last = 0.0;
        for step in 0..=20 {
            let value = curve.sample(step as f32 / 20.0);
            assert!(value >= last - 1e-4, "landing must be monotonic");
            assert!(value <= 1.0 + 1e-4);
            last = value;
        }
        assert!((curve.sample(1.0) - 1.0).abs() < 1e-3);
    }

    struct SlotHost {
        value: f64,
    }

    impl Render for SlotHost {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().p(px(24.0)).child(
                SlotText::new("price", self.value)
                    .align(SlotAlign::End)
                    .duration(0.2)
                    .stagger(0.01),
            )
        }
    }

    #[gpui_kit::test]
    fn slot_text_renders_and_restarts_reels_on_change(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(|_, _| SlotHost { value: 12.0 });
        let frames = Rc::new(Cell::new(0usize));
        cx.update(|window, cx| {
            for _ in 0..3 {
                window.render_frame(cx);
                frames.set(frames.get() + 1);
            }
            assert!(f32::from(window.find_by_label("12").bounds().size.width) > 0.0);
        });
        view.update(cx, |host, cx| {
            host.value = 9.0;
            cx.notify();
        });
        cx.update(|window, cx| {
            for _ in 0..10 {
                window.render_frame(cx);
            }
            assert!(f32::from(window.find_by_label("9").bounds().size.width) > 0.0);
        });
        assert!(frames.get() == 3);
    }
}