revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! Async state management for reactive systems
//!
//! Provides hooks for integrating async operations with the reactive system.
//! Uses background threads for non-blocking execution while maintaining
//! reactive updates. Since Signals are now thread-safe (`Arc<RwLock>`),
//! async operations can directly update signals from background threads.
//!
//! # Example
//!
//! ```rust,ignore
//! use revue::prelude::*;
//!
//! // Create async state that fetches data
//! let (user_data, fetch) = use_async(|| {
//!     // This runs in background thread
//!     fetch_user(1)
//! });
//!
//! // Trigger the fetch
//! fetch();
//!
//! // Check the state
//! match user_data.get() {
//!     AsyncState::Idle => println!("Not started"),
//!     AsyncState::Loading => println!("Loading..."),
//!     AsyncState::Ready(user) => println!("User: {:?}", user),
//!     AsyncState::Error(e) => println!("Error: {}", e),
//! }
//! ```

use crate::utils::lock::{read_or_recover, write_or_recover};
use std::fmt;
use std::sync::{Arc, RwLock};
use std::thread;

use super::{signal, Signal};

/// State of an async operation
///
/// Represents the lifecycle of an async task from idle to completion.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum AsyncState<T> {
    /// Task has not started yet
    #[default]
    Idle,
    /// Task is currently running
    Loading,
    /// Task completed successfully with a result
    Ready(T),
    /// Task failed with an error message
    Error(String),
}

impl<T> AsyncState<T> {
    /// Returns true if the state is Idle
    pub fn is_idle(&self) -> bool {
        matches!(self, AsyncState::Idle)
    }

    /// Returns true if the state is Loading
    pub fn is_loading(&self) -> bool {
        matches!(self, AsyncState::Loading)
    }

    /// Returns true if the state is Ready
    pub fn is_ready(&self) -> bool {
        matches!(self, AsyncState::Ready(_))
    }

    /// Returns true if the state is Error
    pub fn is_error(&self) -> bool {
        matches!(self, AsyncState::Error(_))
    }

    /// Get the value if Ready, otherwise None
    pub fn value(&self) -> Option<&T> {
        match self {
            AsyncState::Ready(v) => Some(v),
            _ => None,
        }
    }

    /// Get the error message if Error, otherwise None
    pub fn error(&self) -> Option<&str> {
        match self {
            AsyncState::Error(e) => Some(e),
            _ => None,
        }
    }

    /// Map the value if Ready
    pub fn map<U, F: FnOnce(&T) -> U>(&self, f: F) -> AsyncState<U>
    where
        U: Clone,
    {
        match self {
            AsyncState::Idle => AsyncState::Idle,
            AsyncState::Loading => AsyncState::Loading,
            AsyncState::Ready(v) => AsyncState::Ready(f(v)),
            AsyncState::Error(e) => AsyncState::Error(e.clone()),
        }
    }

    /// Unwrap the value or return a default
    pub fn unwrap_or(&self, default: T) -> T
    where
        T: Clone,
    {
        match self {
            AsyncState::Ready(v) => v.clone(),
            _ => default,
        }
    }

    /// Unwrap the value or compute a default
    pub fn unwrap_or_else<F: FnOnce() -> T>(&self, f: F) -> T
    where
        T: Clone,
    {
        match self {
            AsyncState::Ready(v) => v.clone(),
            _ => f(),
        }
    }
}

impl<T: fmt::Display> fmt::Display for AsyncState<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AsyncState::Idle => write!(f, "Idle"),
            AsyncState::Loading => write!(f, "Loading"),
            AsyncState::Ready(v) => write!(f, "Ready({})", v),
            AsyncState::Error(e) => write!(f, "Error({})", e),
        }
    }
}

/// Result type for async tasks
pub type AsyncResult<T> = Result<T, String>;

/// Create an async state with manual trigger control
///
/// Returns a tuple of (state signal, trigger function).
/// Call the trigger function to start the async operation.
/// Since Signal is now thread-safe, the background thread can
/// directly update the signal.
///
/// # Example
///
/// ```rust,ignore
/// let (state, trigger) = use_async(|| {
///     // Runs in background thread
///     fetch_data()
/// });
///
/// // Start the async operation
/// trigger();
///
/// // Check state
/// if state.get().is_ready() {
///     // Handle result
/// }
/// ```
pub fn use_async<T, F>(f: F) -> (Signal<AsyncState<T>>, impl Fn() + Clone)
where
    T: Clone + Send + Sync + 'static,
    F: Fn() -> AsyncResult<T> + Send + Sync + Clone + 'static,
{
    let state: Signal<AsyncState<T>> = signal(AsyncState::Idle);
    let state_clone = state.clone();

    let trigger = move || {
        state_clone.set(AsyncState::Loading);

        let f_clone = f.clone();
        let state_for_thread = state_clone.clone();

        thread::spawn(move || {
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f_clone));
            let result = match result {
                Ok(r) => r,
                Err(_) => Err("Task panicked".to_string()),
            };

            match result {
                Ok(value) => state_for_thread.set(AsyncState::Ready(value)),
                Err(e) => state_for_thread.set(AsyncState::Error(e)),
            }
        });
    };

    (state, trigger)
}

