ratatui-interact 0.5.3

Interactive TUI components for ratatui with focus management and mouse 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
//! Toast notification widget
//!
//! A transient notification popup that displays a message for a configurable duration.
//!
//! # Example
//!
//! ```rust
//! use ratatui_interact::components::{Toast, ToastState, ToastStyle};
//! use ratatui::layout::Rect;
//!
//! // Create state
//! let mut state = ToastState::new();
//!
//! // Show a toast for 3 seconds
//! state.show("File saved successfully!", 3000);
//!
//! // In your render function
//! if let Some(message) = state.get_message() {
//!     let toast = Toast::new(message).style(ToastStyle::Info);
//!     // render toast...
//! }
//!
//! // In your event loop, periodically clear expired toasts
//! state.clear_if_expired();
//! ```

use ratatui::{
    buffer::Buffer,
    layout::{Alignment, Rect},
    style::{Color, Style},
    widgets::{Block, Borders, Clear, Paragraph, Widget, Wrap},
};

/// Style variants for toast notifications
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ToastStyle {
    /// Default informational style (cyan border)
    #[default]
    Info,
    /// Success style (green border)
    Success,
    /// Warning style (yellow border)
    Warning,
    /// Error style (red border)
    Error,
}

impl ToastStyle {
    /// Get the border color for this style
    pub fn border_color(&self) -> Color {
        match self {
            ToastStyle::Info => Color::Cyan,
            ToastStyle::Success => Color::Green,
            ToastStyle::Warning => Color::Yellow,
            ToastStyle::Error => Color::Red,
        }
    }

    /// Get the border color for this style, derived from a theme palette.
    pub fn themed_border_color(&self, theme: &crate::theme::Theme) -> Color {
        let p = &theme.palette;
        match self {
            ToastStyle::Info => p.info,
            ToastStyle::Success => p.success,
            ToastStyle::Warning => p.warning,
            ToastStyle::Error => p.error,
        }
    }

    /// Auto-detect style from message content
    pub fn from_message(message: &str) -> Self {
        let lower = message.to_lowercase();
        if lower.contains("error") || lower.contains("fail") {
            ToastStyle::Error
        } else if lower.contains("warning") || lower.contains("warn") {
            ToastStyle::Warning
        } else if lower.contains("success") || lower.contains("saved") || lower.contains("done") {
            ToastStyle::Success
        } else {
            ToastStyle::Info
        }
    }
}

/// State for managing toast visibility and expiration
#[derive(Debug, Clone, Default)]
pub struct ToastState {
    /// Current message to display (if any)
    message: Option<String>,
    /// Expiration time (epoch milliseconds)
    expires_at: Option<i64>,
}

impl ToastState {
    /// Create a new toast state
    pub fn new() -> Self {
        Self::default()
    }

    /// Show a toast message for a specified duration (in milliseconds)
    pub fn show(&mut self, message: impl Into<String>, duration_ms: i64) {
        let now = Self::current_time_ms();
        self.message = Some(message.into());
        self.expires_at = Some(now + duration_ms);
    }

    /// Get the current message if the toast hasn't expired
    pub fn get_message(&self) -> Option<&str> {
        if let (Some(msg), Some(expires)) = (&self.message, self.expires_at) {
            let now = Self::current_time_ms();
            if now < expires {
                return Some(msg.as_str());
            }
        }
        None
    }

    /// Check if a toast is currently visible
    pub fn is_visible(&self) -> bool {
        self.get_message().is_some()
    }

    /// Clear the toast if it has expired
    pub fn clear_if_expired(&mut self) {
        if let Some(expires) = self.expires_at {
            let now = Self::current_time_ms();
            if now >= expires {
                self.message = None;
                self.expires_at = None;
            }
        }
    }

    /// Force clear the toast immediately
    pub fn clear(&mut self) {
        self.message = None;
        self.expires_at = None;
    }

    /// Get current time in milliseconds since epoch
    fn current_time_ms() -> i64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0)
    }
}

/// Toast notification widget
///
/// Renders a centered popup with the given message.
#[derive(Debug, Clone)]
pub struct Toast<'a> {
    message: &'a str,
    style: ToastStyle,
    auto_style: bool,
    max_width: u16,
    max_height: u16,
    top_offset: u16,
}

