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
//! Async operation patterns using mpsc channels
//!
//! Provides patterns for handling background operations in TUI apps.
//! Uses standard library threads and channels (no async runtime needed).
//!
//! # Example
//!
//! ```ignore
//! use revue::patterns::AsyncTask;
//! use std::thread;
//!
//! struct App {
//!     items: Vec<Item>,
//!     loading: bool,
//!     fetch_task: Option<AsyncTask<Vec<Item>>>,
//! }
//!
//! impl App {
//!     fn start_fetch(&mut self) {
//!         let client = self.client.clone();
//!         let task = AsyncTask::spawn(move || {
//!             client.fetch_items()
//!         });
//!
//!         self.fetch_task = Some(task);
//!         self.loading = true;
//!     }
//!
//!     fn poll(&mut self) -> bool {
//!         let mut needs_redraw = false;
//!
//!         if let Some(task) = &mut self.fetch_task {
//!             if let Some(result) = task.try_recv() {
//!                 match result {
//!                     Ok(items) => self.items = items,
//!                     Err(e) => self.message.set(format!("Error: {}", e)),
//!                 }
//!                 self.fetch_task = None;
//!                 self.loading = false;
//!                 needs_redraw = true;
//!             }
//!         }
//!
//!         needs_redraw
//!     }
//! }
//! ```

use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
use std::thread::{self, JoinHandle};

/// Async task with non-blocking result polling
///
/// Wraps a background thread operation with a channel receiver.
/// Call `try_recv()` in your poll/animation loop to check for results.
pub struct AsyncTask<T> {
    rx: Receiver<T>,
    handle: Option<JoinHandle<()>>,
}

impl<T: Send + 'static> AsyncTask<T> {
    /// Spawn a new background task
    ///
    /// # Example
    ///
    /// ```ignore
    /// let task = AsyncTask::spawn(|| {
    ///     // Heavy computation or I/O
    ///     fetch_data_from_api()
    /// });
    /// ```
    pub fn spawn<F>(f: F) -> Self
    where
        F: FnOnce() -> T + Send + 'static,
    {
        let (tx, rx) = mpsc::channel();
        let handle = thread::spawn(move || {
            let result = f();
            let _ = tx.send(result);
        });

        Self {
            rx,
            handle: Some(handle),
        }
    }

    /// Try to receive result (non-blocking)
    ///
    /// Returns `Some(result)` if task completed, `None` otherwise.
    ///
    /// # Example
    ///
    /// ```ignore
    /// if let Some(result) = task.try_recv() {
    ///     // Task completed!
    ///     self.handle_result(result);
    /// }
    /// ```
    pub fn try_recv(&mut self) -> Option<T> {
        match self.rx.try_recv() {
            Ok(result) => Some(result),
            Err(TryRecvError::Empty) => None,
            Err(TryRecvError::Disconnected) => None,
        }
    }

    /// Check if task is still running
    pub fn is_running(&self) -> bool {
        matches!(self.rx.try_recv(), Err(TryRecvError::Empty))
    }

    /// Wait for task to complete (blocking)
    ///
    /// Only use this if you know the task will complete quickly.
    pub fn wait(self) -> Option<T> {
        self.rx.recv().ok()
    }

    /// Cancel the task
    ///
    /// Drops the receiver, which will cause the sender to fail.
    /// The background thread will continue until it tries to send.
    pub fn cancel(mut self) {
        drop(self.rx);
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

// Removed AsyncPoller trait - just implement poll() directly in your App

/// Spinner frames for loading indicators
pub const SPINNER_FRAMES: &[&str] = &["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"];

/// Get spinner character for current frame
///
/// # Example
///
/// ```ignore
/// let frame = self.spinner_frame;
/// let spinner = spinner_char(frame);
/// ctx.draw_text(x, y, spinner, CYAN);
/// ```
pub fn spinner_char(frame: usize) -> &'static str {
    SPINNER_FRAMES[frame % SPINNER_FRAMES.len()]
}

/// Helper to run a function in background and get a channel
///
/// Returns `(Receiver, JoinHandle)` for manual management.
///
/// # Example
///
/// ```ignore
/// let (rx, handle) = spawn_task(|| fetch_data());
/// ```
pub fn spawn_task<T, F>(f: F) -> (Receiver<T>, JoinHandle<()>)
where
    T: Send + 'static,
    F: FnOnce() -> T + Send + 'static,
{
    let (tx, rx) = mpsc::channel();
    let handle = thread::spawn(move || {
        let result = f();
        let _ = tx.send(result);
    });
    (rx, handle)
}