/// Internal state for poll-based async operations
#[derive(Clone)]
enum PollState<T> {
    /// No task running
    Idle,
    /// Task is running (no result yet)
    Running,
    /// Task completed with result
    Done(AsyncResult<T>),
}

/// Create an async state that polls in the tick loop
///
/// This version is designed to work with the app's tick loop for polling.
/// Returns a tuple of (state, start_fn, poll_fn) where:
/// - state: The reactive state signal
/// - start_fn: Call to begin the async operation
/// - poll_fn: Call each tick to check for completion (returns true when done)
///
/// # Thread Safety
///
/// Both `start` and `poll` can be called from any thread. The result is
/// communicated through thread-safe shared state (`Arc<RwLock>`).
///
/// # Example
///
/// ```rust,ignore
/// let (state, start, poll) = use_async_poll(|| fetch_data());
///
/// // In your app:
/// fn on_button_click(&mut self) {
///     start();
/// }
///
/// fn tick(&mut self) {
///     poll(); // Call each tick to check for completion
/// }
/// ```
pub fn use_async_poll<T, F>(
    f: F,
) -> (
    Signal<AsyncState<T>>,
    impl Fn() + Clone,
    impl Fn() -> bool + Clone,
)
where
    T: Clone + Send + Sync + 'static,
    F: Fn() -> AsyncResult<T> + Send + Sync + Clone + 'static,
{
    let state: Signal<AsyncState<T>> = signal(AsyncState::Idle);
    // Use thread-safe shared state instead of channel (Receiver is !Sync)
    let poll_state: Arc<RwLock<PollState<T>>> = Arc::new(RwLock::new(PollState::Idle));

    let poll_state_start = poll_state.clone();
    let state_start = state.clone();
    let start = move || {
        state_start.set(AsyncState::Loading);
        *write_or_recover(&poll_state_start) = PollState::Running;

        let f_clone = f.clone();
        let poll_state_thread = poll_state_start.clone();

        thread::spawn(move || {
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f_clone));
            let result = match result {
                Ok(r) => r,
                Err(_) => Err("Task panicked".to_string()),
            };
            *write_or_recover(&poll_state_thread) = PollState::Done(result);
        });
    };

    let poll_state_poll = poll_state.clone();
    let state_poll = state.clone();
    let poll = move || -> bool {
        // First, read to check if done (avoids unnecessary write lock)
        let is_done = matches!(*read_or_recover(&poll_state_poll), PollState::Done(_));

        if is_done {
            // Take the result with a write lock
            let mut guard = write_or_recover(&poll_state_poll);
            if let PollState::Done(result) = std::mem::replace(&mut *guard, PollState::Idle) {
                match result {
                    Ok(value) => state_poll.set(AsyncState::Ready(value)),
                    Err(e) => state_poll.set(AsyncState::Error(e)),
                }
                return true; // Task completed
            }
        }
        false // Still running or idle
    };

    (state, start, poll)
}

/// Create an async state that immediately starts execution
///
/// Unlike `use_async`, this starts the async operation immediately.
///
/// # Example
///
/// ```rust,ignore
/// let state = use_async_immediate(|| fetch_data());
/// // Operation has already started
/// ```
pub fn use_async_immediate<T, F>(f: F) -> Signal<AsyncState<T>>
where
    T: Clone + Send + Sync + 'static,
    F: FnOnce() -> AsyncResult<T> + Send + 'static,
{
    let state: Signal<AsyncState<T>> = signal(AsyncState::Loading);
    let state_for_thread = state.clone();

    thread::spawn(move || {
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
        let result = match result {
            Ok(r) => r,
            Err(_) => Err("Task panicked".to_string()),
        };

        match result {
            Ok(value) => state_for_thread.set(AsyncState::Ready(value)),
            Err(e) => state_for_thread.set(AsyncState::Error(e)),
        }
    });

    state
}

/// Builder for creating async resources with more control
///
/// # Example
///
/// ```rust,ignore
/// let (user, trigger) = AsyncResource::new(|| fetch_user())
///     .build();
/// ```
pub struct AsyncResource<T, F>
where
    T: Clone + Send + Sync + 'static,
    F: Fn() -> AsyncResult<T> + Send + Sync + Clone + 'static,
{
    fetch: F,
    _phantom: std::marker::PhantomData<T>,
}

