envision 0.16.0

A ratatui framework for collaborative TUI development with headless testing support
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
//! An indeterminate loading indicator component.
//!
//! [`Spinner`] provides a visual activity indicator that animates through frames
//! to show ongoing activity. This is a **display-only** component that does not
//! receive keyboard focus. State is stored in [`SpinnerState`] and updated via
//! [`SpinnerMessage`].
//!
//! See also [`ProgressBar`](super::ProgressBar) for determinate progress,
//! and [`MultiProgress`](super::MultiProgress) for tracking multiple tasks.
//!
//! # Animation Model
//!
//! The spinner does not animate itself - the parent application sends `Tick`
//! messages to advance the animation. This fits the TEA pattern where external
//! events drive state changes. Typical usage involves a timer subscription
//! sending Tick every 80-100ms.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Spinner, SpinnerMessage, SpinnerState, SpinnerStyle, Component};
//!
//! // Create a spinner with label
//! let mut state = SpinnerState::with_label("Loading...");
//! assert!(state.is_spinning());
//!
//! // Animate by sending Tick messages (typically from a timer)
//! Spinner::update(&mut state, SpinnerMessage::Tick);
//! let frame1 = state.current_frame();
//!
//! Spinner::update(&mut state, SpinnerMessage::Tick);
//! let frame2 = state.current_frame();
//!
//! assert_ne!(frame1, frame2); // Frame advanced
//!
//! // Stop/start the spinner
//! Spinner::update(&mut state, SpinnerMessage::Stop);
//! assert!(!state.is_spinning());
//! ```

use ratatui::widgets::Paragraph;

use super::{Component, RenderContext};

/// Built-in spinner animation styles.
///
/// Each style provides a sequence of characters that cycle to create
/// an animation effect.
///
/// # Example
///
/// ```rust
/// use envision::component::SpinnerStyle;
///
/// let style = SpinnerStyle::Dots;
/// assert_eq!(style.frames().len(), 10);
///
/// let style = SpinnerStyle::Line;
/// assert_eq!(style.frames().len(), 4);
///
/// let custom = SpinnerStyle::Custom(vec!['◯', '◔', '◑', '◕', '●']);
/// assert_eq!(custom.frames().len(), 5);
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum SpinnerStyle {
    /// Braille dots animation (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏).
    ///
    /// 10 frames, smooth circular motion.
    #[default]
    Dots,
    /// Classic line animation (|/-\\).
    ///
    /// 4 frames, ASCII-compatible.
    Line,
    /// Quarter circle animation (◐◓◑◒).
    ///
    /// 4 frames, rotating circle segments.
    Circle,
    /// Bouncing dot animation (⠁⠂⠄⠂).
    ///
    /// 4 frames, vertical bouncing effect.
    Bounce,
    /// Custom animation frames.
    ///
    /// Provide your own sequence of characters.
    Custom(Vec<char>),
}

impl SpinnerStyle {
    /// Returns the animation frames for this style.
    ///
    /// For `Custom` styles, returns the provided frames.
    /// For empty `Custom` styles, returns a single space character.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerStyle;
    ///
    /// assert_eq!(SpinnerStyle::Line.frames(), &['|', '/', '-', '\\']);
    /// ```
    pub fn frames(&self) -> &[char] {
        // Static arrays for built-in styles
        const DOTS: &[char] = &['', '', '', '', '', '', '', '', '', ''];
        const LINE: &[char] = &['|', '/', '-', '\\'];
        const CIRCLE: &[char] = &['', '', '', ''];
        const BOUNCE: &[char] = &['', '', '', ''];
        const EMPTY: &[char] = &[' '];

        match self {
            SpinnerStyle::Dots => DOTS,
            SpinnerStyle::Line => LINE,
            SpinnerStyle::Circle => CIRCLE,
            SpinnerStyle::Bounce => BOUNCE,
            SpinnerStyle::Custom(frames) => {
                if frames.is_empty() {
                    EMPTY
                } else {
                    frames
                }
            }
        }
    }