/// Helper for spawning task with sender access
///
/// Useful when you need to send multiple updates.
///
/// # Example
///
/// ```ignore
/// let rx = spawn_with_sender(|tx| {
///     for i in 0..10 {
///         tx.send(i).unwrap();
///         thread::sleep(Duration::from_millis(100));
///     }
/// });
/// ```
pub fn spawn_with_sender<T, F>(f: F) -> Receiver<T>
where
    T: Send + 'static,
    F: FnOnce(Sender<T>) + Send + 'static,
{
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        f(tx);
    });
    rx
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    // AsyncTask tests
    #[test]
    fn test_async_task_spawn_and_wait() {
        let task = AsyncTask::spawn(|| 42);
        assert_eq!(task.wait(), Some(42));
    }

    #[test]
    fn test_async_task_spawn_string() {
        let task = AsyncTask::spawn(|| "hello".to_string());
        assert_eq!(task.wait(), Some("hello".to_string()));
    }

    #[test]
    fn test_async_task_spawn_vec() {
        let task = AsyncTask::spawn(|| vec![1, 2, 3]);
        assert_eq!(task.wait(), Some(vec![1, 2, 3]));
    }

    #[test]
    fn test_async_task_try_recv_completed() {
        let mut task = AsyncTask::spawn(|| 42);
        // Wait for completion
        thread::sleep(Duration::from_millis(10));
        // May or may not be ready, but shouldn't panic
        let _ = task.try_recv();
    }

    #[test]
    fn test_async_task_cancel() {
        let task = AsyncTask::spawn(|| {
            thread::sleep(Duration::from_millis(1000));
            42
        });
        // Cancel should not panic
        task.cancel();
    }

    #[test]
    fn test_async_task_timing() {
        let task = AsyncTask::spawn(|| {
            thread::sleep(Duration::from_millis(5));
            42
        });

        // Poll with timeout instead of fixed sleep
        let mut task = task;
        let mut result = None;
        for _ in 0..100 {
            if let Some(r) = task.try_recv() {
                result = Some(r);
                break;
            }
            thread::sleep(Duration::from_millis(10));
        }

        assert_eq!(result, Some(42));
    }

    #[test]
    fn test_async_task_is_running() {
        use std::sync::{Arc, Barrier};

        // Two barriers: one to signal task started, one to signal task can finish
        let started = Arc::new(Barrier::new(2));
        let finish = Arc::new(Barrier::new(2));
        let started_clone = started.clone();
        let finish_clone = finish.clone();

        let task = AsyncTask::spawn(move || {
            started_clone.wait(); // Signal: task has started
            finish_clone.wait(); // Wait: main thread allows finish
            42
        });

        // Wait until task has started
        started.wait();

        // Now task is blocked at finish barrier, so it's definitely running
        assert!(task.is_running(), "Task should be running while blocked");

        // Allow task to finish
        finish.wait();

        // Wait for completion deterministically
        let result = task.wait();
        assert_eq!(result, Some(42));
    }

    // Spinner tests
    #[test]
    fn test_spinner_frames_count() {
        assert_eq!(SPINNER_FRAMES.len(), 8);
    }

    #[test]
    fn test_spinner_char_first() {
        assert_eq!(spinner_char(0), "⣾");
    }

    #[test]
    fn test_spinner_char_second() {
        assert_eq!(spinner_char(1), "⣽");
    }

    #[test]
    fn test_spinner_char_all_frames() {
        assert_eq!(spinner_char(0), "⣾");
        assert_eq!(spinner_char(1), "⣽");
        assert_eq!(spinner_char(2), "⣻");
        assert_eq!(spinner_char(3), "⢿");
        assert_eq!(spinner_char(4), "â¡¿");
        assert_eq!(spinner_char(5), "⣟");
        assert_eq!(spinner_char(6), "⣯");
        assert_eq!(spinner_char(7), "⣷");
    }

    #[test]
    fn test_spinner_char_wraps() {
        assert_eq!(spinner_char(8), "⣾"); // wraps to 0
        assert_eq!(spinner_char(9), "⣽"); // wraps to 1
        assert_eq!(spinner_char(16), "⣾"); // wraps to 0
    }

    #[test]
    fn test_spinner_char_large_number() {
        // Should not panic with large frame numbers
        let _ = spinner_char(1000);
        let _ = spinner_char(usize::MAX);
    }

    // spawn_task tests
    #[test]
    fn test_spawn_task_int() {
        let (rx, handle) = spawn_task(|| 42);
        assert_eq!(rx.recv().unwrap(), 42);
        handle.join().unwrap();
    }

    #[test]
    fn test_spawn_task_string() {
        let (rx, handle) = spawn_task(|| "result".to_string());
        assert_eq!(rx.recv().unwrap(), "result");
        handle.join().unwrap();
    }

    #[test]
    fn test_spawn_task_result() {
        let (rx, handle) = spawn_task(|| -> Result<i32, &str> { Ok(42) });
        assert_eq!(rx.recv().unwrap(), Ok(42));
        handle.join().unwrap();
    }

    #[test]
    fn test_spawn_task_computation() {
        let (rx, _) = spawn_task(|| {
            let mut sum = 0;
            for i in 0..100 {
                sum += i;
            }
            sum
        });
        assert_eq!(rx.recv().unwrap(), 4950);
    }

    // spawn_with_sender tests
    #[test]
    fn test_spawn_with_sender_single() {
        let rx = spawn_with_sender(|tx| {
            tx.send(42).unwrap();
        });
        assert_eq!(rx.recv().unwrap(), 42);
    }

    #[test]
    fn test_spawn_with_sender_multiple() {
        let rx = spawn_with_sender(|tx| {
            tx.send(1).unwrap();
            tx.send(2).unwrap();
            tx.send(3).unwrap();
        });

        assert_eq!(rx.recv().unwrap(), 1);
        assert_eq!(rx.recv().unwrap(), 2);
        assert_eq!(rx.recv().unwrap(), 3);
    }

    #[test]
    fn test_spawn_with_sender_collect() {
        let rx = spawn_with_sender(|tx| {
            for i in 0..5 {
                tx.send(i).unwrap();
            }
        });

        let results: Vec<i32> = rx.iter().collect();
        assert_eq!(results, vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_spawn_with_sender_strings() {
        let rx = spawn_with_sender(|tx| {
            tx.send("hello".to_string()).unwrap();
            tx.send("world".to_string()).unwrap();
        });

        assert_eq!(rx.recv().unwrap(), "hello");
        assert_eq!(rx.recv().unwrap(), "world");
    }

    #[test]
    fn test_spawn_with_sender_channel_closes() {
        let rx = spawn_with_sender(|tx| {
            tx.send(1).unwrap();
            // Channel closes when tx is dropped
        });

        assert_eq!(rx.recv().unwrap(), 1);
        // After sender is dropped, recv returns error
        assert!(rx.recv().is_err());
    }
}