impl<T, F> AsyncResource<T, F>
where
    T: Clone + Send + Sync + 'static,
    F: Fn() -> AsyncResult<T> + Send + Sync + Clone + 'static,
{
    /// Create a new async resource builder
    pub fn new(fetch: F) -> Self {
        Self {
            fetch,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Build and return the async state signal with manual trigger
    pub fn build(self) -> (Signal<AsyncState<T>>, impl Fn() + Clone) {
        use_async(self.fetch)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicI32, Ordering};
    use std::sync::Arc;
    use std::time::Duration;

    // AsyncState tests
    #[test]
    fn test_async_state_default() {
        let state: AsyncState<i32> = AsyncState::default();
        assert!(state.is_idle());
    }

    #[test]
    fn test_async_state_idle() {
        let state = AsyncState::<i32>::Idle;
        assert!(state.is_idle());
        assert!(!state.is_loading());
        assert!(!state.is_ready());
        assert!(!state.is_error());
    }

    #[test]
    fn test_async_state_loading() {
        let state = AsyncState::<i32>::Loading;
        assert!(!state.is_idle());
        assert!(state.is_loading());
        assert!(!state.is_ready());
        assert!(!state.is_error());
    }

    #[test]
    fn test_async_state_ready() {
        let state = AsyncState::Ready(42);
        assert!(!state.is_idle());
        assert!(!state.is_loading());
        assert!(state.is_ready());
        assert!(!state.is_error());
    }

    #[test]
    fn test_async_state_error() {
        let state = AsyncState::<i32>::Error("test error".to_string());
        assert!(!state.is_idle());
        assert!(!state.is_loading());
        assert!(!state.is_ready());
        assert!(state.is_error());
    }

    #[test]
    fn test_async_state_value() {
        let state = AsyncState::Ready(42);
        assert_eq!(state.value(), Some(&42));

        let state = AsyncState::<i32>::Loading;
        assert_eq!(state.value(), None);
    }

    #[test]
    fn test_async_state_error_message() {
        let state = AsyncState::<i32>::Error("test error".to_string());
        assert_eq!(state.error(), Some("test error"));

        let state = AsyncState::<i32>::Loading;
        assert_eq!(state.error(), None);
    }

    #[test]
    fn test_async_state_map() {
        let state = AsyncState::Ready(42);
        let mapped = state.map(|v| v * 2);
        assert_eq!(mapped, AsyncState::Ready(84));
    }

    #[test]
    fn test_async_state_map_idle() {
        let state = AsyncState::<i32>::Idle;
        let mapped = state.map(|v| v * 2);
        assert_eq!(mapped, AsyncState::<i32>::Idle);
    }

    #[test]
    fn test_async_state_map_loading() {
        let state = AsyncState::<i32>::Loading;
        let mapped = state.map(|v| v * 2);
        assert_eq!(mapped, AsyncState::<i32>::Loading);
    }

    #[test]
    fn test_async_state_map_error() {
        let state = AsyncState::<i32>::Error("error".to_string());
        let mapped = state.map(|v| v * 2);
        assert_eq!(mapped, AsyncState::Error("error".to_string()));
    }

    #[test]
    fn test_async_state_unwrap_or() {
        let state = AsyncState::Ready(42);
        assert_eq!(state.unwrap_or(0), 42);

        let state = AsyncState::<i32>::Idle;
        assert_eq!(state.unwrap_or(0), 0);
    }

    #[test]
    fn test_async_state_unwrap_or_else() {
        let state = AsyncState::Ready(42);
        assert_eq!(state.unwrap_or_else(|| 0), 42);

        let state = AsyncState::<i32>::Idle;
        assert_eq!(state.unwrap_or_else(|| 99), 99);
    }

    // Display tests
    #[test]
    fn test_async_state_display_idle() {
        let state = AsyncState::<i32>::Idle;
        assert_eq!(format!("{}", state), "Idle");
    }

    #[test]
    fn test_async_state_display_loading() {
        let state = AsyncState::<i32>::Loading;
        assert_eq!(format!("{}", state), "Loading");
    }

    #[test]
    fn test_async_state_display_ready() {
        let state = AsyncState::Ready(42);
        assert_eq!(format!("{}", state), "Ready(42)");
    }

    #[test]
    fn test_async_state_display_error() {
        let state = AsyncState::<i32>::Error("error".to_string());
        assert_eq!(format!("{}", state), "Error(error)");
    }

    // Clone tests
    #[test]
    fn test_async_state_clone_ready() {
        let state1 = AsyncState::Ready(42);
        let state2 = state1.clone();
        assert_eq!(state2, AsyncState::Ready(42));
    }

    #[test]
    fn test_async_state_clone_error() {
        let state1: AsyncState<i32> = AsyncState::Error("error".to_string());
        let state2 = state1.clone();
        assert_eq!(state2, AsyncState::Error("error".to_string()));
    }

    // PartialEq tests
    #[test]
    fn test_async_state_partial_eq() {
        let state1 = AsyncState::Ready(42);
        let state2 = AsyncState::Ready(42);
        assert_eq!(state1, state2);
    }

    // use_async tests
    #[test]
    fn test_use_async() {
        let (state, trigger) = use_async(|| {
            std::thread::sleep(Duration::from_millis(50));
            Ok::<i32, String>(42)
        });

        // Initially idle
        assert!(state.get().is_idle());

        // Trigger the async operation
        trigger();

        // Wait for completion
        std::thread::sleep(Duration::from_millis(200));
        assert!(state.get().is_ready());
        assert_eq!(state.get().value(), Some(&42));
    }

    #[test]
    fn test_use_async_with_error() {
        let (state, trigger) = use_async(|| Err::<i32, String>("error".to_string()));

        trigger();
        std::thread::sleep(Duration::from_millis(100));

        assert!(state.get().is_error());
    }

    #[test]
    fn test_use_async_trigger_multiple() {
        let (state, trigger) = use_async(|| Ok::<i32, String>(42));

        trigger();
        trigger(); // Should trigger again

        // Wait for at least one to complete
        std::thread::sleep(Duration::from_millis(100));
        assert!(state.get().is_ready() || state.get().is_loading());
    }

    // use_async_poll tests
    #[test]
    fn test_use_async_poll() {
        let (state, start, poll) = use_async_poll(|| Ok::<i32, String>(42));

        assert!(state.get().is_idle());

        start();
        assert!(state.get().is_loading());

        // Poll until done
        for _ in 0..10 {
            if poll() {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }

        assert!(state.get().is_ready());
    }

    #[test]
    fn test_use_async_poll_returns_false_when_not_done() {
        let (_state, start, poll) = use_async_poll(|| {
            std::thread::sleep(Duration::from_millis(100));
            Ok::<i32, String>(42)
        });

        start();
        // First poll should return false (not done yet)
        assert!(!poll());
    }

    #[test]
    fn test_use_async_poll_with_error() {
        let (state, start, poll) = use_async_poll(|| Err::<i32, String>("error".to_string()));

        start();

        for _ in 0..10 {
            if poll() {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }

        assert!(state.get().is_error());
    }

    // use_async_immediate tests
    #[test]
    fn test_use_async_immediate() {
        let state = use_async_immediate(|| Ok::<i32, String>(42));

        // Wait for completion
        std::thread::sleep(Duration::from_millis(100));

        assert!(state.get().is_ready());
        assert_eq!(state.get().value(), Some(&42));
    }

    #[test]
    fn test_use_async_immediate_with_error() {
        let state = use_async_immediate(|| Err::<i32, String>("error".to_string()));

        std::thread::sleep(Duration::from_millis(100));

        assert!(state.get().is_error());
    }

    // AsyncResource tests
    #[test]
    fn test_async_resource_new() {
        let _resource = AsyncResource::new(|| Ok::<i32, String>(42));
        // Just verify it compiles
    }

    #[test]
    fn test_async_resource_build() {
        let resource = AsyncResource::new(|| Ok::<i32, String>(42));
        let (state, trigger) = resource.build();

        assert!(state.get().is_idle());
        trigger();
        std::thread::sleep(Duration::from_millis(100));
        assert!(state.get().is_ready());
    }

    // Different type tests
    #[test]
    fn test_async_state_with_string() {
        let state = AsyncState::Ready("hello".to_string());
        assert!(state.is_ready());
        assert_eq!(state.value(), Some(&"hello".to_string()));
    }

    #[test]
    fn test_async_state_with_vec() {
        let state = AsyncState::Ready(vec![1, 2, 3]);
        assert!(state.is_ready());
        assert_eq!(state.value(), Some(&vec![1, 2, 3]));
    }

    #[test]
    fn test_async_state_map_string() {
        let state = AsyncState::Ready("hello".to_string());
        let mapped = state.map(|s| s.len());
        assert_eq!(mapped, AsyncState::Ready(5));
    }

    // Integration tests
    #[test]
    fn test_use_async_with_closure() {
        let value = Arc::new(AtomicI32::new(10));
        let value_clone = value.clone();

        let (state, trigger) = use_async(move || {
            std::thread::sleep(Duration::from_millis(50));
            // Return the current value after incrementing
            value_clone.fetch_add(1, Ordering::SeqCst);
            Ok::<i32, String>(value_clone.load(Ordering::SeqCst))
        });

        trigger();
        std::thread::sleep(Duration::from_millis(200));

        assert!(state.get().is_ready());
        // The atomic was incremented from 10 to 11
        assert_eq!(state.get().value(), Some(&11));
    }
}