impl<'a> Toast<'a> {
    /// Create a new toast with the given message
    pub fn new(message: &'a str) -> Self {
        Self {
            message,
            style: ToastStyle::Info,
            auto_style: true,
            max_width: 80,
            max_height: 8,
            top_offset: 3,
        }
    }

    /// Set the toast style
    ///
    /// This disables auto-style detection.
    pub fn style(mut self, style: ToastStyle) -> Self {
        self.style = style;
        self.auto_style = false;
        self
    }

    /// Enable auto-style detection from message content
    pub fn auto_style(mut self) -> Self {
        self.auto_style = true;
        self
    }

    /// Set the maximum width of the toast
    pub fn max_width(mut self, width: u16) -> Self {
        self.max_width = width;
        self
    }

    /// Set the maximum height of the toast
    pub fn max_height(mut self, height: u16) -> Self {
        self.max_height = height;
        self
    }

    /// Set the offset from the top of the area
    pub fn top_offset(mut self, offset: u16) -> Self {
        self.top_offset = offset;
        self
    }

    /// Calculate the toast area centered within the given area
    pub fn calculate_area(&self, area: Rect) -> Rect {
        // Calculate toast dimensions
        let max_content_width = (area.width as usize)
            .saturating_sub(8)
            .min(self.max_width as usize);
        let content_width = self.message.len() + 4; // padding
        let toast_width = content_width.min(max_content_width).max(20) as u16;

        // Calculate height based on text wrapping
        let inner_width = toast_width.saturating_sub(2) as usize; // account for borders
        let lines_needed = (self.message.len() + inner_width - 1) / inner_width.max(1);
        let toast_height = (lines_needed as u16 + 2).min(self.max_height); // +2 for borders

        // Center horizontally and position from top
        let x = area.x + (area.width.saturating_sub(toast_width)) / 2;
        let y = area.y
            + self
                .top_offset
                .min(area.height.saturating_sub(toast_height));

        Rect::new(x, y, toast_width, toast_height)
    }

    /// Render the toast, clearing the area behind it
    ///
    /// This is the preferred method as it ensures the toast appears on top.
    pub fn render_with_clear(self, area: Rect, buf: &mut Buffer) {
        let toast_area = self.calculate_area(area);

        // Clear the area behind the toast
        Clear.render(toast_area, buf);

        // Render the toast
        self.render_in_area(toast_area, buf);
    }

    /// Render the toast in a specific pre-calculated area
    fn render_in_area(self, area: Rect, buf: &mut Buffer) {
        let border_color = if self.auto_style {
            ToastStyle::from_message(self.message).border_color()
        } else {
            self.style.border_color()
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(border_color))
            .style(Style::default().bg(Color::Black));

        let paragraph = Paragraph::new(self.message)
            .block(block)
            .wrap(Wrap { trim: true })
            .alignment(Alignment::Left)
            .style(Style::default().fg(Color::White));

        paragraph.render(area, buf);
    }
}

