rnk 0.17.3

A React-like declarative terminal UI framework for Rust, inspired by Ink
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
//! Transition hook for smooth value changes
//!
//! Provides a simple hook for transitioning between values with easing.

use crate::animation::{Animation, AnimationInstance, Easing, FillMode};
use crate::hooks::context::{RenderCallback, current_context};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

/// Handle for a transitioning value
#[derive(Clone)]
pub struct TransitionHandle {
    current: Arc<RwLock<f32>>,
    target: Arc<RwLock<f32>>,
    instance: Arc<RwLock<Option<AnimationInstance>>>,
    duration: Duration,
    easing: Easing,
    last_tick: Arc<RwLock<Instant>>,
    render_callback: Option<RenderCallback>,
}

impl TransitionHandle {
    /// Get the current value
    pub fn get(&self) -> f32 {
        if let Some(ref instance) = *self.instance.read().unwrap() {
            if instance.is_running() {
                return instance.get();
            }
        }
        *self.current.read().unwrap()
    }

    /// Get the current value as i32
    pub fn get_i32(&self) -> i32 {
        self.get().round() as i32
    }

    /// Get the current value as usize
    pub fn get_usize(&self) -> usize {
        self.get().round().max(0.0) as usize
    }

    /// Get the target value
    pub fn target(&self) -> f32 {
        *self.target.read().unwrap()
    }

    /// Set a new target value and start transitioning
    pub fn set(&self, value: f32) {
        let current = self.get();
        *self.target.write().unwrap() = value;

        if (current - value).abs() < 0.001 {
            // Already at target, no transition needed
            *self.current.write().unwrap() = value;
            *self.instance.write().unwrap() = None;
            return;
        }

        // Create new animation from current to target
        let anim = Animation::new()
            .from(current)
            .to(value)
            .duration(self.duration)
            .easing(self.easing)
            .fill_mode(FillMode::Forwards);

        let mut instance = anim.start();
        instance.play();

        *self.instance.write().unwrap() = Some(instance);
        *self.last_tick.write().unwrap() = Instant::now();

        self.trigger_render();
    }

    /// Set value immediately without transition
    pub fn set_immediate(&self, value: f32) {
        *self.current.write().unwrap() = value;
        *self.target.write().unwrap() = value;
        *self.instance.write().unwrap() = None;
        self.trigger_render();
    }

    /// Check if currently transitioning
    pub fn is_transitioning(&self) -> bool {
        self.instance
            .read()
            .unwrap()
            .as_ref()
            .is_some_and(|i| i.is_running())
    }

    /// Tick the transition (called internally)
    pub fn tick(&self) {
        let now = Instant::now();
        let delta = {
            let mut last = self.last_tick.write().unwrap();
            let delta = now.duration_since(*last);
            *last = now;
            delta
        };

        let mut instance_guard = self.instance.write().unwrap();
        if let Some(ref mut instance) = *instance_guard {
            let was_running = instance.is_running();
            instance.tick(delta);

            if instance.is_completed() {
                // Update current to final value
                *self.current.write().unwrap() = *self.target.read().unwrap();
                *instance_guard = None;
            } else if was_running && instance.is_running() {
                drop(instance_guard);
                self.trigger_render();
            }
        }
    }

    fn trigger_render(&self) {
        if let Some(callback) = &self.render_callback {
            callback();
        }
    }

    // =========================================================================
    // Try methods (non-panicking versions)
    // =========================================================================

    /// Try to get the current value, returning None if lock is poisoned
    pub fn try_get(&self) -> Option<f32> {
        let instance_guard = self.instance.read().ok()?;
        if let Some(ref instance) = *instance_guard {
            if instance.is_running() {
                return Some(instance.get());
            }
        }
        self.current.read().ok().map(|g| *g)
    }

    /// Try to get the current value as i32, returning None if lock is poisoned
    pub fn try_get_i32(&self) -> Option<i32> {
        self.try_get().map(|v| v.round() as i32)
    }

