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,
};
const CELL: f32 = 1.6;
const LINE: f32 = 1.15;
const DIGITS: &str = "0123456789";
const LOWER: &str = "abcdefghijklmnopqrstuvwxyz";
const UPPER: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const LANDING: (f64, f64, f64, f64) = (0.12, 0.8, 0.16, 1.0);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SlotAlign {
Start,
End,
}
#[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
}
}
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)
}
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
}
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>;
#[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,
}
}
pub fn format(mut self, format: impl Fn(f64) -> String + 'static) -> Self {
self.format = Some(Rc::new(format));
self
}
pub fn duration(mut self, duration: f64) -> Self {
self.duration = duration.max(0.05);
self
}
pub fn stagger(mut self, stagger: f64) -> Self {
self.stagger = stagger.max(0.0);
self
}
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),
},
}
}
}
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);
{
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)
}
}
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);
}
}