-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoast.rs
More file actions
635 lines (553 loc) · 18.3 KB
/
toast.rs
File metadata and controls
635 lines (553 loc) · 18.3 KB
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
625
626
627
628
629
630
631
632
633
634
635
//! Toast Notification System
//!
//! Provides temporary notification messages (success, warning, error, info)
//! displayed in configurable screen positions with auto-dismiss and fade animation.
//!
//! ## Usage
//!
//! ```ignore
//! use cortex_tui_components::toast::{Toast, ToastLevel, ToastManager, ToastWidget, ToastPosition};
//!
//! let mut manager = ToastManager::new()
//! .with_max_visible(5)
//! .with_position(ToastPosition::TopRight);
//!
//! manager.success("Session saved");
//! manager.warning("API rate limit warning");
//! manager.error("Connection failed");
//!
//! // In render loop:
//! manager.tick();
//! let widget = ToastWidget::new(&manager).terminal_size(width, height);
//! frame.render_widget(widget, area);
//! ```
use crate::color_scheme::ColorScheme;
use ratatui::prelude::*;
use ratatui::widgets::Widget;
use std::time::{Duration, Instant};
// ============================================================
// TOAST LEVEL
// ============================================================
/// The severity/type level of a toast notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ToastLevel {
/// Success notification - positive outcome
Success,
/// Info notification - informational message
#[default]
Info,
/// Warning notification - potential issue
Warning,
/// Error notification - failure or problem
Error,
}
impl ToastLevel {
/// Returns the ASCII icon for this toast level.
///
/// Icons are ASCII-only for terminal compatibility:
/// - Success: `[+]`
/// - Info: `[i]`
/// - Warning: `[!]`
/// - Error: `[x]`
pub fn icon(&self) -> &'static str {
match self {
ToastLevel::Success => "[+]",
ToastLevel::Info => "[i]",
ToastLevel::Warning => "[!]",
ToastLevel::Error => "[x]",
}
}
/// Returns the color associated with this toast level using the given color scheme.
pub fn color(&self, scheme: &ColorScheme) -> Color {
match self {
ToastLevel::Success => scheme.success,
ToastLevel::Info => scheme.info,
ToastLevel::Warning => scheme.warning,
ToastLevel::Error => scheme.error,
}
}
/// Returns the default display duration in milliseconds for this level.
///
/// More severe levels stay visible longer:
/// - Success: 3000ms
/// - Info: 4000ms
/// - Warning: 5000ms
/// - Error: 7000ms
pub fn default_duration_ms(&self) -> u64 {
match self {
ToastLevel::Success => 3000,
ToastLevel::Info => 4000,
ToastLevel::Warning => 5000,
ToastLevel::Error => 7000,
}
}
}
// ============================================================
// TOAST
// ============================================================
/// A single toast notification message.
///
/// Toasts have a level, message, creation time, and duration.
/// They can be persistent (never auto-dismiss) or fade out after their duration.
#[derive(Debug, Clone)]
pub struct Toast {
/// Unique identifier for this toast
pub id: u64,
/// Severity level of the toast
pub level: ToastLevel,
/// Message text to display
pub message: String,
/// When the toast was created
pub created_at: Instant,
/// How long the toast should be visible
pub duration: Duration,
/// If true, toast never auto-dismisses
pub persistent: bool,
/// Fade animation progress (0.0 = visible, 1.0 = fully faded)
pub fade_progress: f32,
}
impl Toast {
/// Creates a new toast with the given level and message.
///
/// The duration is set to the default for the level.
pub fn new(level: ToastLevel, message: impl Into<String>) -> Self {
Self {
id: 0, // Will be set by ToastManager
level,
message: message.into(),
created_at: Instant::now(),
duration: Duration::from_millis(level.default_duration_ms()),
persistent: false,
fade_progress: 0.0,
}
}
/// Creates a success toast.
pub fn success(message: impl Into<String>) -> Self {
Self::new(ToastLevel::Success, message)
}
/// Creates an info toast.
pub fn info(message: impl Into<String>) -> Self {
Self::new(ToastLevel::Info, message)
}
/// Creates a warning toast.
pub fn warning(message: impl Into<String>) -> Self {
Self::new(ToastLevel::Warning, message)
}
/// Creates an error toast.
pub fn error(message: impl Into<String>) -> Self {
Self::new(ToastLevel::Error, message)
}
/// Sets a custom duration for the toast.
pub fn with_duration(mut self, duration: Duration) -> Self {
self.duration = duration;
self
}
/// Makes the toast persistent (never auto-dismisses).
pub fn persistent(mut self) -> Self {
self.persistent = true;
self
}
/// Returns true if the toast has exceeded its display duration.
pub fn is_expired(&self) -> bool {
if self.persistent {
return false;
}
self.created_at.elapsed() >= self.duration
}
/// Returns the remaining time before the toast expires.
pub fn remaining(&self) -> Duration {
if self.persistent {
return Duration::MAX;
}
self.duration.saturating_sub(self.created_at.elapsed())
}
/// Updates the fade progress based on remaining time.
///
/// The fade animation occurs during the last 500ms of the toast's lifetime.
pub fn tick(&mut self) {
if self.persistent {
self.fade_progress = 0.0;
return;
}
let remaining = self.remaining();
let fade_duration = Duration::from_millis(500);
if remaining <= fade_duration {
let remaining_ms = remaining.as_millis() as f32;
let fade_ms = fade_duration.as_millis() as f32;
self.fade_progress = 1.0 - (remaining_ms / fade_ms);
} else {
self.fade_progress = 0.0;
}
}
}
// ============================================================
// TOAST POSITION
// ============================================================
/// Position where toasts are displayed on screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ToastPosition {
/// Top-right corner (default)
#[default]
TopRight,
/// Top-left corner
TopLeft,
/// Bottom-right corner
BottomRight,
/// Bottom-left corner
BottomLeft,
}
// ============================================================
// TOAST MANAGER
// ============================================================
/// Manages a collection of toast notifications.
///
/// The manager handles:
/// - Adding and removing toasts
/// - Updating fade animations
/// - Limiting visible toasts
/// - Positioning toasts on screen
#[derive(Default)]
pub struct ToastManager {
/// Active toasts (newest first)
toasts: Vec<Toast>,
/// Counter for generating unique toast IDs
next_id: u64,
/// Maximum number of toasts to display at once
max_visible: usize,
/// Screen position for toast display
position: ToastPosition,
}
impl ToastManager {
/// Creates a new ToastManager with default settings.
///
/// Defaults:
/// - max_visible: 5
/// - position: TopRight
pub fn new() -> Self {
Self {
toasts: Vec::new(),
next_id: 1,
max_visible: 5,
position: ToastPosition::TopRight,
}
}
/// Sets the maximum number of visible toasts.
pub fn with_max_visible(mut self, max: usize) -> Self {
self.max_visible = max;
self
}
/// Sets the screen position for toast display.
pub fn with_position(mut self, pos: ToastPosition) -> Self {
self.position = pos;
self
}
/// Returns the current position setting.
pub fn position(&self) -> ToastPosition {
self.position
}
/// Adds a toast to the manager and returns its ID.
pub fn push(&mut self, mut toast: Toast) -> u64 {
let id = self.next_id;
self.next_id += 1;
toast.id = id;
self.toasts.insert(0, toast);
id
}
/// Adds a success toast and returns its ID.
pub fn success(&mut self, message: impl Into<String>) -> u64 {
self.push(Toast::success(message))
}
/// Adds an info toast and returns its ID.
pub fn info(&mut self, message: impl Into<String>) -> u64 {
self.push(Toast::info(message))
}
/// Adds a warning toast and returns its ID.
pub fn warning(&mut self, message: impl Into<String>) -> u64 {
self.push(Toast::warning(message))
}
/// Adds an error toast and returns its ID.
pub fn error(&mut self, message: impl Into<String>) -> u64 {
self.push(Toast::error(message))
}
/// Removes a specific toast by ID.
pub fn dismiss(&mut self, id: u64) {
self.toasts.retain(|t| t.id != id);
}
/// Removes all toasts.
pub fn clear(&mut self) {
self.toasts.clear();
}
/// Updates all toasts: removes expired ones and updates fade progress.
///
/// Should be called on each frame/tick of the application.
pub fn tick(&mut self) {
for toast in &mut self.toasts {
toast.tick();
}
self.toasts.retain(|t| !t.is_expired());
}
/// Returns visible toasts (newest first, limited by max_visible).
pub fn visible(&self) -> Vec<&Toast> {
self.toasts.iter().take(self.max_visible).collect()
}
/// Returns true if there are no active toasts.
pub fn is_empty(&self) -> bool {
self.toasts.is_empty()
}
/// Returns true if there are any visible toasts.
pub fn has_visible(&self) -> bool {
!self.toasts.is_empty()
}
/// Returns the total number of active toasts.
pub fn len(&self) -> usize {
self.toasts.len()
}
}
// ============================================================
// TOAST WIDGET
// ============================================================
/// Widget for rendering toast notifications.
///
/// Renders all visible toasts from the manager at the configured position.
pub struct ToastWidget<'a> {
manager: &'a ToastManager,
terminal_width: u16,
terminal_height: u16,
colors: ColorScheme,
}
impl<'a> ToastWidget<'a> {
/// Creates a new ToastWidget for the given manager.
pub fn new(manager: &'a ToastManager) -> Self {
Self {
manager,
terminal_width: 80,
terminal_height: 24,
colors: ColorScheme::default(),
}
}
/// Sets the terminal size for proper positioning.
pub fn terminal_size(mut self, width: u16, height: u16) -> Self {
self.terminal_width = width;
self.terminal_height = height;
self
}
/// Sets a custom color scheme.
pub fn with_colors(mut self, colors: ColorScheme) -> Self {
self.colors = colors;
self
}
fn render_toast(&self, toast: &Toast, x: u16, y: u16, width: u16, buf: &mut Buffer) {
let color = toast.level.color(&self.colors);
let icon = toast.level.icon();
let faded_color = if toast.fade_progress > 0.0 {
interpolate_color(color, self.colors.surface, toast.fade_progress)
} else {
color
};
let faded_text = if toast.fade_progress > 0.0 {
interpolate_color(self.colors.text, self.colors.surface, toast.fade_progress)
} else {
self.colors.text
};
let bg_style = Style::default().bg(self.colors.surface_alt);
for dx in 0..width {
let cell_x = x + dx;
if cell_x < buf.area.width {
if let Some(cell) = buf.cell_mut(Position::new(cell_x, y)) {
cell.set_style(bg_style);
cell.set_char(' ');
}
}
}
if x < buf.area.width {
buf.set_string(
x,
y,
"|",
Style::default().fg(faded_color).bg(self.colors.surface_alt),
);
}
let icon_x = x + 2;
if icon_x + 3 < buf.area.width {
buf.set_string(
icon_x,
y,
icon,
Style::default().fg(faded_color).bg(self.colors.surface_alt),
);
}
let msg_x = x + 6;
let msg_width = width.saturating_sub(8) as usize;
if msg_width > 0 && msg_x < buf.area.width {
let message = if toast.message.len() > msg_width {
if msg_width > 3 {
format!("{}...", &toast.message[..msg_width - 3])
} else {
toast.message.chars().take(msg_width).collect()
}
} else {
toast.message.clone()
};
buf.set_string(
msg_x,
y,
&message,
Style::default().fg(faded_text).bg(self.colors.surface_alt),
);
}
let right_x = x + width.saturating_sub(1);
if right_x < buf.area.width {
buf.set_string(
right_x,
y,
"|",
Style::default().fg(faded_color).bg(self.colors.surface_alt),
);
}
}
}
impl Widget for ToastWidget<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let toasts = self.manager.visible();
if toasts.is_empty() {
return;
}
let toast_width = 50
.min((area.width as f32 * 0.4) as u16)
.max(20)
.min(area.width.saturating_sub(2));
let x = match self.manager.position() {
ToastPosition::TopRight | ToastPosition::BottomRight => {
area.width.saturating_sub(toast_width + 1)
}
ToastPosition::TopLeft | ToastPosition::BottomLeft => 1,
};
for (i, toast) in toasts.iter().enumerate() {
let y = match self.manager.position() {
ToastPosition::TopRight | ToastPosition::TopLeft => 1 + i as u16,
ToastPosition::BottomRight | ToastPosition::BottomLeft => {
area.height.saturating_sub(2 + i as u16)
}
};
if y >= area.height || y == 0 {
continue;
}
self.render_toast(toast, x, y, toast_width, buf);
}
}
}
// ============================================================
// COLOR INTERPOLATION
// ============================================================
fn interpolate_color(from: Color, to: Color, progress: f32) -> Color {
let progress = progress.clamp(0.0, 1.0);
let (from_r, from_g, from_b) = extract_rgb(from);
let (to_r, to_g, to_b) = extract_rgb(to);
let r = lerp(from_r as f32, to_r as f32, progress) as u8;
let g = lerp(from_g as f32, to_g as f32, progress) as u8;
let b = lerp(from_b as f32, to_b as f32, progress) as u8;
Color::Rgb(r, g, b)
}
fn extract_rgb(color: Color) -> (u8, u8, u8) {
match color {
Color::Rgb(r, g, b) => (r, g, b),
_ => (128, 128, 128),
}
}
#[inline]
fn lerp(start: f32, end: f32, t: f32) -> f32 {
start + (end - start) * t
}
// ============================================================
// WIDGET IMPL FOR TOAST (standalone rendering)
// ============================================================
impl Widget for &Toast {
fn render(self, area: Rect, buf: &mut Buffer) {
if area.width < 5 || area.height < 1 {
return;
}
let scheme = ColorScheme::default();
let color = self.level.color(&scheme);
let icon = self.level.icon();
// Render: | [icon] message |
let mut x = area.x;
// Left border
if x < area.right() {
buf.set_string(x, area.y, "|", Style::default().fg(color));
x += 1;
}
// Space
if x < area.right() {
buf.set_string(x, area.y, " ", Style::default());
x += 1;
}
// Icon
let icon_len = icon.len() as u16;
if x + icon_len <= area.right() {
buf.set_string(x, area.y, icon, Style::default().fg(color));
x += icon_len;
}
// Space
if x < area.right() {
buf.set_string(x, area.y, " ", Style::default());
x += 1;
}
// Message (truncated if needed)
let remaining_width = area.right().saturating_sub(x + 2) as usize; // -2 for " |" at end
if remaining_width > 0 {
let msg = if self.message.len() > remaining_width {
if remaining_width > 3 {
format!("{}...", &self.message[..remaining_width - 3])
} else {
self.message.chars().take(remaining_width).collect()
}
} else {
self.message.clone()
};
buf.set_string(x, area.y, &msg, Style::default().fg(scheme.text));
x += msg.len() as u16;
}
// Padding to right border
while x < area.right().saturating_sub(1) {
buf.set_string(x, area.y, " ", Style::default());
x += 1;
}
// Right border
if x < area.right() {
buf.set_string(x, area.y, "|", Style::default().fg(color));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_toast_level_icons() {
assert_eq!(ToastLevel::Success.icon(), "[+]");
assert_eq!(ToastLevel::Info.icon(), "[i]");
assert_eq!(ToastLevel::Warning.icon(), "[!]");
assert_eq!(ToastLevel::Error.icon(), "[x]");
}
#[test]
fn test_toast_manager_push() {
let mut manager = ToastManager::new();
let id1 = manager.success("First");
let id2 = manager.info("Second");
assert_eq!(manager.len(), 2);
assert_ne!(id1, id2);
}
#[test]
fn test_toast_manager_visible_limit() {
let mut manager = ToastManager::new().with_max_visible(2);
manager.success("First");
manager.info("Second");
manager.warning("Third");
let visible = manager.visible();
assert_eq!(visible.len(), 2);
}
#[test]
fn test_toast_persistent() {
let toast = Toast::info("Persistent").persistent();
assert!(!toast.is_expired());
}
}