rpi-tui 0.3.2

Terminal User Interface for pi-rust
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
//! Loader component - loading indicator.
//!
//! Provides a visual loading indicator for TUI.

use std::any::Any;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use super::component::Component;

/// Canonical working-spinner frames, in order.
///
/// Shared by [`Loader`] and the editor's working indicator so both animate
/// identically. Mirrors native pi's `DEFAULT_FRAMES`.
///
/// [`Loader`]: crate::loader::Loader
pub const SPINNER_FRAMES: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];

/// Frame interval for animated indicators. Mirrors native pi's
/// `DEFAULT_INTERVAL_MS`: one frame per 80 ms, i.e. a full 10-frame cycle every
/// 800 ms.
pub const SPINNER_FRAME_MS: u64 = 80;

/// Loader indicator options.
#[derive(Debug, Clone)]
pub struct LoaderIndicatorOptions {
    /// Characters to cycle through for the spinner.
    pub spinner_chars: Vec<char>,
    /// Animation frame duration.
    pub frame_duration_ms: u64,
    /// Text to display next to the spinner.
    pub text: Option<String>,
}

impl Default for LoaderIndicatorOptions {
    fn default() -> Self {
        Self {
            spinner_chars: SPINNER_FRAMES.to_vec(),
            frame_duration_ms: SPINNER_FRAME_MS,
            text: None,
        }
    }
}

/// Loader component.
pub struct Loader {
    options: LoaderIndicatorOptions,
    frame: Mutex<usize>,
    start_time: Mutex<Option<Instant>>,
    running: Mutex<bool>,
}

impl Loader {
    /// Create a new loader.
    pub fn new() -> Self {
        Self {
            options: LoaderIndicatorOptions::default(),
            frame: Mutex::new(0),
            start_time: Mutex::new(None),
            running: Mutex::new(false),
        }
    }

    /// Create a loader with options.
    pub fn with_options(options: LoaderIndicatorOptions) -> Self {
        Self {
            options,
            frame: Mutex::new(0),
            start_time: Mutex::new(None),
            running: Mutex::new(false),
        }
    }

    /// Create a loader with text.
    pub fn with_text(text: &str) -> Self {
        let mut options = LoaderIndicatorOptions::default();
        options.text = Some(text.to_string());
        Self::with_options(options)
    }

    /// Start the loader animation.
    pub fn start(&self) {
        if let Ok(mut running) = self.running.lock() {
            *running = true;
        }
        if let Ok(mut start_time) = self.start_time.lock() {
            *start_time = Some(Instant::now());
        }
    }

    /// Stop the loader animation.
    pub fn stop(&self) {
        if let Ok(mut running) = self.running.lock() {
            *running = false;
        }
    }

    /// Check if the loader is running.
    pub fn is_running(&self) -> bool {
        *self.running.lock().unwrap()
    }

    /// Get the elapsed time since the loader started.
    pub fn elapsed(&self) -> Duration {
        self.start_time
            .lock()
            .ok()
            .and_then(|t| t.map(|s| s.elapsed()))
            .unwrap_or_default()
    }

    /// Advance to the next frame.
    pub fn advance(&self) {
        if let Ok(mut frame) = self.frame.lock() {
            *frame = (*frame + 1) % self.options.spinner_chars.len();
        }
    }

    /// Get the current spinner character.
    fn current_char(&self) -> char {
        let frame = *self.frame.lock().unwrap();
        self.options
            .spinner_chars
            .get(frame)
            .copied()
            .unwrap_or('⠋')
    }

    /// Set the text.
    pub fn set_text(&mut self, text: &str) {
        self.options.text = Some(text.to_string());
    }

    /// Clear the text.
    pub fn clear_text(&mut self) {
        self.options.text = None;
    }
}

impl Default for Loader {
    fn default() -> Self {
        Self::new()
    }
}

impl Component for Loader {
    fn render(&self, width: usize) -> Vec<String> {
        let spinner = self.current_char();
        let text = self.options.text.clone().unwrap_or_default();

        let elapsed = self.elapsed();
        let seconds = elapsed.as_secs();
        let minutes = seconds / 60;
        let secs = seconds % 60;

        let time_str = if minutes > 0 {
            format!("{}m {}s", minutes, secs)
        } else {
            format!("{}s", secs)
        };

        let line = if text.is_empty() {
            format!("\x1b[36m{}\x1b[0m \x1b[90m{}\x1b[0m", spinner, time_str)
        } else {
            let text_width = crate::utils::visible_width(&text);
            let max_text_width = width.saturating_sub(15); // Reserve space for spinner and time
            let display_text = if text_width > max_text_width {
                crate::utils::truncate_to_width(&text, max_text_width, "...")
            } else {
                text
            };
            format!(
                "\x1b[36m{}\x1b[0m \x1b[1m{}\x1b[0m \x1b[90m{}\x1b[0m",
                spinner, display_text, time_str
            )
        };

        // Advance frame for next render
        self.advance();

        vec![line]
    }

