Skip to main content

arc_motion/
value.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Subscribable `MotionValue<T>` with `map` (`useTransform`) and `velocity` (`useVelocity`).
3
4use std::{cell::RefCell, collections::VecDeque, rc::Rc};
5
6const VELOCITY_WINDOW_SECS: f64 = 0.1;
7
8/// Piecewise linear mapping matching Motion's `useTransform(value, range_in, range_out, { clamp })`.
9pub fn map_range(value: f32, range_in: &[f32], range_out: &[f32], clamp: bool) -> f32 {
10    debug_assert_eq!(range_in.len(), range_out.len());
11    debug_assert!(range_in.len() >= 2);
12    if range_in.len() < 2 || range_out.len() != range_in.len() {
13        return value;
14    }
15
16    let last = range_in.len() - 1;
17    let ascending = range_in[last] >= range_in[0];
18
19    if clamp {
20        if ascending {
21            if value <= range_in[0] {
22                return range_out[0];
23            }
24            if value >= range_in[last] {
25                return range_out[last];
26            }
27        } else {
28            if value >= range_in[0] {
29                return range_out[0];
30            }
31            if value <= range_in[last] {
32                return range_out[last];
33            }
34        }
35    }
36
37    let mut seg = 0;
38    for i in 0..last {
39        let b = range_in[i + 1];
40        if (ascending && value <= b) || (!ascending && value >= b) {
41            seg = i;
42            break;
43        }
44        seg = i;
45    }
46
47    let in_a = range_in[seg];
48    let in_b = range_in[seg + 1];
49    let out_a = range_out[seg];
50    let out_b = range_out[seg + 1];
51    let span = in_b - in_a;
52    if span.abs() <= f32::EPSILON {
53        return out_b;
54    }
55    let t = (value - in_a) / span;
56    out_a + (out_b - out_a) * t
57}
58
59type ListenerFn<T> = Rc<dyn Fn(&T)>;
60type Listener<T> = (usize, ListenerFn<T>);
61
62struct Inner<T> {
63    value: T,
64    next_listener_id: usize,
65    listeners: Vec<Listener<T>>,
66    /// Timestamped scalar samples (time_secs, value) for velocity estimation when `T = f32`.
67    samples: VecDeque<(f64, f32)>,
68}
69
70/// Subscribable reactive value (`f32`, `Point<Pixels>`, `Hsla`, etc.) with derived mapping
71/// and velocity tracking.
72#[derive(Clone)]
73pub struct MotionValue<T> {
74    inner: Rc<RefCell<Inner<T>>>,
75}
76
77impl<T: Clone + 'static> MotionValue<T> {
78    pub fn new(initial: T) -> Self {
79        Self {
80            inner: Rc::new(RefCell::new(Inner {
81                value: initial,
82                next_listener_id: 1,
83                listeners: Vec::new(),
84                samples: VecDeque::with_capacity(8),
85            })),
86        }
87    }
88
89    pub fn get(&self) -> T {
90        self.inner.borrow().value.clone()
91    }
92
93    pub fn set(&self, next: T)
94    where
95        T: PartialEq,
96    {
97        let listeners: Vec<ListenerFn<T>> = {
98            let mut inner = self.inner.borrow_mut();
99            if inner.value == next {
100                return;
101            }
102            inner.value = next.clone();
103            inner.listeners.iter().map(|(_, cb)| cb.clone()).collect()
104        };
105        for cb in listeners {
106            cb(&next);
107        }
108    }
109
110    /// Subscribe to value changes. Returns an unsubscribe handle ID.
111    pub fn subscribe(&self, listener: impl Fn(&T) + 'static) -> usize {
112        let mut inner = self.inner.borrow_mut();
113        let id = inner.next_listener_id;
114        inner.next_listener_id += 1;
115        inner.listeners.push((id, Rc::new(listener)));
116        id
117    }
118
119    pub fn unsubscribe(&self, id: usize) {
120        self.inner
121            .borrow_mut()
122            .listeners
123            .retain(|(lid, _)| *lid != id);
124    }
125
126    /// Creates a derived `MotionValue<U>` updated automatically whenever this value changes.
127    pub fn map_fn<U: Clone + PartialEq + 'static>(
128        &self,
129        transform: impl Fn(&T) -> U + 'static,
130    ) -> MotionValue<U> {
131        let derived = MotionValue::new(transform(&self.get()));
132        let derived_clone = derived.clone();
133        self.subscribe(move |v| {
134            derived_clone.set(transform(v));
135        });
136        derived
137    }
138}
139
140impl MotionValue<f32> {
141    /// Sets a scalar value with an explicit timestamp (seconds) so [`Self::velocity`] stays accurate.
142    pub fn set_at(&self, next: f32, time_secs: f64) {
143        let listeners: Vec<ListenerFn<f32>> = {
144            let mut inner = self.inner.borrow_mut();
145            inner.samples.push_back((time_secs, next));
146            while inner.samples.len() > 2 {
147                if let Some(&(first_t, _)) = inner.samples.front()
148                    && time_secs - first_t > VELOCITY_WINDOW_SECS
149                {
150                    inner.samples.pop_front();
151                    continue;
152                }
153                break;
154            }
155            if (inner.value - next).abs() <= f32::EPSILON {
156                return;
157            }
158            inner.value = next;
159            inner.listeners.iter().map(|(_, cb)| cb.clone()).collect()
160        };
161        for cb in listeners {
162            cb(&next);
163        }
164    }
165
166    /// Jumps to `next` and resets velocity history (matching Motion's `mv.jump(...)`).
167    pub fn jump(&self, next: f32) {
168        let listeners: Vec<ListenerFn<f32>> = {
169            let mut inner = self.inner.borrow_mut();
170            inner.samples.clear();
171            inner.value = next;
172            inner.listeners.iter().map(|(_, cb)| cb.clone()).collect()
173        };
174        for cb in listeners {
175            cb(&next);
176        }
177    }
178
179    /// Returns instantaneous velocity in units/sec (matching Motion's `useVelocity` / `getVelocity`).
180    pub fn velocity(&self) -> f32 {
181        let inner = self.inner.borrow();
182        let (Some(&(t0, v0)), Some(&(t1, v1))) = (inner.samples.front(), inner.samples.back())
183        else {
184            return 0.0;
185        };
186        let dt = t1 - t0;
187        if dt <= 1e-5 {
188            return 0.0;
189        }
190        ((v1 - v0) as f64 / dt) as f32
191    }
192
193    /// Piecewise-linear derived value (`useTransform(mv, range_in, range_out, clamp)`).
194    pub fn map(&self, range_in: Vec<f32>, range_out: Vec<f32>, clamp: bool) -> MotionValue<f32> {
195        self.map_fn(move |&v| map_range(v, &range_in, &range_out, clamp))
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use std::cell::Cell;
202
203    use super::*;
204
205    #[test]
206    fn motion_value_map_and_clamp_work() {
207        let x = MotionValue::new(0.0_f32);
208        let opacity = x.map(vec![0.0, 280.0], vec![1.0, 0.25], true);
209        assert!((opacity.get() - 1.0).abs() < 1e-5);
210
211        x.set(140.0);
212        assert!((opacity.get() - 0.625).abs() < 1e-5);
213
214        x.set(500.0);
215        assert!((opacity.get() - 0.25).abs() < 1e-5);
216
217        x.set(-50.0);
218        assert!((opacity.get() - 1.0).abs() < 1e-5);
219    }
220
221    #[test]
222    fn motion_value_velocity_and_jump_reset() {
223        let pos = MotionValue::new(0.0_f32);
224        pos.set_at(0.0, 1.000);
225        pos.set_at(50.0, 1.050);
226        assert!((pos.velocity() - 1000.0).abs() < 1e-2);
227
228        pos.jump(10.0);
229        assert_eq!(pos.get(), 10.0);
230        assert_eq!(pos.velocity(), 0.0);
231    }
232
233    #[test]
234    fn motion_value_subscribe_and_unsubscribe() {
235        let v = MotionValue::new(1.0_f32);
236        let hits = Rc::new(Cell::new(0usize));
237        let hits_clone = hits.clone();
238        let sub = v.subscribe(move |_| hits_clone.set(hits_clone.get() + 1));
239        v.set(2.0);
240        v.set(2.0); // unchanged does not fire
241        assert_eq!(hits.get(), 1);
242        v.unsubscribe(sub);
243        v.set(3.0);
244        assert_eq!(hits.get(), 1);
245    }
246}