impl Widget for Toast<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        // When used as a Widget directly, render in the given area
        // For proper centering, use render_with_clear instead
        self.render_in_area(area, buf);
    }
}

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

    #[test]
    fn test_toast_state_new() {
        let state = ToastState::new();
        assert!(state.message.is_none());
        assert!(state.expires_at.is_none());
    }

    #[test]
    fn test_toast_state_lifecycle() {
        let mut state = ToastState::new();

        // Initially no message
        assert!(state.get_message().is_none());
        assert!(!state.is_visible());

        // Show a toast with very long duration
        state.show("Test message", 100_000);
        assert!(state.is_visible());
        assert_eq!(state.get_message(), Some("Test message"));

        // Force clear
        state.clear();
        assert!(!state.is_visible());
    }

    #[test]
    fn test_toast_show_replaces_existing() {
        let mut state = ToastState::new();

        state.show("First message", 100_000);
        assert_eq!(state.get_message(), Some("First message"));

        state.show("Second message", 100_000);
        assert_eq!(state.get_message(), Some("Second message"));
    }

    #[test]
    fn test_toast_clear_if_expired() {
        let mut state = ToastState::new();

        // Show toast that expires immediately (duration 0)
        state.show("Quick message", 0);
        std::thread::sleep(std::time::Duration::from_millis(10));

        state.clear_if_expired();
        assert!(!state.is_visible());
    }

    #[test]
    fn test_toast_style_detection() {
        assert_eq!(
            ToastStyle::from_message("error occurred"),
            ToastStyle::Error
        );
        assert_eq!(ToastStyle::from_message("File saved"), ToastStyle::Success);
        assert_eq!(
            ToastStyle::from_message("Warning: low disk"),
            ToastStyle::Warning
        );
        assert_eq!(ToastStyle::from_message("Hello world"), ToastStyle::Info);
    }

    #[test]
    fn test_toast_style_detection_case_insensitive() {
        assert_eq!(
            ToastStyle::from_message("ERROR OCCURRED"),
            ToastStyle::Error
        );
        assert_eq!(ToastStyle::from_message("FILE SAVED"), ToastStyle::Success);
        assert_eq!(ToastStyle::from_message("WARNING"), ToastStyle::Warning);
    }

    #[test]
    fn test_toast_style_detection_variants() {
        assert_eq!(
            ToastStyle::from_message("failed to load"),
            ToastStyle::Error
        );
        assert_eq!(
            ToastStyle::from_message("done processing"),
            ToastStyle::Success
        );
        assert_eq!(
            ToastStyle::from_message("warn: deprecated"),
            ToastStyle::Warning
        );
    }

    #[test]
    fn test_toast_style_colors() {
        assert_eq!(ToastStyle::Info.border_color(), Color::Cyan);
        assert_eq!(ToastStyle::Success.border_color(), Color::Green);
        assert_eq!(ToastStyle::Warning.border_color(), Color::Yellow);
        assert_eq!(ToastStyle::Error.border_color(), Color::Red);
    }

    #[test]
    fn test_toast_style_default() {
        let style = ToastStyle::default();
        assert_eq!(style, ToastStyle::Info);
    }

    #[test]
    fn test_toast_area_calculation() {
        let toast = Toast::new("Hello");
        let area = Rect::new(0, 0, 100, 50);
        let toast_area = toast.calculate_area(area);

        // Should be centered horizontally
        assert!(toast_area.x > 0);
        assert!(toast_area.x + toast_area.width <= area.width);

        // Should be near top
        assert_eq!(toast_area.y, 3); // default top_offset
    }

    #[test]
    fn test_toast_area_calculation_long_message() {
        let long_msg = "This is a very long message that should wrap to multiple lines";
        let toast = Toast::new(long_msg);
        let area = Rect::new(0, 0, 40, 20);
        let toast_area = toast.calculate_area(area);

        // Width should be constrained
        assert!(toast_area.width <= area.width);
    }

    #[test]
    fn test_toast_area_calculation_custom_offset() {
        let toast = Toast::new("Hello").top_offset(10);
        let area = Rect::new(0, 0, 100, 50);
        let toast_area = toast.calculate_area(area);

        assert_eq!(toast_area.y, 10);
    }

    #[test]
    fn test_toast_builder_methods() {
        let toast = Toast::new("Test")
            .style(ToastStyle::Error)
            .max_width(60)
            .max_height(5)
            .top_offset(5);

        assert_eq!(toast.style, ToastStyle::Error);
        assert_eq!(toast.max_width, 60);
        assert_eq!(toast.max_height, 5);
        assert_eq!(toast.top_offset, 5);
        assert!(!toast.auto_style); // auto_style disabled when style is set
    }

    #[test]
    fn test_toast_auto_style() {
        let toast = Toast::new("Test").auto_style();
        assert!(toast.auto_style);
    }

    #[test]
    fn test_toast_render() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 60, 20));
        let toast = Toast::new("Test toast message");

        toast.render_with_clear(Rect::new(0, 0, 60, 20), &mut buf);

        // Check that something was rendered (borders at least)
        // The toast should contain the message text
        let content: String = buf.content.iter().map(|c| c.symbol()).collect();
        assert!(content.contains("Test"));
    }

    #[test]
    fn test_toast_render_with_style() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 60, 20));
        let toast = Toast::new("Success!").style(ToastStyle::Success);

        toast.render_with_clear(Rect::new(0, 0, 60, 20), &mut buf);

        let content: String = buf.content.iter().map(|c| c.symbol()).collect();
        assert!(content.contains("Success"));
    }

    #[test]
    fn test_toast_widget_render() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 5));
        let toast = Toast::new("Widget test");
        let area = Rect::new(0, 0, 30, 5);

        toast.render(area, &mut buf);
        // Should not panic
    }
}