Skip to main content

arc_ui/text/
slot_text.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/slot-text/slot-text.tsx` & `.module.css`
3//!
4//! P2 Component #30: `slot-text`
5//!
6//! - Every character is a slot-machine reel. Digits count through the wheel in the direction the
7//!   number moved, letters shuffle through their alphabet, everything else simply slides.
8//! - All reels start together but later ones run longer (`duration + order * stagger`), so they
9//!   stop left to right with the same fast-out / soft-landing easing and never overshoot.
10//! - Numbers align from the end so growing a number adds reels on the left while separators and
11//!   suffixes keep their own reels.
12//! - Local design: the per-glyph motion-blur is omitted (no shader sample for glyph velocity),
13//!   reel width and add/remove width springs are dropped (width snaps to the sizer), and
14//!   `aria-live` announcements become the element's accessible name.
15
16use std::{cell::RefCell, collections::HashMap, collections::HashSet, rc::Rc};
17
18use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
19use arc_tokens::{ActiveArcTheme as _, Typography};
20use gpui_kit::{
21    App, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Styled,
22    TestSupportExt as _, Window, div, prelude::*, px,
23};
24
25/// Cell pitch in em — keep in sync with [`CELL_HEIGHT_EM`] usage in the reel window.
26const CELL: f32 = 1.6;
27/// Window height in em (`line-height: 1.15`).
28const LINE: f32 = 1.15;
29
30const DIGITS: &str = "0123456789";
31const LOWER: &str = "abcdefghijklmnopqrstuvwxyz";
32const UPPER: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
33
34/// `cubic-bezier(.12, .8, .16, 1)` — fast out, long soft landing, never past the target.
35const LANDING: (f64, f64, f64, f64) = (0.12, 0.8, 0.16, 1.0);
36
37/// Which end reels are matched from when the text length changes.
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub enum SlotAlign {
40    Start,
41    End,
42}
43
44/// Value shown by [`SlotText`]; numbers are formatted, strings render as they are.
45#[derive(Clone, Debug, PartialEq)]
46pub enum SlotValue {
47    Text(SharedString),
48    Number(f64),
49}
50
51impl From<f64> for SlotValue {
52    fn from(value: f64) -> Self {
53        Self::Number(value)
54    }
55}
56
57impl From<&str> for SlotValue {
58    fn from(value: &str) -> Self {
59        Self::Text(value.into())
60    }
61}
62
63impl From<String> for SlotValue {
64    fn from(value: String) -> Self {
65        Self::Text(value.into())
66    }
67}
68
69impl From<SharedString> for SlotValue {
70    fn from(value: SharedString) -> Self {
71        Self::Text(value)
72    }
73}
74
75fn alphabet_for(ch: char) -> Option<&'static str> {
76    if DIGITS.contains(ch) {
77        Some(DIGITS)
78    } else if LOWER.contains(ch) {
79        Some(LOWER)
80    } else if UPPER.contains(ch) {
81        Some(UPPER)
82    } else {
83        None
84    }
85}
86
87/// Deterministic shuffle so the same change always spins the same letters.
88fn seeded(seed: u32) -> impl FnMut() -> f32 {
89    let mut state = if seed == 0 { 1 } else { seed };
90    move || {
91        state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
92        state as f32 / 4_294_967_296.0
93    }
94}
95
96fn digit_of(ch: char) -> Option<i32> {
97    ch.to_digit(10).map(|d| d as i32)
98}
99
100/// The reel's cells, from what is visible now to the target.
101pub fn strip_for(from: char, to: char, spins: usize, rising: bool, seed: u32) -> Vec<char> {
102    if from == to {
103        return vec![to];
104    }
105    let Some(set) = alphabet_for(to) else {
106        return vec![from, to];
107    };
108    if set == DIGITS
109        && let (Some(a), Some(b)) = (digit_of(from), digit_of(to))
110    {
111        let steps = spins as i32 * 10
112            + if rising {
113                (b - a + 10) % 10
114            } else {
115                (a - b + 10) % 10
116            };
117        return (0..=steps)
118            .map(|i| {
119                let value = if rising { a + i } else { a - i };
120                char::from_digit(((value + 100) % 10) as u32, 10).unwrap_or('0')
121            })
122            .collect();
123    }
124
125    let mut random = seeded(seed);
126    let fillers = (0..(spins * 5 + 2).max(2))
127        .map(|_| {
128            let chars: Vec<char> = set.chars().collect();
129            let index = ((random() * chars.len() as f32) as usize).min(chars.len() - 1);
130            chars[index]
131        })
132        .collect::<Vec<_>>();
133    let mut strip = vec![from];
134    strip.extend(fillers);
135    strip.push(to);
136    strip
137}
138
139/// Stable reel keys: a leading run of symbols is keyed from the start and never spins into a
140/// digit; the rest is keyed from the aligned end so separators/suffixes keep their own reels.
141pub fn reel_keys(chars: &[char], align: SlotAlign) -> Vec<String> {
142    let from_end = align == SlotAlign::End;
143    let prefix = if from_end {
144        chars
145            .iter()
146            .position(|ch| ch.is_alphanumeric())
147            .unwrap_or(chars.len())
148    } else {
149        0
150    };
151    chars
152        .iter()
153        .enumerate()
154        .map(|(index, _)| {
155            if index < prefix {
156                format!("p{index}")
157            } else if from_end {
158                format!("e{}", chars.len() - 1 - index)
159            } else {
160                format!("s{index}")
161            }
162        })
163        .collect()
164}
165
166fn landing_curve() -> CubicBezier {
167    CubicBezier::new(LANDING.0, LANDING.1, LANDING.2, LANDING.3)
168}
169
170struct Reel {
171    char: char,
172    strip: Vec<char>,
173    from: f32,
174    to: f32,
175    started_at: f64,
176    duration: f64,
177    done: bool,
178}
179
180struct SlotShared {
181    reels: RefCell<HashMap<String, Reel>>,
182    initial_keys: RefCell<Option<HashSet<String>>>,
183    prev_value: RefCell<Option<f64>>,
184    rising: RefCell<bool>,
185}
186
187impl Default for SlotShared {
188    fn default() -> Self {
189        Self {
190            reels: RefCell::new(HashMap::new()),
191            initial_keys: RefCell::new(None),
192            prev_value: RefCell::new(None),
193            rising: RefCell::new(true),
194        }
195    }
196}
197
198type FormatFn = Rc<dyn Fn(f64) -> String>;
199
200/// Arc `SlotText` — text and numbers that spin into their new value like slot reels.
201#[derive(IntoElement)]
202pub struct SlotText {
203    id: ElementId,
204    value: SlotValue,
205    format: Option<FormatFn>,
206    duration: f64,
207    stagger: f64,
208    spins: usize,
209    align: Option<SlotAlign>,
210    announce: bool,
211    text_size: Pixels,
212}
213
214impl SlotText {
215    pub fn new(id: impl Into<ElementId>, value: impl Into<SlotValue>) -> Self {
216        Self {
217            id: id.into(),
218            value: value.into(),
219            format: None,
220            duration: 0.9,
221            stagger: 0.07,
222            spins: 1,
223            align: None,
224            announce: false,
225            text_size: Typography::TEXT_3XL,
226        }
227    }
228
229    /// Formats a numeric value (defaults to `en-US` grouping).
230    pub fn format(mut self, format: impl Fn(f64) -> String + 'static) -> Self {
231        self.format = Some(Rc::new(format));
232        self
233    }
234
235    /// Seconds the first reel spins.
236    pub fn duration(mut self, duration: f64) -> Self {
237        self.duration = duration.max(0.05);
238        self
239    }
240
241    /// Seconds between reels stopping, left to right.
242    pub fn stagger(mut self, stagger: f64) -> Self {
243        self.stagger = stagger.max(0.0);
244        self
245    }
246
247    /// Extra full turns a digit makes before landing.
248    pub fn spins(mut self, spins: usize) -> Self {
249        self.spins = spins;
250        self
251    }
252
253    pub fn align(mut self, align: SlotAlign) -> Self {
254        self.align = Some(align);
255        self
256    }
257
258    pub fn announce(mut self, announce: bool) -> Self {
259        self.announce = announce;
260        self
261    }
262
263    pub fn text_size(mut self, size: Pixels) -> Self {
264        self.text_size = size;
265        self
266    }
267
268    fn text(&self) -> String {
269        match &self.value {
270            SlotValue::Text(text) => text.to_string(),
271            SlotValue::Number(value) => match &self.format {
272                Some(format) => format(*value),
273                None => group_en_us(*value),
274            },
275        }
276    }
277}
278
279/// Minimal `en-US` number formatting (`12,480`) matching Arc's default.
280pub fn group_en_us(value: f64) -> String {
281    let rounded = if value.fract() == 0.0 {
282        format!("{}", value as i64)
283    } else {
284        format!("{value}")
285    };
286    let (sign, rest) = match rounded.strip_prefix('-') {
287        Some(rest) => ("-", rest),
288        None => ("", rounded.as_str()),
289    };
290    let (integer, fraction) = match rest.split_once('.') {
291        Some((i, f)) => (i, Some(f)),
292        None => (rest, None),
293    };
294    let mut grouped = String::new();
295    for (index, ch) in integer.chars().enumerate() {
296        if index > 0 && (integer.len() - index) % 3 == 0 {
297            grouped.push(',');
298        }
299        grouped.push(ch);
300    }
301    match fraction {
302        Some(fraction) => format!("{sign}{grouped}.{fraction}"),
303        None => format!("{sign}{grouped}"),
304    }
305}
306
307impl RenderOnce for SlotText {
308    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
309        let theme = cx.arc_theme().clone();
310        let colors = theme.colors;
311        let reduced = is_reduced_motion(cx);
312
313        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-slot-text".into());
314        let shared = window
315            .use_keyed_state(state_id, cx, |_, _| Rc::new(SlotShared::default()))
316            .read(cx)
317            .clone();
318
319        let text = self.text();
320        let chars: Vec<char> = text.chars().collect();
321        let default_align = match self.value {
322            SlotValue::Number(_) => SlotAlign::End,
323            SlotValue::Text(_) => SlotAlign::Start,
324        };
325        let align = self.align.unwrap_or(default_align);
326        let keys = reel_keys(&chars, align);
327
328        let mut initial = shared.initial_keys.borrow_mut();
329        if initial.is_none() {
330            *initial = Some(keys.iter().cloned().collect());
331        }
332        let initial_keys = initial.clone().unwrap_or_default();
333        drop(initial);
334
335        // Track direction for numeric values so digits roll the way the number moved.
336        {
337            let mut prev = shared.prev_value.borrow_mut();
338            if let SlotValue::Number(value) = self.value {
339                let rising = prev.map(|p| value >= p).unwrap_or(true);
340                if prev.map(|p| (p - value).abs() > 1e-9).unwrap_or(true) {
341                    *shared.rising.borrow_mut() = rising;
342                }
343                *prev = Some(value);
344            }
345        }
346        let rising = *shared.rising.borrow();
347
348        let now = motion_now(cx);
349        let curve = landing_curve();
350        let em = f32::from(self.text_size);
351        let mut reels_row = div()
352            .flex()
353            .flex_row()
354            .items_start()
355            .h(px(LINE * em))
356            .whitespace_nowrap();
357
358        let mut reels_guard = shared.reels.borrow_mut();
359        for (order, (ch, key)) in chars.iter().zip(keys.iter()).enumerate() {
360            let entering = !initial_keys.contains(key);
361            let time = self.duration + order as f64 * self.stagger;
362
363            let reel = reels_guard.entry(key.clone()).or_insert_with(|| {
364                let strip = if entering && !reduced {
365                    strip_for(' ', *ch, self.spins, rising, (*ch as u32) + order as u32)
366                } else {
367                    vec![*ch]
368                };
369                let last = strip.len().saturating_sub(1) as f32;
370                Reel {
371                    char: *ch,
372                    strip,
373                    from: 0.0,
374                    to: last,
375                    started_at: now,
376                    duration: time,
377                    done: last <= 0.0,
378                }
379            });
380
381            if reel.char != *ch {
382                let current = reel_progress(reel, now, &curve);
383                let index = (current.round() as i32)
384                    .clamp(0, reel.strip.len().saturating_sub(1) as i32)
385                    as usize;
386                let visible = reel.strip[index].to_string();
387                let visible = visible.chars().next().unwrap_or(*ch);
388                let strip = if reduced {
389                    vec![*ch]
390                } else {
391                    strip_for(
392                        visible,
393                        *ch,
394                        self.spins,
395                        rising,
396                        (*ch as u32)
397                            .wrapping_mul(31)
398                            .wrapping_add((visible as u32).wrapping_mul(7))
399                            .wrapping_add(order as u32)
400                            .wrapping_add(reel.strip.len() as u32),
401                    )
402                };
403                let last = strip.len().saturating_sub(1) as f32;
404                reel.char = *ch;
405                reel.strip = strip;
406                reel.from = if reduced { 0.0 } else { current - index as f32 };
407                reel.to = last;
408                reel.started_at = now;
409                reel.duration = time;
410                reel.done = last <= 0.0;
411            }
412
413            let progress = reel_progress(reel, now, &curve);
414            if !reel.done {
415                window.request_animation_frame();
416            }
417            let strip = reel.strip.clone();
418
419            let mut strip_column = div()
420                .absolute()
421                .left(px(0.08 * em))
422                .right(px(0.08 * em))
423                .top(px((0.22 - 0.225 - progress * CELL) * em))
424                .flex()
425                .flex_col()
426                .items_center();
427            for cell in &strip {
428                strip_column = strip_column.child(
429                    div()
430                        .h(px(CELL * em))
431                        .pt(px(0.225 * em))
432                        .flex_none()
433                        .justify_center()
434                        .text_center()
435                        .line_height(self.text_size * LINE)
436                        .child(cell.to_string()),
437                );
438            }
439
440            let window = div()
441                .absolute()
442                .top(px(-0.22 * em))
443                .bottom(px(-0.22 * em))
444                .left(px(-0.08 * em))
445                .right(px(-0.08 * em))
446                .overflow_hidden()
447                .child(strip_column);
448
449            let slot = div()
450                .relative()
451                .flex_none()
452                .h(px(LINE * em))
453                .child(div().opacity(0.0).child(ch.to_string()))
454                .child(window);
455            reels_row = reels_row.child(slot);
456        }
457        drop(reels_guard);
458
459        let announce = self.announce;
460        div()
461            .id(self.id)
462            .test_support()
463            .self_start()
464            .relative()
465            .flex()
466            .flex_row()
467            .items_start()
468            .text_color(colors.foreground)
469            .text_size(self.text_size)
470            .line_height(self.text_size * LINE)
471            .aria_label(text.clone())
472            .when(announce, |this| this.text_color(colors.foreground))
473            .child(reels_row)
474    }
475}
476
477/// Sampling helper kept as a free function so tests can drive it without a window.
478fn reel_progress(reel: &Reel, now: f64, curve: &CubicBezier) -> f32 {
479    if reel.duration <= 0.0 || reel.done {
480        return reel.to;
481    }
482    let t = ((now - reel.started_at) / reel.duration).clamp(0.0, 1.0) as f32;
483    let eased = curve.sample(t);
484    reel.from + (reel.to - reel.from) * eased
485}
486
487#[cfg(test)]
488mod tests {
489    use std::cell::Cell;
490
491    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
492    use gpui_kit::{
493        Context, Render, TestAppContext, div,
494        test::{TestQueryExt as _, TestWindowExt as _},
495    };
496
497    use super::*;
498
499    #[test]
500    fn digits_roll_one_step_and_wrap_upward() {
501        assert_eq!(strip_for('4', '5', 0, true, 0), vec!['4', '5']);
502        assert_eq!(strip_for('9', '0', 0, true, 0), vec!['9', '0']);
503        assert_eq!(strip_for('5', '4', 0, false, 0), vec!['5', '4']);
504        assert_eq!(
505            strip_for('8', '6', 0, false, 0),
506            vec!['8', '7', '6'],
507            "decreasing walks backwards"
508        );
509        assert_eq!(
510            strip_for('4', '5', 1, true, 0).len(),
511            12,
512            "ten extra turns plus one step"
513        );
514        assert_eq!(strip_for('a', 'a', 1, true, 0), vec!['a']);
515    }
516
517    #[test]
518    fn letters_shuffle_through_their_own_alphabet_deterministically() {
519        let first = strip_for('a', 'b', 1, true, 42);
520        let second = strip_for('a', 'b', 1, true, 42);
521        assert_eq!(first, second);
522        assert_eq!(first.first(), Some(&'a'));
523        assert_eq!(first.last(), Some(&'b'));
524        assert!(first.len() >= 4);
525        assert!(first.iter().all(|ch| ch.is_ascii_lowercase()));
526    }
527
528    #[test]
529    fn keys_align_from_the_end_for_numbers() {
530        let chars: Vec<char> = "¥999".chars().collect();
531        assert_eq!(
532            reel_keys(&chars, SlotAlign::End),
533            vec!["p0", "e2", "e1", "e0"]
534        );
535        let grown: Vec<char> = "¥1,000".chars().collect();
536        let keys = reel_keys(&grown, SlotAlign::End);
537        assert_eq!(keys[0], "p0");
538        assert_eq!(keys.last().map(String::as_str), Some("e0"));
539        assert_eq!(keys.len(), grown.len());
540        let plain: Vec<char> = "ab".chars().collect();
541        assert_eq!(reel_keys(&plain, SlotAlign::Start), vec!["s0", "s1"]);
542    }
543
544    #[test]
545    fn en_us_grouping_matches_arc_default() {
546        assert_eq!(group_en_us(12_480.0), "12,480");
547        assert_eq!(group_en_us(999.0), "999");
548        assert_eq!(group_en_us(1_000_000.0), "1,000,000");
549        assert_eq!(group_en_us(-2_500.5), "-2,500.5");
550    }
551
552    #[test]
553    fn landing_curve_approaches_one_without_overshoot() {
554        let curve = landing_curve();
555        let mut last = 0.0;
556        for step in 0..=20 {
557            let value = curve.sample(step as f32 / 20.0);
558            assert!(value >= last - 1e-4, "landing must be monotonic");
559            assert!(value <= 1.0 + 1e-4);
560            last = value;
561        }
562        assert!((curve.sample(1.0) - 1.0).abs() < 1e-3);
563    }
564
565    struct SlotHost {
566        value: f64,
567    }
568
569    impl Render for SlotHost {
570        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
571            div().p(px(24.0)).child(
572                SlotText::new("price", self.value)
573                    .align(SlotAlign::End)
574                    .duration(0.2)
575                    .stagger(0.01),
576            )
577        }
578    }
579
580    #[gpui_kit::test]
581    fn slot_text_renders_and_restarts_reels_on_change(cx: &mut TestAppContext) {
582        cx.update(|cx| {
583            gpui_kit::init(cx);
584            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
585        });
586        let (view, cx) = cx.add_window_view(|_, _| SlotHost { value: 12.0 });
587        let frames = Rc::new(Cell::new(0usize));
588        cx.update(|window, cx| {
589            for _ in 0..3 {
590                window.render_frame(cx);
591                frames.set(frames.get() + 1);
592            }
593            assert!(f32::from(window.find_by_label("12").bounds().size.width) > 0.0);
594        });
595        view.update(cx, |host, cx| {
596            host.value = 9.0;
597            cx.notify();
598        });
599        cx.update(|window, cx| {
600            for _ in 0..10 {
601                window.render_frame(cx);
602            }
603            assert!(f32::from(window.find_by_label("9").bounds().size.width) > 0.0);
604        });
605        assert!(frames.get() == 3);
606    }
607}