    /// Try to get the current value as usize, returning None if lock is poisoned
    pub fn try_get_usize(&self) -> Option<usize> {
        self.try_get().map(|v| v.round().max(0.0) as usize)
    }

    /// Try to get the target value, returning None if lock is poisoned
    pub fn try_target(&self) -> Option<f32> {
        self.target.read().ok().map(|g| *g)
    }

    /// Try to set a new target value, returning false if lock is poisoned
    pub fn try_set(&self, value: f32) -> bool {
        let current = match self.try_get() {
            Some(v) => v,
            None => return false,
        };

        if self.target.write().ok().map(|mut g| *g = value).is_none() {
            return false;
        }

        if (current - value).abs() < 0.001 {
            // Already at target, no transition needed
            if self.current.write().ok().map(|mut g| *g = value).is_none() {
                return false;
            }
            if self.instance.write().ok().map(|mut g| *g = None).is_none() {
                return false;
            }
            return true;
        }

        // Create new animation from current to target
        let anim = Animation::new()
            .from(current)
            .to(value)
            .duration(self.duration)
            .easing(self.easing)
            .fill_mode(FillMode::Forwards);

        let mut instance = anim.start();
        instance.play();

        if self
            .instance
            .write()
            .ok()
            .map(|mut g| *g = Some(instance))
            .is_none()
        {
            return false;
        }
        if self
            .last_tick
            .write()
            .ok()
            .map(|mut g| *g = Instant::now())
            .is_none()
        {
            return false;
        }

        self.trigger_render();
        true
    }

    /// Try to set value immediately without transition, returning false if lock is poisoned
    pub fn try_set_immediate(&self, value: f32) -> bool {
        if self.current.write().ok().map(|mut g| *g = value).is_none() {
            return false;
        }
        if self.target.write().ok().map(|mut g| *g = value).is_none() {
            return false;
        }
        if self.instance.write().ok().map(|mut g| *g = None).is_none() {
            return false;
        }
        self.trigger_render();
        true
    }

    /// Try to check if currently transitioning, returning None if lock is poisoned
    pub fn try_is_transitioning(&self) -> Option<bool> {
        self.instance
            .read()
            .ok()
            .map(|g| g.as_ref().is_some_and(|i| i.is_running()))
    }
}

impl std::fmt::Debug for TransitionHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TransitionHandle")
            .field("current", &self.get())
            .field("target", &self.target())
            .field("transitioning", &self.is_transitioning())
            .finish()
    }
}

/// Storage for transition hook
#[derive(Clone)]
struct TransitionStorage {
    handle: TransitionHandle,
}

fn new_transition_handle(
    initial: f32,
    duration: Duration,
    easing: Easing,
    render_callback: Option<RenderCallback>,
) -> TransitionHandle {
    TransitionHandle {
        current: Arc::new(RwLock::new(initial)),
        target: Arc::new(RwLock::new(initial)),
        instance: Arc::new(RwLock::new(None)),
        duration,
        easing,
        last_tick: Arc::new(RwLock::new(Instant::now())),
        render_callback,
    }
}

/// Create a transition hook for smooth value changes
///
/// Returns a tuple of (current_value, set_function) where setting a new value
/// will smoothly transition from the current value.
///
/// # Example
///
/// ```ignore
/// use rnk::animation::DurationExt;
///
/// fn my_component() -> Element {
///     let position = use_transition(0.0, 200.ms());
///
///     use_input(move |input, _| {
///         if input == "j" {
///             position.set(position.target() + 10.0);
///         }
///     });
///
///     let y = position.get_i32();
///     // Use y for positioning...
/// }
/// ```
pub fn use_transition(initial: f32, duration: Duration) -> TransitionHandle {
    use_transition_with_easing(initial, duration, Easing::EaseInOut)
}