    /// Returns the number of frames in this style.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerStyle;
    ///
    /// assert_eq!(SpinnerStyle::Line.frame_count(), 4);
    /// assert_eq!(SpinnerStyle::Dots.frame_count(), 10);
    /// ```
    pub fn frame_count(&self) -> usize {
        self.frames().len()
    }
}

/// Messages that can be sent to a Spinner.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpinnerMessage {
    /// Advance to the next animation frame.
    ///
    /// Only advances if the spinner is currently spinning.
    Tick,
    /// Start spinning (if stopped).
    Start,
    /// Stop spinning.
    Stop,
}

/// State for a Spinner component.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct SpinnerState {
    /// The animation style.
    style: SpinnerStyle,
    /// The current frame index.
    frame: usize,
    /// Whether the spinner is currently animating.
    spinning: bool,
    /// Optional label displayed next to the spinner.
    label: Option<String>,
    /// Whether the component is disabled.
    disabled: bool,
}

impl Default for SpinnerState {
    fn default() -> Self {
        Self {
            style: SpinnerStyle::default(),
            frame: 0,
            spinning: true,
            label: None,
            disabled: false,
        }
    }
}

impl SpinnerState {
    /// Creates a new spinning spinner with the default Dots style.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerState;
    ///
    /// let state = SpinnerState::new();
    /// assert!(state.is_spinning());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a spinner with the given style.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{SpinnerState, SpinnerStyle};
    ///
    /// let state = SpinnerState::with_style(SpinnerStyle::Line);
    /// assert_eq!(state.style(), &SpinnerStyle::Line);
    /// ```
    pub fn with_style(style: SpinnerStyle) -> Self {
        Self {
            style,
            ..Self::default()
        }
    }

    /// Creates a spinner with a label.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerState;
    ///
    /// let state = SpinnerState::with_label("Loading...");
    /// assert_eq!(state.label(), Some("Loading..."));
    /// ```
    pub fn with_label(label: impl Into<String>) -> Self {
        Self {
            label: Some(label.into()),
            ..Self::default()
        }
    }

    /// Returns the current frame character.
    ///
    /// This is the character that should be displayed for the current
    /// animation state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{Spinner, SpinnerMessage, SpinnerState, Component};
    ///
    /// let mut state = SpinnerState::new();
    /// let first = state.current_frame();
    /// Spinner::update(&mut state, SpinnerMessage::Tick);
    /// let second = state.current_frame();
    /// assert_ne!(first, second);
    /// ```
    pub fn current_frame(&self) -> char {
        let frames = self.style.frames();
        frames[self.frame % frames.len()]
    }

    /// Returns true if the spinner is currently spinning.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{Spinner, SpinnerMessage, SpinnerState, Component};
    ///
    /// let mut state = SpinnerState::new();
    /// assert!(state.is_spinning());
    /// Spinner::update(&mut state, SpinnerMessage::Stop);
    /// assert!(!state.is_spinning());
    /// ```
    pub fn is_spinning(&self) -> bool {
        self.spinning
    }

    /// Sets whether the spinner is spinning.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerState;
    ///
    /// let mut state = SpinnerState::new();
    /// state.set_spinning(false);
    /// assert!(!state.is_spinning());
    /// ```
    pub fn set_spinning(&mut self, spinning: bool) {
        self.spinning = spinning;
    }

    /// Returns the label if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerState;
    ///
    /// let state = SpinnerState::with_label("Uploading...");
    /// assert_eq!(state.label(), Some("Uploading..."));
    /// ```
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// Sets the label.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerState;
    ///
    /// let mut state = SpinnerState::new();
    /// state.set_label(Some("Processing...".to_string()));
    /// assert_eq!(state.label(), Some("Processing..."));
    /// ```
    pub fn set_label(&mut self, label: Option<String>) {
        self.label = label;
    }

    /// Returns the spinner style.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{SpinnerState, SpinnerStyle};
    ///
    /// let state = SpinnerState::with_style(SpinnerStyle::Circle);
    /// assert_eq!(state.style(), &SpinnerStyle::Circle);
    /// ```
    pub fn style(&self) -> &SpinnerStyle {
        &self.style
    }