    fn invalidate(&self) {
        // No cached state
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Cancellable loader with a cancel callback.
pub struct CancellableLoader {
    loader: Loader,
    on_cancel: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
}

impl CancellableLoader {
    /// Create a new cancellable loader.
    pub fn new() -> Self {
        Self {
            loader: Loader::new(),
            on_cancel: Mutex::new(None),
        }
    }

    /// Create with text.
    pub fn with_text(text: &str) -> Self {
        Self {
            loader: Loader::with_text(text),
            on_cancel: Mutex::new(None),
        }
    }

    /// Set cancel callback.
    pub fn on_cancel(&self, callback: Arc<dyn Fn() + Send + Sync>) {
        if let Ok(mut cb) = self.on_cancel.lock() {
            *cb = Some(callback);
        }
    }

    /// Cancel the loader.
    pub fn cancel(&self) {
        self.loader.stop();

        if let Ok(cb) = self.on_cancel.lock() {
            if let Some(callback) = cb.as_ref() {
                callback();
            }
        }
    }

    /// Start the loader.
    pub fn start(&self) {
        self.loader.start();
    }

    /// Stop the loader.
    pub fn stop(&self) {
        self.loader.stop();
    }

    /// Check if running.
    pub fn is_running(&self) -> bool {
        self.loader.is_running()
    }

    /// Set text.
    pub fn set_text(&mut self, text: &str) {
        self.loader.set_text(text);
    }
}

impl Default for CancellableLoader {
    fn default() -> Self {
        Self::new()
    }
}

impl Component for CancellableLoader {
    fn render(&self, width: usize) -> Vec<String> {
        let mut lines = self.loader.render(width);

        // Add cancel hint
        if self.is_running() {
            let hint = "\x1b[90mPress Ctrl+C to cancel\x1b[0m";
            lines.push(hint.to_string());
        }

        lines
    }

    fn invalidate(&self) {
        self.loader.invalidate();
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Progress loader with percentage.
pub struct ProgressLoader {
    loader: Loader,
    progress: Mutex<f32>, // 0.0 to 1.0
}

impl ProgressLoader {
    /// Create a new progress loader.
    pub fn new() -> Self {
        Self {
            loader: Loader::new(),
            progress: Mutex::new(0.0),
        }
    }

    /// Create with text.
    pub fn with_text(text: &str) -> Self {
        Self {
            loader: Loader::with_text(text),
            progress: Mutex::new(0.0),
        }
    }

    /// Set progress (0.0 to 1.0).
    pub fn set_progress(&self, progress: f32) {
        if let Ok(mut p) = self.progress.lock() {
            *p = progress.clamp(0.0, 1.0);
        }
    }

    /// Get progress.
    pub fn get_progress(&self) -> f32 {
        *self.progress.lock().unwrap()
    }

    /// Start the loader.
    pub fn start(&self) {
        self.loader.start();
    }

    /// Stop the loader.
    pub fn stop(&self) {
        self.loader.stop();
    }
}

impl Default for ProgressLoader {
    fn default() -> Self {
        Self::new()
    }
}

impl Component for ProgressLoader {
    fn render(&self, width: usize) -> Vec<String> {
        let progress = self.get_progress();
        let percent = (progress * 100.0) as usize;

        let spinner = self.loader.current_char();
        let text = self.loader.options.text.clone().unwrap_or_default();

        // Create progress bar
        let bar_width = width.saturating_sub(20).min(30);
        let filled = (bar_width as f32 * progress) as usize;
        let empty = bar_width - filled;

        let bar = format!(
            "\x1b[36m{}\x1b[44m{}\x1b[40m{}\x1b[0m {}%",
            spinner,
            "█".repeat(filled),
            "░".repeat(empty),
            percent
        );

        let line = if text.is_empty() {
            bar
        } else {
            let text_display =
                crate::utils::truncate_to_width(&text, width.saturating_sub(bar_width + 5), "...");
            format!("{} {}", text_display, bar)
        };

        // Advance frame
        self.loader.advance();

        vec![line]
    }

    fn invalidate(&self) {
        self.loader.invalidate();
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

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

    #[test]
    fn test_loader_new() {
        let loader = Loader::new();
        assert!(!loader.is_running());
    }

    #[test]
    fn test_loader_start_stop() {
        let loader = Loader::new();
        loader.start();
        assert!(loader.is_running());
        loader.stop();
        assert!(!loader.is_running());
    }

    #[test]
    fn test_loader_render() {
        let loader = Loader::with_text("Loading...");
        loader.start();
        let lines = loader.render(40);
        assert!(!lines.is_empty());
        assert!(lines[0].contains("Loading"));
    }

    #[test]
    fn test_cancellable_loader() {
        let loader = CancellableLoader::new();
        let cancelled = Arc::new(Mutex::new(false));
        let cancelled_clone = cancelled.clone();

        loader.on_cancel(Arc::new(move || {
            *cancelled_clone.lock().unwrap() = true;
        }));

        loader.cancel();
        assert!(*cancelled.lock().unwrap());
    }

    #[test]
    fn test_progress_loader() {
        let loader = ProgressLoader::new();
        loader.set_progress(0.5);
        assert_eq!(loader.get_progress(), 0.5);
    }
}