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
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
//! A toast notification component for temporary messages.
//!
//! [`Toast`] provides non-modal notifications that appear as a vertical stack,
//! with severity levels and auto-dismiss support. State is stored in
//! [`ToastState`] and updated via [`ToastMessage`].
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Toast, ToastMessage, ToastState, ToastLevel, Component};
//!
//! // Create toast state with 3 second default duration
//! let mut state = ToastState::with_duration(3000);
//!
//! // Add toasts using convenience methods
//! state.info("Information message");
//! state.success("Operation completed!");
//! state.warning("Low disk space");
//! state.error("Connection failed");
//!
//! // Or via the Push message
//! Toast::update(&mut state, ToastMessage::Push {
//!     message: "Custom toast".into(),
//!     level: ToastLevel::Info,
//!     duration_ms: Some(5000),
//! });
//!
//! // Tick to advance time (call periodically from your app)
//! Toast::update(&mut state, ToastMessage::Tick(100));
//! ```

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};

use super::{Component, RenderContext};

/// Default maximum number of visible toasts.
const DEFAULT_MAX_VISIBLE: usize = 5;

/// Severity level for toast notifications.
///
/// Each level has a distinct color for visual differentiation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum ToastLevel {
    /// General information (blue).
    #[default]
    Info,
    /// Successful operation (green).
    Success,
    /// Warning message (yellow).
    Warning,
    /// Error message (red).
    Error,
}

/// A single toast notification.
///
/// Each toast has a unique ID, message, severity level, and optional
/// remaining duration for auto-dismiss.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct ToastItem {
    /// Unique identifier for this toast.
    id: u64,
    /// The toast message.
    message: String,
    /// Severity level.
    level: ToastLevel,
    /// Remaining duration in milliseconds (None = persistent).
    remaining_ms: Option<u64>,
}

impl ToastItem {
    /// Returns the toast's unique identifier.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::new();
    /// let id = state.info("Hello");
    /// assert_eq!(state.toasts()[0].id(), id);
    /// ```
    pub fn id(&self) -> u64 {
        self.id
    }

    /// Returns the toast message.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::new();
    /// state.info("Hello, world!");
    /// assert_eq!(state.toasts()[0].message(), "Hello, world!");
    /// ```
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Returns the severity level.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{ToastState, ToastLevel};
    ///
    /// let mut state = ToastState::new();
    /// state.error("Something went wrong");
    /// assert_eq!(state.toasts()[0].level(), ToastLevel::Error);
    /// ```
    pub fn level(&self) -> ToastLevel {
        self.level
    }

    /// Returns true if this toast is persistent (no auto-dismiss).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::new();
    /// state.info("Persistent toast");
    /// assert!(state.toasts()[0].is_persistent());
    /// ```
    pub fn is_persistent(&self) -> bool {
        self.remaining_ms.is_none()
    }

    /// Returns the remaining duration in milliseconds, if any.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::with_duration(5000);
    /// state.info("Timed toast");
    /// assert_eq!(state.toasts()[0].remaining_ms(), Some(5000));
    /// ```
    pub fn remaining_ms(&self) -> Option<u64> {
        self.remaining_ms
    }
}

/// Messages that can be sent to a Toast component.
#[derive(Clone, Debug, PartialEq)]
pub enum ToastMessage {
    /// Add a new toast with optional auto-dismiss duration.
    Push {
        /// The message to display.
        message: String,
        /// Severity level.
        level: ToastLevel,
        /// Duration in milliseconds (None = persistent).
        duration_ms: Option<u64>,
    },
    /// Dismiss a specific toast by ID.
    Dismiss(u64),
    /// Dismiss all toasts.
    Clear,
    /// Advance time by the given milliseconds (for auto-dismiss).
    Tick(u64),
}

/// Output messages from a Toast component.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ToastOutput {
    /// A toast was added (returns ID).
    Added(u64),
    /// A toast was dismissed by user.
    Dismissed(u64),
    /// One or more toasts expired (auto-dismissed) in a single tick.
    Expired(Vec<u64>),
    /// All toasts were cleared.
    Cleared,
}

/// State for a Toast component.
///
/// Manages a collection of toast notifications with support for
/// auto-dismiss, manual dismiss, and configurable limits.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct ToastState {
    /// Active toasts.
    toasts: Vec<ToastItem>,
    /// Counter for generating unique IDs.
    next_id: u64,
    /// Default duration for new toasts (ms).
    default_duration_ms: Option<u64>,
    /// Maximum number of visible toasts.
    max_visible: usize,
}

impl Default for ToastState {
    fn default() -> Self {
        Self {
            toasts: Vec::new(),
            next_id: 0,
            default_duration_ms: None,
            max_visible: DEFAULT_MAX_VISIBLE,
        }
    }
}