    /// Sets the spinner style.
    ///
    /// This resets the frame index to 0.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{SpinnerState, SpinnerStyle};
    ///
    /// let mut state = SpinnerState::new();
    /// state.set_style(SpinnerStyle::Bounce);
    /// assert_eq!(state.style(), &SpinnerStyle::Bounce);
    /// assert_eq!(state.frame_index(), 0);
    /// ```
    pub fn set_style(&mut self, style: SpinnerStyle) {
        self.style = style;
        self.frame = 0;
    }

    /// Returns the current frame index.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{Spinner, SpinnerMessage, SpinnerState, Component};
    ///
    /// let mut state = SpinnerState::new();
    /// assert_eq!(state.frame_index(), 0);
    /// Spinner::update(&mut state, SpinnerMessage::Tick);
    /// assert_eq!(state.frame_index(), 1);
    /// ```
    pub fn frame_index(&self) -> usize {
        self.frame
    }

    /// Returns true if the spinner is disabled.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerState;
    ///
    /// let state = SpinnerState::new();
    /// assert!(!state.is_disabled());
    /// ```
    pub fn is_disabled(&self) -> bool {
        self.disabled
    }

    /// Sets the disabled state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerState;
    ///
    /// let mut state = SpinnerState::new();
    /// state.set_disabled(true);
    /// assert!(state.is_disabled());
    /// ```
    pub fn set_disabled(&mut self, disabled: bool) {
        self.disabled = disabled;
    }

    /// Sets the disabled state using builder pattern.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SpinnerState;
    ///
    /// let state = SpinnerState::new()
    ///     .with_disabled(true);
    /// assert!(state.is_disabled());
    /// ```
    pub fn with_disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

/// An indeterminate loading indicator component.
///
/// `Spinner` displays an animated indicator to show ongoing activity.
/// Unlike [`ProgressBar`](super::ProgressBar), it does not show specific
/// progress - just that something is happening.
///
/// # Animation
///
/// The spinner advances one frame each time it receives a `Tick` message.
/// Your application should send Tick messages at regular intervals
/// (typically every 80-100ms) to create smooth animation.
///
/// # Styles
///
/// Several built-in styles are available:
/// - `Dots`: Braille dots (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏) - default
/// - `Line`: Classic ASCII (|/-\\)
/// - `Circle`: Quarter circles (◐◓◑◒)
/// - `Bounce`: Bouncing dot (⠁⠂⠄⠂)
/// - `Custom`: Your own character sequence
///
/// # Example
///
/// ```rust
/// use envision::component::{Spinner, SpinnerMessage, SpinnerState, Component};
///
/// let mut state = SpinnerState::with_label("Processing...");
///
/// // In your app's update function, forward timer ticks:
/// Spinner::update(&mut state, SpinnerMessage::Tick);
///
/// // Stop when done:
/// Spinner::update(&mut state, SpinnerMessage::Stop);
/// ```
pub struct Spinner;

impl Component for Spinner {
    type State = SpinnerState;
    type Message = SpinnerMessage;
    type Output = ();

    fn init() -> Self::State {
        SpinnerState::default()
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            SpinnerMessage::Tick => {
                if state.spinning {
                    let frame_count = state.style.frame_count();
                    state.frame = (state.frame + 1) % frame_count;
                }
            }
            SpinnerMessage::Start => {
                state.spinning = true;
            }
            SpinnerMessage::Stop => {
                state.spinning = false;
            }
        }
        None
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        let spinner_char = if state.spinning {
            state.current_frame().to_string()
        } else {
            " ".to_string()
        };

        let text = match &state.label {
            Some(label) => format!("{} {}", spinner_char, label),
            None => spinner_char,
        };

        let paragraph = Paragraph::new(text).style(ctx.theme.info_style());

        let annotation = crate::annotation::Annotation::spinner("spinner")
            .with_label(state.label.as_deref().unwrap_or(""));
        let annotated = crate::annotation::Annotate::new(paragraph, annotation);
        ctx.frame.render_widget(annotated, ctx.area);
    }
}

#[cfg(test)]
mod tests;