/// Create a transition hook with custom easing
///
/// # Example
///
/// ```ignore
/// use rnk::animation::{DurationExt, Easing};
///
/// let scale = use_transition_with_easing(1.0, 150.ms(), Easing::EaseOutBack);
/// ```
pub fn use_transition_with_easing(
    initial: f32,
    duration: Duration,
    easing: Easing,
) -> TransitionHandle {
    let Some(ctx) = current_context() else {
        return new_transition_handle(initial, duration, easing, None);
    };
    let Ok(mut ctx_ref) = ctx.write() else {
        return new_transition_handle(initial, duration, easing, None);
    };

    let render_callback = ctx_ref.get_render_callback();

    let storage = ctx_ref.use_hook(|| TransitionStorage {
        handle: new_transition_handle(initial, duration, easing, render_callback.clone()),
    });

    storage
        .get::<TransitionStorage>()
        .map(|s| s.handle)
        .unwrap_or_else(|| new_transition_handle(initial, duration, easing, render_callback))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::animation::DurationExt;
    use crate::hooks::context::{HookContext, with_hooks};

    #[test]
    fn test_transition_handle_basic() {
        let handle = TransitionHandle {
            current: Arc::new(RwLock::new(0.0)),
            target: Arc::new(RwLock::new(0.0)),
            instance: Arc::new(RwLock::new(None)),
            duration: Duration::from_millis(100),
            easing: Easing::Linear,
            last_tick: Arc::new(RwLock::new(Instant::now())),
            render_callback: None,
        };

        assert_eq!(handle.get(), 0.0);
        assert!(!handle.is_transitioning());
    }

    #[test]
    fn test_transition_set() {
        let handle = TransitionHandle {
            current: Arc::new(RwLock::new(0.0)),
            target: Arc::new(RwLock::new(0.0)),
            instance: Arc::new(RwLock::new(None)),
            duration: Duration::from_millis(100),
            easing: Easing::Linear,
            last_tick: Arc::new(RwLock::new(Instant::now())),
            render_callback: None,
        };

        handle.set(100.0);
        assert!(handle.is_transitioning());
        assert_eq!(handle.target(), 100.0);
    }

    #[test]
    fn test_transition_immediate() {
        let handle = TransitionHandle {
            current: Arc::new(RwLock::new(0.0)),
            target: Arc::new(RwLock::new(0.0)),
            instance: Arc::new(RwLock::new(None)),
            duration: Duration::from_millis(100),
            easing: Easing::Linear,
            last_tick: Arc::new(RwLock::new(Instant::now())),
            render_callback: None,
        };

        handle.set_immediate(50.0);
        assert!(!handle.is_transitioning());
        assert_eq!(handle.get(), 50.0);
        assert_eq!(handle.target(), 50.0);
    }

    #[test]
    fn test_use_transition_in_context() {
        let ctx = Arc::new(RwLock::new(HookContext::new()));

        let handle = with_hooks(ctx.clone(), || use_transition(0.0, 100.ms()));

        assert_eq!(handle.get(), 0.0);
        handle.set(100.0);
        assert!(handle.is_transitioning());
    }

    #[test]
    fn test_transition_persistence() {
        let ctx = Arc::new(RwLock::new(HookContext::new()));

        // First render
        let handle1 = with_hooks(ctx.clone(), || use_transition(0.0, 100.ms()));
        handle1.set(50.0);

        // Second render - should preserve state
        let handle2 = with_hooks(ctx.clone(), || use_transition(999.0, 999.ms()));

        assert_eq!(handle2.target(), 50.0);
    }

    #[test]
    fn test_transition_no_change() {
        let handle = TransitionHandle {
            current: Arc::new(RwLock::new(50.0)),
            target: Arc::new(RwLock::new(50.0)),
            instance: Arc::new(RwLock::new(None)),
            duration: Duration::from_millis(100),
            easing: Easing::Linear,
            last_tick: Arc::new(RwLock::new(Instant::now())),
            render_callback: None,
        };

        // Setting to same value should not start transition
        handle.set(50.0);
        assert!(!handle.is_transitioning());
    }

    #[test]
    fn test_use_transition_without_context_does_not_panic() {
        let handle = use_transition(0.0, 100.ms());
        assert_eq!(handle.get(), 0.0);

        handle.set(100.0);
        assert!(handle.is_transitioning());
        assert_eq!(handle.target(), 100.0);
    }
}