impl ToastState {
    /// Creates a new toast state with default settings.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let state = ToastState::new();
    /// assert!(state.is_empty());
    /// assert_eq!(state.default_duration(), None);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a toast state with a default duration for new toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let state = ToastState::with_duration(3000);
    /// assert_eq!(state.default_duration(), Some(3000));
    /// ```
    pub fn with_duration(duration_ms: u64) -> Self {
        Self {
            default_duration_ms: Some(duration_ms),
            ..Self::default()
        }
    }

    /// Creates a toast state with a custom maximum visible toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let state = ToastState::with_max_visible(3);
    /// assert_eq!(state.max_visible(), 3);
    /// ```
    pub fn with_max_visible(max: usize) -> Self {
        Self {
            max_visible: max,
            ..Self::default()
        }
    }

    /// Returns all active toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::new();
    /// state.info("First");
    /// state.error("Second");
    /// assert_eq!(state.toasts().len(), 2);
    /// ```
    pub fn toasts(&self) -> &[ToastItem] {
        &self.toasts
    }

    /// Returns the number of active toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::new();
    /// assert_eq!(state.len(), 0);
    /// state.info("Hello");
    /// assert_eq!(state.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.toasts.len()
    }

    /// Returns true if there are no active toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::new();
    /// assert!(state.is_empty());
    /// state.success("Done!");
    /// assert!(!state.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.toasts.is_empty()
    }

    /// Returns the default duration for new toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let state = ToastState::new();
    /// assert_eq!(state.default_duration(), None);
    /// ```
    pub fn default_duration(&self) -> Option<u64> {
        self.default_duration_ms
    }

    /// Returns the maximum number of visible toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let state = ToastState::new();
    /// assert_eq!(state.max_visible(), 5);
    /// ```
    pub fn max_visible(&self) -> usize {
        self.max_visible
    }

    /// Sets the default duration for new toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::new();
    /// state.set_default_duration(Some(2000));
    /// assert_eq!(state.default_duration(), Some(2000));
    /// ```
    pub fn set_default_duration(&mut self, duration_ms: Option<u64>) {
        self.default_duration_ms = duration_ms;
    }

    /// Sets the maximum number of visible toasts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ToastState;
    ///
    /// let mut state = ToastState::new();
    /// state.set_max_visible(3);
    /// assert_eq!(state.max_visible(), 3);
    /// ```
    pub fn set_max_visible(&mut self, max: usize) {
        self.max_visible = max;
    }

    /// Internal method to add a toast.
    fn push(&mut self, message: String, level: ToastLevel, duration_ms: Option<u64>) -> u64 {
        let id = self.next_id;
        self.next_id += 1;

        // Use provided duration, or fall back to default
        let remaining_ms = match duration_ms {
            Some(d) => Some(d),
            None => self.default_duration_ms,
        };

        self.toasts.push(ToastItem {
            id,
            message,
            level,
            remaining_ms,
        });

        id
    }

    /// Adds an info toast and returns its ID.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{ToastState, ToastLevel};
    ///
    /// let mut state = ToastState::new();
    /// let id = state.info("Information message");
    /// assert_eq!(state.toasts()[0].level(), ToastLevel::Info);
    /// ```
    pub fn info(&mut self, message: impl Into<String>) -> u64 {
        self.push(message.into(), ToastLevel::Info, None)
    }

    /// Adds a success toast and returns its ID.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{ToastState, ToastLevel};
    ///
    /// let mut state = ToastState::new();
    /// let id = state.success("Operation completed!");
    /// assert_eq!(state.toasts()[0].level(), ToastLevel::Success);
    /// ```
    pub fn success(&mut self, message: impl Into<String>) -> u64 {
        self.push(message.into(), ToastLevel::Success, None)
    }

    /// Adds a warning toast and returns its ID.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{ToastState, ToastLevel};
    ///
    /// let mut state = ToastState::new();
    /// let id = state.warning("Low disk space");
    /// assert_eq!(state.toasts()[0].level(), ToastLevel::Warning);
    /// ```
    pub fn warning(&mut self, message: impl Into<String>) -> u64 {
        self.push(message.into(), ToastLevel::Warning, None)
    }

    /// Adds an error toast and returns its ID.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{ToastState, ToastLevel};
    ///
    /// let mut state = ToastState::new();
    /// let id = state.error("Connection failed");
    /// assert_eq!(state.toasts()[0].level(), ToastLevel::Error);
    /// ```
    pub fn error(&mut self, message: impl Into<String>) -> u64 {
        self.push(message.into(), ToastLevel::Error, None)
    }
}

/// A toast notification component.
///
/// `Toast` displays temporary notification messages in a vertical stack.
/// Toasts can have different severity levels and auto-dismiss after a
/// configurable duration.
///
/// # Timer Integration
///
/// The component uses a `Tick` message to track time. Your application
/// should send periodic `Tick(elapsed_ms)` messages (e.g., every 100ms)
/// to drive auto-dismiss functionality.
///
/// # Visual Format
///
/// Toasts render in the bottom-right corner, stacking upward:
/// ```text
///                                    ┌──────────────────────────────────┐
///                                    │ ✓ Operation completed!           │
///                                    └──────────────────────────────────┘
///                                    ┌──────────────────────────────────┐
///                                    │ ℹ Processing your request...     │
///                                    └──────────────────────────────────┘
/// ```
///
/// # Severity Levels
///
/// - `Info` - Blue border, ℹ prefix
/// - `Success` - Green border, ✓ prefix
/// - `Warning` - Yellow border, ⚠ prefix
/// - `Error` - Red border, ✗ prefix
///
/// # Example
///
/// ```rust
/// use envision::component::{Toast, ToastMessage, ToastOutput, ToastState, Component};
///
/// let mut state = ToastState::with_duration(3000);
///
/// // Add a success toast
/// let id = state.success("File saved!");
///
/// // Tick to advance time
/// let output = Toast::update(&mut state, ToastMessage::Tick(3000));
/// assert_eq!(output, Some(ToastOutput::Expired(vec![id])));
/// assert!(state.is_empty());
/// ```
pub struct Toast;

impl Component for Toast {
    type State = ToastState;
    type Message = ToastMessage;
    type Output = ToastOutput;

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

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            ToastMessage::Push {
                message,
                level,
                duration_ms,
            } => {
                let id = state.push(message, level, duration_ms);
                Some(ToastOutput::Added(id))
            }
            ToastMessage::Dismiss(id) => {
                let len_before = state.toasts.len();
                state.toasts.retain(|t| t.id != id);
                if state.toasts.len() < len_before {
                    Some(ToastOutput::Dismissed(id))
                } else {
                    None
                }
            }
            ToastMessage::Clear => {
                if state.toasts.is_empty() {
                    None
                } else {
                    state.toasts.clear();
                    Some(ToastOutput::Cleared)
                }
            }
            ToastMessage::Tick(elapsed_ms) => {
                let mut expired_ids = Vec::new();

                for toast in &mut state.toasts {
                    if let Some(remaining) = toast.remaining_ms.as_mut() {
                        if *remaining <= elapsed_ms {
                            expired_ids.push(toast.id);
                        } else {
                            *remaining -= elapsed_ms;
                        }
                    }
                }

                // Remove expired toasts
                state.toasts.retain(|t| !expired_ids.contains(&t.id));

                if expired_ids.is_empty() {
                    None
                } else {
                    Some(ToastOutput::Expired(expired_ids))
                }
            }
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        if state.toasts.is_empty() {
            return;
        }

        crate::annotation::with_registry(|reg| {
            reg.register(
                ctx.area,
                crate::annotation::Annotation::toast("toast")
                    .with_meta("count", state.toasts.len().to_string()),
            );
        });

        // Calculate toast dimensions
        let toast_width = 40.min(ctx.area.width);
        let toast_height = 3;
        let visible_count = state.toasts.len().min(state.max_visible);

        // Render from bottom-right corner, stacking upward
        // Newest toasts appear at the bottom
        for (i, toast) in state.toasts.iter().rev().take(visible_count).enumerate() {
            let y = ctx
                .area
                .bottom()
                .saturating_sub((i as u16 + 1) * toast_height);
            let x = ctx.area.right().saturating_sub(toast_width);

            if y < ctx.area.y {
                break; // Don't render above the ctx.area
            }

            let toast_area = Rect::new(x, y, toast_width, toast_height.min(ctx.area.bottom() - y));

            let (border_style, prefix) = match toast.level {
                ToastLevel::Info => (ctx.theme.info_style(), "i"),
                ToastLevel::Success => (ctx.theme.success_style(), "+"),
                ToastLevel::Warning => (ctx.theme.warning_style(), "!"),
                ToastLevel::Error => (ctx.theme.error_style(), "x"),
            };

            // Clear the ctx.area for overlay effect
            ctx.frame.render_widget(Clear, toast_area);

            let block = Block::default()
                .borders(Borders::ALL)
                .border_style(border_style);

            let text = format!("[{}] {}", prefix, toast.message);
            let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: true });

            ctx.frame.render_widget(paragraph, toast_area);
        }
    }
}

#[cfg(test)]
mod tests;