Skip to main content

ftui_widgets/
toast.rs

1#![forbid(unsafe_code)]
2
3//! Toast widget for displaying transient notifications.
4//!
5//! A toast is a non-blocking notification that appears temporarily and
6//! can be dismissed automatically or manually. Toasts support:
7//!
8//! - Multiple positions (corners and center top/bottom)
9//! - Automatic dismissal with configurable duration
10//! - Icons for different message types (success, error, warning, info)
11//! - Semantic styling that integrates with the theme system
12//!
13//! # Example
14//!
15//! ```ignore
16//! let toast = Toast::new("File saved successfully")
17//!     .icon(ToastIcon::Success)
18//!     .position(ToastPosition::TopRight)
19//!     .duration(Duration::from_secs(3));
20//! ```
21
22use web_time::{Duration, Instant};
23
24use crate::{Widget, clear_text_area};
25use ftui_a11y::node::{A11yNodeInfo, A11yRole, LiveRegion};
26use ftui_core::geometry::Rect;
27use ftui_render::cell::Cell;
28use ftui_render::frame::Frame;
29use ftui_style::Style;
30use ftui_text::display_width;
31
32/// Unique identifier for a toast notification.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub struct ToastId(pub u64);
35
36impl ToastId {
37    /// Create a new toast ID.
38    pub fn new(id: u64) -> Self {
39        Self(id)
40    }
41}
42
43/// Position where the toast should be displayed.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum ToastPosition {
46    /// Top-left corner.
47    TopLeft,
48    /// Top center.
49    TopCenter,
50    /// Top-right corner.
51    #[default]
52    TopRight,
53    /// Bottom-left corner.
54    BottomLeft,
55    /// Bottom center.
56    BottomCenter,
57    /// Bottom-right corner.
58    BottomRight,
59}
60
61impl ToastPosition {
62    /// Calculate the toast's top-left position within a terminal area.
63    ///
64    /// Returns `(x, y)` for the toast's origin given its dimensions.
65    pub fn calculate_position(
66        self,
67        terminal_width: u16,
68        terminal_height: u16,
69        toast_width: u16,
70        toast_height: u16,
71        margin: u16,
72    ) -> (u16, u16) {
73        let x = match self {
74            Self::TopLeft | Self::BottomLeft => margin,
75            Self::TopCenter | Self::BottomCenter => terminal_width.saturating_sub(toast_width) / 2,
76            Self::TopRight | Self::BottomRight => terminal_width
77                .saturating_sub(toast_width)
78                .saturating_sub(margin),
79        };
80
81        let y = match self {
82            Self::TopLeft | Self::TopCenter | Self::TopRight => margin,
83            Self::BottomLeft | Self::BottomCenter | Self::BottomRight => terminal_height
84                .saturating_sub(toast_height)
85                .saturating_sub(margin),
86        };
87
88        (x, y)
89    }
90}
91
92/// Icon displayed in the toast to indicate message type.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
94pub enum ToastIcon {
95    /// Success indicator (checkmark).
96    Success,
97    /// Error indicator (X mark).
98    Error,
99    /// Warning indicator (exclamation).
100    Warning,
101    /// Information indicator (i).
102    #[default]
103    Info,
104    /// Custom single character.
105    Custom(char),
106}
107
108impl ToastIcon {
109    /// Get the display character for this icon.
110    pub fn as_char(self) -> char {
111        match self {
112            Self::Success => '\u{2713}', // ✓
113            Self::Error => '\u{2717}',   // ✗
114            Self::Warning => '!',
115            Self::Info => 'i',
116            Self::Custom(c) => c,
117        }
118    }
119
120    /// Get the fallback ASCII character for degraded rendering.
121    pub fn as_ascii(self) -> char {
122        match self {
123            Self::Success => '+',
124            Self::Error => 'x',
125            Self::Warning => '!',
126            Self::Info => 'i',
127            Self::Custom(c) if c.is_ascii() => c,
128            Self::Custom(_) => '*',
129        }
130    }
131}
132
133/// Visual style variant for the toast.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
135pub enum ToastStyle {
136    /// Success style (typically green).
137    Success,
138    /// Error style (typically red).
139    Error,
140    /// Warning style (typically yellow/orange).
141    Warning,
142    /// Informational style (typically blue).
143    #[default]
144    Info,
145    /// Neutral style (no semantic coloring).
146    Neutral,
147}
148
149// ============================================================================
150// Animation Types
151// ============================================================================
152
153/// Animation phase for toast lifecycle.
154///
155/// Toasts progress through these phases: Entering → Visible → Exiting → Hidden.
156/// The animation system tracks progress within each phase.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
158pub enum ToastAnimationPhase {
159    /// Toast is animating in (slide/fade entrance).
160    Entering,
161    /// Toast is fully visible (no animation).
162    #[default]
163    Visible,
164    /// Toast is animating out (slide/fade exit).
165    Exiting,
166    /// Toast has completed exit animation.
167    Hidden,
168}
169
170/// Entrance animation type.
171///
172/// Determines how the toast appears on screen.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
174pub enum ToastEntranceAnimation {
175    /// Slide in from the top edge.
176    SlideFromTop,
177    /// Slide in from the right edge.
178    #[default]
179    SlideFromRight,
180    /// Slide in from the bottom edge.
181    SlideFromBottom,
182    /// Slide in from the left edge.
183    SlideFromLeft,
184    /// Fade in (opacity transition).
185    FadeIn,
186    /// No animation (instant appear).
187    None,
188}
189
190impl ToastEntranceAnimation {
191    fn offset_from_dimension(value: u16) -> i16 {
192        i16::try_from(value).unwrap_or(i16::MAX)
193    }
194
195    /// Get the initial offset for this entrance animation.
196    ///
197    /// Returns (dx, dy) offset in cells from the final position.
198    pub fn initial_offset(self, toast_width: u16, toast_height: u16) -> (i16, i16) {
199        let width_offset = Self::offset_from_dimension(toast_width);
200        let height_offset = Self::offset_from_dimension(toast_height);
201        match self {
202            Self::SlideFromTop => (0, -height_offset),
203            Self::SlideFromRight => (width_offset, 0),
204            Self::SlideFromBottom => (0, height_offset),
205            Self::SlideFromLeft => (-width_offset, 0),
206            Self::FadeIn | Self::None => (0, 0),
207        }
208    }
209
210    /// Calculate the offset at a given progress (0.0 to 1.0).
211    ///
212    /// Progress of 0.0 = initial offset, 1.0 = no offset.
213    pub fn offset_at_progress(
214        self,
215        progress: f64,
216        toast_width: u16,
217        toast_height: u16,
218    ) -> (i16, i16) {
219        let (dx, dy) = self.initial_offset(toast_width, toast_height);
220        let inv_progress = 1.0 - progress.clamp(0.0, 1.0);
221        (
222            (dx as f64 * inv_progress).round() as i16,
223            (dy as f64 * inv_progress).round() as i16,
224        )
225    }
226
227    /// Check if this animation affects position (vs. just opacity).
228    pub fn affects_position(self) -> bool {
229        !matches!(self, Self::FadeIn | Self::None)
230    }
231}
232
233/// Exit animation type.
234///
235/// Determines how the toast disappears from screen.
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
237pub enum ToastExitAnimation {
238    /// Fade out (opacity transition).
239    #[default]
240    FadeOut,
241    /// Slide out in the reverse of entrance direction.
242    SlideOut,
243    /// Slide out to the specified edge.
244    SlideToTop,
245    SlideToRight,
246    SlideToBottom,
247    SlideToLeft,
248    /// No animation (instant disappear).
249    None,
250}
251
252impl ToastExitAnimation {
253    /// Get the final offset for this exit animation.
254    ///
255    /// Returns (dx, dy) offset in cells from the starting position.
256    pub fn final_offset(
257        self,
258        toast_width: u16,
259        toast_height: u16,
260        entrance: ToastEntranceAnimation,
261    ) -> (i16, i16) {
262        let width_offset = ToastEntranceAnimation::offset_from_dimension(toast_width);
263        let height_offset = ToastEntranceAnimation::offset_from_dimension(toast_height);
264        match self {
265            Self::SlideOut => {
266                // Reverse of entrance direction
267                let (dx, dy) = entrance.initial_offset(toast_width, toast_height);
268                (-dx, -dy)
269            }
270            Self::SlideToTop => (0, -height_offset),
271            Self::SlideToRight => (width_offset, 0),
272            Self::SlideToBottom => (0, height_offset),
273            Self::SlideToLeft => (-width_offset, 0),
274            Self::FadeOut | Self::None => (0, 0),
275        }
276    }
277
278    /// Calculate the offset at a given progress (0.0 to 1.0).
279    ///
280    /// Progress of 0.0 = no offset, 1.0 = final offset.
281    pub fn offset_at_progress(
282        self,
283        progress: f64,
284        toast_width: u16,
285        toast_height: u16,
286        entrance: ToastEntranceAnimation,
287    ) -> (i16, i16) {
288        let (dx, dy) = self.final_offset(toast_width, toast_height, entrance);
289        let p = progress.clamp(0.0, 1.0);
290        (
291            (dx as f64 * p).round() as i16,
292            (dy as f64 * p).round() as i16,
293        )
294    }
295
296    /// Check if this animation affects position (vs. just opacity).
297    pub fn affects_position(self) -> bool {
298        !matches!(self, Self::FadeOut | Self::None)
299    }
300}
301
302/// Easing function for animations.
303///
304/// Simplified subset of easing curves for toast animations.
305/// For the full set, see `ftui_extras::text_effects::Easing`.
306#[derive(Debug, Clone, Copy, PartialEq, Default)]
307pub enum ToastEasing {
308    /// Linear interpolation.
309    Linear,
310    /// Smooth ease-out (decelerating).
311    #[default]
312    EaseOut,
313    /// Smooth ease-in (accelerating).
314    EaseIn,
315    /// Smooth S-curve.
316    EaseInOut,
317    /// Bouncy effect.
318    Bounce,
319}
320
321impl ToastEasing {
322    /// Apply the easing function to a progress value (0.0 to 1.0).
323    pub fn apply(self, t: f64) -> f64 {
324        let t = t.clamp(0.0, 1.0);
325        match self {
326            Self::Linear => t,
327            Self::EaseOut => {
328                let inv = 1.0 - t;
329                1.0 - inv * inv * inv
330            }
331            Self::EaseIn => t * t * t,
332            Self::EaseInOut => {
333                if t < 0.5 {
334                    4.0 * t * t * t
335                } else {
336                    let inv = -2.0 * t + 2.0;
337                    1.0 - inv * inv * inv / 2.0
338                }
339            }
340            Self::Bounce => {
341                let n1 = 7.5625;
342                let d1 = 2.75;
343                let mut t = t;
344                if t < 1.0 / d1 {
345                    n1 * t * t
346                } else if t < 2.0 / d1 {
347                    t -= 1.5 / d1;
348                    n1 * t * t + 0.75
349                } else if t < 2.5 / d1 {
350                    t -= 2.25 / d1;
351                    n1 * t * t + 0.9375
352                } else {
353                    t -= 2.625 / d1;
354                    n1 * t * t + 0.984375
355                }
356            }
357        }
358    }
359}
360
361/// Animation configuration for a toast.
362#[derive(Debug, Clone)]
363pub struct ToastAnimationConfig {
364    /// Entrance animation type.
365    pub entrance: ToastEntranceAnimation,
366    /// Exit animation type.
367    pub exit: ToastExitAnimation,
368    /// Duration of entrance animation.
369    pub entrance_duration: Duration,
370    /// Duration of exit animation.
371    pub exit_duration: Duration,
372    /// Easing function for entrance.
373    pub entrance_easing: ToastEasing,
374    /// Easing function for exit.
375    pub exit_easing: ToastEasing,
376    /// Whether to respect reduced-motion preference.
377    pub respect_reduced_motion: bool,
378}
379
380impl Default for ToastAnimationConfig {
381    fn default() -> Self {
382        Self {
383            entrance: ToastEntranceAnimation::default(),
384            exit: ToastExitAnimation::default(),
385            entrance_duration: Duration::from_millis(200),
386            exit_duration: Duration::from_millis(150),
387            entrance_easing: ToastEasing::EaseOut,
388            exit_easing: ToastEasing::EaseIn,
389            respect_reduced_motion: true,
390        }
391    }
392}
393
394impl ToastAnimationConfig {
395    /// Create a config with no animations.
396    pub fn none() -> Self {
397        Self {
398            entrance: ToastEntranceAnimation::None,
399            exit: ToastExitAnimation::None,
400            entrance_duration: Duration::ZERO,
401            exit_duration: Duration::ZERO,
402            ..Default::default()
403        }
404    }
405
406    /// Check if animations are effectively disabled.
407    pub fn is_disabled(&self) -> bool {
408        matches!(self.entrance, ToastEntranceAnimation::None)
409            && matches!(self.exit, ToastExitAnimation::None)
410    }
411}
412
413/// Tracks the animation state for a toast.
414#[derive(Debug, Clone)]
415pub struct ToastAnimationState {
416    /// Current animation phase.
417    pub phase: ToastAnimationPhase,
418    /// When the current phase started.
419    pub phase_started: Instant,
420    /// Whether reduced motion is active.
421    pub reduced_motion: bool,
422}
423
424impl Default for ToastAnimationState {
425    fn default() -> Self {
426        Self {
427            phase: ToastAnimationPhase::Entering,
428            phase_started: Instant::now(),
429            reduced_motion: false,
430        }
431    }
432}
433
434impl ToastAnimationState {
435    /// Create a new animation state starting in the Entering phase.
436    pub fn new() -> Self {
437        Self::default()
438    }
439
440    /// Create a state with reduced motion enabled (skips to Visible).
441    pub fn with_reduced_motion() -> Self {
442        Self {
443            phase: ToastAnimationPhase::Visible,
444            phase_started: Instant::now(),
445            reduced_motion: true,
446        }
447    }
448
449    /// Get the progress within the current phase (0.0 to 1.0).
450    pub fn progress(&self, phase_duration: Duration) -> f64 {
451        if phase_duration.is_zero() {
452            return 1.0;
453        }
454        let elapsed = self.phase_started.elapsed();
455        (elapsed.as_secs_f64() / phase_duration.as_secs_f64()).min(1.0)
456    }
457
458    /// Transition to the next phase.
459    pub fn transition_to(&mut self, phase: ToastAnimationPhase) {
460        self.phase = phase;
461        self.phase_started = Instant::now();
462    }
463
464    /// Start the exit animation.
465    pub fn start_exit(&mut self) {
466        if self.reduced_motion {
467            self.transition_to(ToastAnimationPhase::Hidden);
468        } else {
469            self.transition_to(ToastAnimationPhase::Exiting);
470        }
471    }
472
473    /// Check if the animation has completed (Hidden phase).
474    pub fn is_complete(&self) -> bool {
475        self.phase == ToastAnimationPhase::Hidden
476    }
477
478    /// Update the animation state based on elapsed time.
479    ///
480    /// Returns true if the phase changed.
481    pub fn tick(&mut self, config: &ToastAnimationConfig) -> bool {
482        let prev_phase = self.phase;
483
484        match self.phase {
485            ToastAnimationPhase::Entering => {
486                let duration = if self.reduced_motion {
487                    Duration::ZERO
488                } else {
489                    config.entrance_duration
490                };
491                if self.progress(duration) >= 1.0 {
492                    self.transition_to(ToastAnimationPhase::Visible);
493                }
494            }
495            ToastAnimationPhase::Exiting => {
496                let duration = if self.reduced_motion {
497                    Duration::ZERO
498                } else {
499                    config.exit_duration
500                };
501                if self.progress(duration) >= 1.0 {
502                    self.transition_to(ToastAnimationPhase::Hidden);
503                }
504            }
505            ToastAnimationPhase::Visible | ToastAnimationPhase::Hidden => {}
506        }
507
508        self.phase != prev_phase
509    }
510
511    /// Calculate the current animation offset.
512    ///
513    /// Returns (dx, dy) offset to apply to the toast position.
514    pub fn current_offset(
515        &self,
516        config: &ToastAnimationConfig,
517        toast_width: u16,
518        toast_height: u16,
519    ) -> (i16, i16) {
520        if self.reduced_motion {
521            return (0, 0);
522        }
523
524        match self.phase {
525            ToastAnimationPhase::Entering => {
526                let raw_progress = self.progress(config.entrance_duration);
527                let eased_progress = config.entrance_easing.apply(raw_progress);
528                config
529                    .entrance
530                    .offset_at_progress(eased_progress, toast_width, toast_height)
531            }
532            ToastAnimationPhase::Exiting => {
533                let raw_progress = self.progress(config.exit_duration);
534                let eased_progress = config.exit_easing.apply(raw_progress);
535                config.exit.offset_at_progress(
536                    eased_progress,
537                    toast_width,
538                    toast_height,
539                    config.entrance,
540                )
541            }
542            ToastAnimationPhase::Visible => (0, 0),
543            ToastAnimationPhase::Hidden => (0, 0),
544        }
545    }
546
547    /// Calculate the current opacity (0.0 to 1.0).
548    ///
549    /// Used for fade animations.
550    pub fn current_opacity(&self, config: &ToastAnimationConfig) -> f64 {
551        if self.reduced_motion {
552            return if self.phase == ToastAnimationPhase::Hidden {
553                0.0
554            } else {
555                1.0
556            };
557        }
558
559        match self.phase {
560            ToastAnimationPhase::Entering => {
561                if matches!(config.entrance, ToastEntranceAnimation::FadeIn) {
562                    let raw_progress = self.progress(config.entrance_duration);
563                    config.entrance_easing.apply(raw_progress)
564                } else {
565                    1.0
566                }
567            }
568            ToastAnimationPhase::Exiting => {
569                if matches!(config.exit, ToastExitAnimation::FadeOut) {
570                    let raw_progress = self.progress(config.exit_duration);
571                    1.0 - config.exit_easing.apply(raw_progress)
572                } else {
573                    1.0
574                }
575            }
576            ToastAnimationPhase::Visible => 1.0,
577            ToastAnimationPhase::Hidden => 0.0,
578        }
579    }
580}
581
582/// Configuration for a toast notification.
583#[derive(Debug, Clone)]
584pub struct ToastConfig {
585    /// Position on screen.
586    pub position: ToastPosition,
587    /// Auto-dismiss duration. `None` means persistent until dismissed.
588    pub duration: Option<Duration>,
589    /// Whether the duration/persistence policy was explicitly configured by
590    /// the caller instead of inherited from a queue-level default.
591    pub duration_explicit: bool,
592    /// Visual style variant.
593    pub style_variant: ToastStyle,
594    /// Maximum width in columns.
595    pub max_width: u16,
596    /// Margin from screen edges.
597    pub margin: u16,
598    /// Whether the toast can be dismissed by the user.
599    pub dismissable: bool,
600    /// Animation configuration.
601    pub animation: ToastAnimationConfig,
602}
603
604impl Default for ToastConfig {
605    fn default() -> Self {
606        Self {
607            position: ToastPosition::default(),
608            duration: Some(Duration::from_secs(5)),
609            duration_explicit: false,
610            style_variant: ToastStyle::default(),
611            max_width: 50,
612            margin: 1,
613            dismissable: true,
614            animation: ToastAnimationConfig::default(),
615        }
616    }
617}
618
619/// Simplified key event for toast interaction handling.
620///
621/// This is a widget-level abstraction over terminal key events. The hosting
622/// application maps its native key events to these variants before passing
623/// them to `Toast::handle_key`.
624#[derive(Debug, Clone, Copy, PartialEq, Eq)]
625pub enum KeyEvent {
626    /// Escape key — dismiss the toast.
627    Esc,
628    /// Tab key — cycle focus through action buttons.
629    Tab,
630    /// Enter key — invoke the focused action.
631    Enter,
632    /// Any other key (not consumed by the toast).
633    Other,
634}
635
636/// An interactive action button displayed in a toast.
637///
638/// Actions allow users to respond to a toast (e.g., "Undo", "Retry", "View").
639/// Each action has a display label and a unique identifier used to match
640/// callbacks when the action is invoked.
641///
642/// # Invariants
643///
644/// - `label` must be non-empty after trimming whitespace.
645/// - `id` must be non-empty; it serves as the stable callback key.
646/// - Display width of `label` is bounded by toast `max_width` minus chrome.
647///
648/// # Evidence Ledger
649///
650/// Action focus uses a simple round-robin model: Tab advances focus index
651/// modulo action count. This is deterministic and requires no scoring heuristic.
652/// The decision rule is: `next_focus = (current_focus + 1) % actions.len()`.
653#[derive(Debug, Clone, PartialEq, Eq)]
654pub struct ToastAction {
655    /// Display label for the action button (e.g., "Undo").
656    pub label: String,
657    /// Unique identifier for callback matching.
658    pub id: String,
659}
660
661impl ToastAction {
662    /// Create a new toast action.
663    ///
664    /// # Panics
665    ///
666    /// Panics in debug builds if `label` or `id` is empty after trimming.
667    pub fn new(label: impl Into<String>, id: impl Into<String>) -> Self {
668        let label = label.into();
669        let id = id.into();
670        debug_assert!(
671            !label.trim().is_empty(),
672            "ToastAction label must not be empty"
673        );
674        debug_assert!(!id.trim().is_empty(), "ToastAction id must not be empty");
675        Self { label, id }
676    }
677
678    /// Display width of the action button including brackets.
679    ///
680    /// Rendered as `[Label]`, so width = label_width + 2 (brackets).
681    pub fn display_width(&self) -> usize {
682        display_width(self.label.as_str()) + 2 // [ + label + ]
683    }
684}
685
686/// Result of handling a toast interaction event.
687///
688/// Returned by `Toast::handle_key` to indicate what happened.
689#[derive(Debug, Clone, PartialEq, Eq)]
690pub enum ToastEvent {
691    /// No interaction occurred (key not consumed).
692    None,
693    /// The toast was dismissed.
694    Dismissed,
695    /// An action button was invoked. Contains the action ID.
696    Action(String),
697    /// Focus moved between action buttons.
698    FocusChanged,
699}
700
701/// Content of a toast notification.
702#[derive(Debug, Clone)]
703pub struct ToastContent {
704    /// Main message text.
705    pub message: String,
706    /// Optional icon.
707    pub icon: Option<ToastIcon>,
708    /// Optional title.
709    pub title: Option<String>,
710}
711
712impl ToastContent {
713    /// Create new content with just a message.
714    pub fn new(message: impl Into<String>) -> Self {
715        Self {
716            message: message.into(),
717            icon: None,
718            title: None,
719        }
720    }
721
722    /// Set the icon.
723    #[must_use]
724    pub fn with_icon(mut self, icon: ToastIcon) -> Self {
725        self.icon = Some(icon);
726        self
727    }
728
729    /// Set the title.
730    #[must_use]
731    pub fn with_title(mut self, title: impl Into<String>) -> Self {
732        self.title = Some(title.into());
733        self
734    }
735}
736
737/// Internal state tracking for a toast.
738#[derive(Debug, Clone)]
739pub struct ToastState {
740    /// When the toast was created.
741    pub created_at: Instant,
742    /// Whether the toast has been dismissed.
743    pub dismissed: bool,
744    /// Animation state.
745    pub animation: ToastAnimationState,
746    /// Index of the currently focused action, if any.
747    pub focused_action: Option<usize>,
748    /// Whether the auto-dismiss timer is paused (e.g., due to action focus).
749    pub timer_paused: bool,
750    /// When the timer was paused, for calculating credited time.
751    pub pause_started: Option<Instant>,
752    /// Total duration the timer has been paused (accumulated across multiple pauses).
753    pub total_paused: Duration,
754}
755
756impl Default for ToastState {
757    fn default() -> Self {
758        Self {
759            created_at: Instant::now(),
760            dismissed: false,
761            animation: ToastAnimationState::default(),
762            focused_action: None,
763            timer_paused: false,
764            pause_started: None,
765            total_paused: Duration::ZERO,
766        }
767    }
768}
769
770impl ToastState {
771    /// Create a new state with reduced motion enabled.
772    pub fn with_reduced_motion() -> Self {
773        Self {
774            created_at: Instant::now(),
775            dismissed: false,
776            animation: ToastAnimationState::with_reduced_motion(),
777            focused_action: None,
778            timer_paused: false,
779            pause_started: None,
780            total_paused: Duration::ZERO,
781        }
782    }
783}
784
785/// A toast notification widget.
786///
787/// Toasts display transient messages to the user, typically in a corner
788/// of the screen. They can auto-dismiss after a duration or be manually
789/// dismissed.
790///
791/// # Example
792///
793/// ```ignore
794/// let toast = Toast::new("Operation completed")
795///     .icon(ToastIcon::Success)
796///     .position(ToastPosition::TopRight)
797///     .duration(Duration::from_secs(3));
798///
799/// // Render the toast
800/// toast.render(area, frame);
801/// ```
802#[derive(Debug, Clone)]
803pub struct Toast {
804    /// Unique identifier.
805    pub id: ToastId,
806    /// Toast content.
807    pub content: ToastContent,
808    /// Configuration.
809    pub config: ToastConfig,
810    /// Internal state.
811    pub state: ToastState,
812    /// Interactive action buttons (e.g., "Undo", "Retry").
813    pub actions: Vec<ToastAction>,
814    /// Base style override.
815    style: Style,
816    /// Icon style override.
817    icon_style: Style,
818    /// Title style override.
819    title_style: Style,
820    /// Style for action buttons.
821    action_style: Style,
822    /// Style for the focused action button.
823    action_focus_style: Style,
824}
825
826impl Toast {
827    /// Create a new toast with the given message.
828    pub fn new(message: impl Into<String>) -> Self {
829        static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
830        let id = ToastId::new(NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
831
832        Self {
833            id,
834            content: ToastContent::new(message),
835            config: ToastConfig::default(),
836            state: ToastState::default(),
837            actions: Vec::new(),
838            style: Style::default(),
839            icon_style: Style::default(),
840            title_style: Style::default(),
841            action_style: Style::default(),
842            action_focus_style: Style::default(),
843        }
844    }
845
846    /// Create a toast with a specific ID.
847    pub fn with_id(id: ToastId, message: impl Into<String>) -> Self {
848        Self {
849            id,
850            content: ToastContent::new(message),
851            config: ToastConfig::default(),
852            state: ToastState::default(),
853            actions: Vec::new(),
854            style: Style::default(),
855            icon_style: Style::default(),
856            title_style: Style::default(),
857            action_style: Style::default(),
858            action_focus_style: Style::default(),
859        }
860    }
861
862    // --- Builder methods ---
863
864    /// Set the toast icon.
865    #[must_use]
866    pub fn icon(mut self, icon: ToastIcon) -> Self {
867        self.content.icon = Some(icon);
868        self
869    }
870
871    /// Set the toast title.
872    #[must_use]
873    pub fn title(mut self, title: impl Into<String>) -> Self {
874        self.content.title = Some(title.into());
875        self
876    }
877
878    /// Set the toast position.
879    #[must_use]
880    pub fn position(mut self, position: ToastPosition) -> Self {
881        self.config.position = position;
882        self
883    }
884
885    /// Set the auto-dismiss duration.
886    #[must_use]
887    pub fn duration(mut self, duration: Duration) -> Self {
888        self.config.duration = Some(duration);
889        self.config.duration_explicit = true;
890        self
891    }
892
893    /// Make the toast persistent (no auto-dismiss).
894    #[must_use]
895    pub fn persistent(mut self) -> Self {
896        self.config.duration = None;
897        self.config.duration_explicit = true;
898        self
899    }
900
901    /// Set the style variant.
902    #[must_use]
903    pub fn style_variant(mut self, variant: ToastStyle) -> Self {
904        self.config.style_variant = variant;
905        self
906    }
907
908    /// Set the maximum width.
909    #[must_use]
910    pub fn max_width(mut self, width: u16) -> Self {
911        self.config.max_width = width;
912        self
913    }
914
915    /// Set the margin from screen edges.
916    #[must_use]
917    pub fn margin(mut self, margin: u16) -> Self {
918        self.config.margin = margin;
919        self
920    }
921
922    /// Set whether the toast is dismissable.
923    #[must_use]
924    pub fn dismissable(mut self, dismissable: bool) -> Self {
925        self.config.dismissable = dismissable;
926        self
927    }
928
929    /// Set the base style.
930    #[must_use]
931    pub fn style(mut self, style: Style) -> Self {
932        self.style = style;
933        self
934    }
935
936    /// Set the icon style.
937    #[must_use]
938    pub fn with_icon_style(mut self, style: Style) -> Self {
939        self.icon_style = style;
940        self
941    }
942
943    /// Set the title style.
944    #[must_use]
945    pub fn with_title_style(mut self, style: Style) -> Self {
946        self.title_style = style;
947        self
948    }
949
950    // --- Animation builder methods ---
951
952    /// Set the entrance animation.
953    #[must_use]
954    pub fn entrance_animation(mut self, animation: ToastEntranceAnimation) -> Self {
955        self.config.animation.entrance = animation;
956        self
957    }
958
959    /// Set the exit animation.
960    #[must_use]
961    pub fn exit_animation(mut self, animation: ToastExitAnimation) -> Self {
962        self.config.animation.exit = animation;
963        self
964    }
965
966    /// Set the entrance animation duration.
967    #[must_use]
968    pub fn entrance_duration(mut self, duration: Duration) -> Self {
969        self.config.animation.entrance_duration = duration;
970        self
971    }
972
973    /// Set the exit animation duration.
974    #[must_use]
975    pub fn exit_duration(mut self, duration: Duration) -> Self {
976        self.config.animation.exit_duration = duration;
977        self
978    }
979
980    /// Set the entrance easing function.
981    #[must_use]
982    pub fn entrance_easing(mut self, easing: ToastEasing) -> Self {
983        self.config.animation.entrance_easing = easing;
984        self
985    }
986
987    /// Set the exit easing function.
988    #[must_use]
989    pub fn exit_easing(mut self, easing: ToastEasing) -> Self {
990        self.config.animation.exit_easing = easing;
991        self
992    }
993
994    // --- Action builder methods ---
995
996    /// Add a single action button to the toast.
997    #[must_use]
998    pub fn action(mut self, action: ToastAction) -> Self {
999        self.actions.push(action);
1000        self
1001    }
1002
1003    /// Set all action buttons at once.
1004    #[must_use]
1005    pub fn actions(mut self, actions: Vec<ToastAction>) -> Self {
1006        self.actions = actions;
1007        self
1008    }
1009
1010    /// Set the style for action buttons.
1011    #[must_use]
1012    pub fn with_action_style(mut self, style: Style) -> Self {
1013        self.action_style = style;
1014        self
1015    }
1016
1017    /// Set the style for the focused action button.
1018    #[must_use]
1019    pub fn with_action_focus_style(mut self, style: Style) -> Self {
1020        self.action_focus_style = style;
1021        self
1022    }
1023
1024    /// Disable all animations.
1025    #[must_use]
1026    pub fn no_animation(mut self) -> Self {
1027        self.config.animation = ToastAnimationConfig::none();
1028        self.state.animation = ToastAnimationState {
1029            phase: ToastAnimationPhase::Visible,
1030            phase_started: Instant::now(),
1031            reduced_motion: true,
1032        };
1033        self
1034    }
1035
1036    /// Enable reduced motion mode (skips animations).
1037    #[must_use]
1038    pub fn reduced_motion(mut self, enabled: bool) -> Self {
1039        self.config.animation.respect_reduced_motion = enabled;
1040        if enabled {
1041            self.state.animation = ToastAnimationState::with_reduced_motion();
1042        }
1043        self
1044    }
1045
1046    // --- State methods ---
1047
1048    /// Check if the toast has expired based on its duration.
1049    ///
1050    /// Accounts for time spent paused (when actions are focused).
1051    pub fn is_expired(&self) -> bool {
1052        if let Some(duration) = self.config.duration {
1053            let wall_elapsed = self.state.created_at.elapsed();
1054            let effective_elapsed = wall_elapsed.saturating_sub(self.paused_duration());
1055            effective_elapsed >= duration
1056        } else {
1057            false
1058        }
1059    }
1060
1061    /// Check if the toast should be visible.
1062    ///
1063    /// A toast is visible if it's not in the Hidden animation phase.
1064    #[inline]
1065    pub fn is_visible(&self) -> bool {
1066        self.state.animation.phase != ToastAnimationPhase::Hidden
1067    }
1068
1069    /// Check if the toast is currently animating.
1070    pub fn is_animating(&self) -> bool {
1071        matches!(
1072            self.state.animation.phase,
1073            ToastAnimationPhase::Entering | ToastAnimationPhase::Exiting
1074        )
1075    }
1076
1077    /// Dismiss the toast, starting exit animation.
1078    pub fn dismiss(&mut self) {
1079        if !self.state.dismissed {
1080            self.state.dismissed = true;
1081            self.state.animation.start_exit();
1082        }
1083    }
1084
1085    /// Dismiss immediately without animation.
1086    pub fn dismiss_immediately(&mut self) {
1087        self.state.dismissed = true;
1088        self.state
1089            .animation
1090            .transition_to(ToastAnimationPhase::Hidden);
1091    }
1092
1093    /// Update the animation state. Call this each frame.
1094    ///
1095    /// Returns true if the animation phase changed.
1096    pub fn tick_animation(&mut self) -> bool {
1097        self.state.animation.tick(&self.config.animation)
1098    }
1099
1100    /// Get the current animation phase.
1101    pub fn animation_phase(&self) -> ToastAnimationPhase {
1102        self.state.animation.phase
1103    }
1104
1105    /// Get the current animation offset for rendering.
1106    ///
1107    /// Returns (dx, dy) offset to apply to the position.
1108    pub fn animation_offset(&self) -> (i16, i16) {
1109        let (width, height) = self.calculate_dimensions();
1110        self.state
1111            .animation
1112            .current_offset(&self.config.animation, width, height)
1113    }
1114
1115    /// Get the current opacity for rendering (0.0 to 1.0).
1116    pub fn animation_opacity(&self) -> f64 {
1117        self.state.animation.current_opacity(&self.config.animation)
1118    }
1119
1120    /// Get the remaining time before auto-dismiss.
1121    ///
1122    /// Accounts for paused time.
1123    #[must_use = "use the remaining time (if any) for scheduling"]
1124    pub fn remaining_time(&self) -> Option<Duration> {
1125        self.config.duration.map(|d| {
1126            let wall_elapsed = self.state.created_at.elapsed();
1127            let effective_elapsed = wall_elapsed.saturating_sub(self.paused_duration());
1128            d.saturating_sub(effective_elapsed)
1129        })
1130    }
1131
1132    // --- Interaction methods ---
1133
1134    /// Handle a key event for toast interaction.
1135    ///
1136    /// Supported keys:
1137    /// - `Esc`: Dismiss the toast (if dismissable).
1138    /// - `Tab`: Cycle focus through action buttons (round-robin).
1139    /// - `Enter`: Invoke the focused action. Returns `ToastEvent::Action(id)`.
1140    pub fn handle_key(&mut self, key: KeyEvent) -> ToastEvent {
1141        if !self.is_visible() || self.state.dismissed {
1142            return ToastEvent::None;
1143        }
1144
1145        match key {
1146            KeyEvent::Esc => {
1147                if self.has_focus() {
1148                    self.clear_focus();
1149                    ToastEvent::None
1150                } else if self.config.dismissable {
1151                    self.dismiss();
1152                    ToastEvent::Dismissed
1153                } else {
1154                    ToastEvent::None
1155                }
1156            }
1157            KeyEvent::Tab => {
1158                if self.actions.is_empty() {
1159                    return ToastEvent::None;
1160                }
1161                let next = match self.state.focused_action {
1162                    None => 0,
1163                    Some(i) => (i + 1) % self.actions.len(),
1164                };
1165                self.state.focused_action = Some(next);
1166                self.pause_timer();
1167                ToastEvent::FocusChanged
1168            }
1169            KeyEvent::Enter => {
1170                if let Some(idx) = self.state.focused_action
1171                    && let Some(action) = self.actions.get(idx)
1172                {
1173                    let id = action.id.clone();
1174                    self.dismiss();
1175                    return ToastEvent::Action(id);
1176                }
1177                ToastEvent::None
1178            }
1179            _ => ToastEvent::None,
1180        }
1181    }
1182
1183    /// Pause the auto-dismiss timer.
1184    pub fn pause_timer(&mut self) {
1185        if !self.state.timer_paused {
1186            self.state.timer_paused = true;
1187            self.state.pause_started = Some(Instant::now());
1188        }
1189    }
1190
1191    /// Resume the auto-dismiss timer.
1192    pub fn resume_timer(&mut self) {
1193        if self.state.timer_paused {
1194            if let Some(pause_start) = self.state.pause_started.take() {
1195                self.state.total_paused = self
1196                    .state
1197                    .total_paused
1198                    .saturating_add(pause_start.elapsed());
1199            }
1200            self.state.timer_paused = false;
1201        }
1202    }
1203
1204    /// Clear action focus and resume the timer.
1205    pub fn clear_focus(&mut self) {
1206        self.state.focused_action = None;
1207        self.resume_timer();
1208    }
1209
1210    /// Check whether any action is currently focused.
1211    pub fn has_focus(&self) -> bool {
1212        self.state.focused_action.is_some()
1213    }
1214
1215    /// Get the currently focused action, if any.
1216    #[must_use = "use the focused action (if any)"]
1217    pub fn focused_action(&self) -> Option<&ToastAction> {
1218        self.state
1219            .focused_action
1220            .and_then(|idx| self.actions.get(idx))
1221    }
1222
1223    fn paused_duration(&self) -> Duration {
1224        let mut paused = self.state.total_paused;
1225        if self.state.timer_paused
1226            && let Some(pause_start) = self.state.pause_started
1227        {
1228            paused = paused.saturating_add(pause_start.elapsed());
1229        }
1230        paused
1231    }
1232
1233    fn accessibility_root_id(&self) -> u64 {
1234        use std::hash::{Hash, Hasher};
1235        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1236        ("ftui.toast", self.id.0).hash(&mut hasher);
1237        hasher.finish()
1238    }
1239
1240    fn accessibility_action_id(&self, parent: u64, index: usize) -> u64 {
1241        use std::hash::{Hash, Hasher};
1242        let action = &self.actions[index];
1243        let occurrence = self.actions[..index]
1244            .iter()
1245            .filter(|previous| previous.id == action.id)
1246            .count();
1247        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1248        ("ftui.toast.action", parent, &action.id, occurrence).hash(&mut hasher);
1249        hasher.finish()
1250    }
1251
1252    fn accessibility_name(&self) -> &str {
1253        self.content
1254            .title
1255            .as_deref()
1256            .unwrap_or(match self.config.style_variant {
1257                ToastStyle::Success => "Success notification",
1258                ToastStyle::Error => "Error notification",
1259                ToastStyle::Warning => "Warning notification",
1260                ToastStyle::Info => "Information notification",
1261                ToastStyle::Neutral => "Notification",
1262            })
1263    }
1264
1265    fn accessibility_urgency(&self) -> LiveRegion {
1266        match self.config.style_variant {
1267            ToastStyle::Error => LiveRegion::Assertive,
1268            ToastStyle::Success | ToastStyle::Warning | ToastStyle::Info | ToastStyle::Neutral => {
1269                LiveRegion::Polite
1270            }
1271        }
1272    }
1273
1274    /// Calculate the toast dimensions based on content.
1275    pub fn calculate_dimensions(&self) -> (u16, u16) {
1276        let max_width = self.config.max_width as usize;
1277
1278        // Calculate content width
1279        let icon_width = self
1280            .content
1281            .icon
1282            .map(|icon| {
1283                let mut buf = [0u8; 4];
1284                let s = icon.as_char().encode_utf8(&mut buf);
1285                display_width(s) + 1
1286            })
1287            .unwrap_or(0); // icon + space
1288        let message_width = display_width(self.content.message.as_str());
1289        let title_width = self
1290            .content
1291            .title
1292            .as_ref()
1293            .map(|t| display_width(t.as_str()))
1294            .unwrap_or(0);
1295
1296        // Content width is max of title and message (plus icon)
1297        let mut content_width = (icon_width + message_width).max(title_width);
1298
1299        // Account for actions row width: [Label] [Label] with spaces between
1300        if !self.actions.is_empty() {
1301            let actions_width: usize = self
1302                .actions
1303                .iter()
1304                .map(|a| a.display_width())
1305                .sum::<usize>()
1306                + self.actions.len().saturating_sub(1); // spaces between buttons
1307            content_width = content_width.max(actions_width);
1308        }
1309
1310        // Add padding (1 char each side) and border (1 char each side)
1311        let total_width = content_width.saturating_add(4).min(max_width);
1312
1313        // Height: border (2) + optional title (1) + message (1) + optional actions (1)
1314        let has_title = self.content.title.is_some();
1315        let has_actions = !self.actions.is_empty();
1316        let height = 3 + u16::from(has_title) + u16::from(has_actions);
1317
1318        (total_width as u16, height)
1319    }
1320}
1321
1322impl Widget for Toast {
1323    fn render(&self, area: Rect, frame: &mut Frame) {
1324        #[cfg(feature = "tracing")]
1325        let _span = tracing::debug_span!(
1326            "widget_render",
1327            widget = "Toast",
1328            x = area.x,
1329            y = area.y,
1330            w = area.width,
1331            h = area.height
1332        )
1333        .entered();
1334
1335        if area.is_empty() {
1336            return;
1337        }
1338
1339        // Calculate actual render area (use provided area or calculate from content)
1340        let (content_width, content_height) = self.calculate_dimensions();
1341        let width = area.width.min(content_width);
1342        let height = area.height.min(content_height);
1343
1344        if width < 3 || height < 3 {
1345            return; // Too small to render
1346        }
1347
1348        let render_area = Rect::new(area.x, area.y, width, height);
1349
1350        if !self.is_visible() {
1351            clear_text_area(frame, render_area, Style::default());
1352            return;
1353        }
1354
1355        // A visible toast is a live region independent of visual degradation:
1356        // reduced rendering must not make an error or notification disappear
1357        // from assistive output. Stable ToastId-derived IDs keep animation and
1358        // geometry changes from replaying the same notification.
1359        let a11y_root = if frame.a11y_enabled() {
1360            let bounds = render_area.intersection(&frame.buffer.current_scissor());
1361            if bounds.is_empty() {
1362                None
1363            } else {
1364                let id = self.accessibility_root_id();
1365                let node = A11yNodeInfo::new(id, A11yRole::Group, bounds)
1366                    .with_name(self.accessibility_name())
1367                    .with_description(self.content.message.clone())
1368                    .with_live_region(self.accessibility_urgency());
1369                frame.push_a11y(node);
1370                Some(id)
1371            }
1372        } else {
1373            None
1374        };
1375
1376        let deg = frame.buffer.degradation;
1377        if !deg.render_content() {
1378            return;
1379        }
1380
1381        let base_style = if deg.apply_styling() {
1382            self.style
1383        } else {
1384            Style::default()
1385        };
1386        clear_text_area(frame, render_area, base_style);
1387
1388        // Draw border
1389        let use_unicode = deg.use_unicode_borders();
1390        let (tl, tr, bl, br, h, v) = if use_unicode {
1391            (
1392                '\u{250C}', '\u{2510}', '\u{2514}', '\u{2518}', '\u{2500}', '\u{2502}',
1393            )
1394        } else {
1395            ('+', '+', '+', '+', '-', '|')
1396        };
1397
1398        // Top border
1399        let mut cell = Cell::from_char(tl);
1400        if deg.apply_styling() {
1401            crate::apply_style(&mut cell, self.style);
1402        }
1403        frame.buffer.set_fast(render_area.x, render_area.y, cell);
1404
1405        for x in (render_area.x + 1)..(render_area.right().saturating_sub(1)) {
1406            let mut cell = Cell::from_char(h);
1407            if deg.apply_styling() {
1408                crate::apply_style(&mut cell, self.style);
1409            }
1410            frame.buffer.set_fast(x, render_area.y, cell);
1411        }
1412
1413        let mut cell_tr = Cell::from_char(tr);
1414        if deg.apply_styling() {
1415            crate::apply_style(&mut cell_tr, self.style);
1416        }
1417        frame.buffer.set_fast(
1418            render_area.right().saturating_sub(1),
1419            render_area.y,
1420            cell_tr,
1421        );
1422
1423        // Bottom border
1424        let bottom_y = render_area.bottom().saturating_sub(1);
1425        let mut cell_bl = Cell::from_char(bl);
1426        if deg.apply_styling() {
1427            crate::apply_style(&mut cell_bl, self.style);
1428        }
1429        frame.buffer.set_fast(render_area.x, bottom_y, cell_bl);
1430
1431        for x in (render_area.x + 1)..(render_area.right().saturating_sub(1)) {
1432            let mut cell = Cell::from_char(h);
1433            if deg.apply_styling() {
1434                crate::apply_style(&mut cell, self.style);
1435            }
1436            frame.buffer.set_fast(x, bottom_y, cell);
1437        }
1438
1439        let mut cell_br = Cell::from_char(br);
1440        if deg.apply_styling() {
1441            crate::apply_style(&mut cell_br, self.style);
1442        }
1443        frame
1444            .buffer
1445            .set_fast(render_area.right().saturating_sub(1), bottom_y, cell_br);
1446
1447        // Side borders
1448        for y in (render_area.y + 1)..bottom_y {
1449            let mut cell_l = Cell::from_char(v);
1450            if deg.apply_styling() {
1451                crate::apply_style(&mut cell_l, self.style);
1452            }
1453            frame.buffer.set_fast(render_area.x, y, cell_l);
1454
1455            let mut cell_r = Cell::from_char(v);
1456            if deg.apply_styling() {
1457                crate::apply_style(&mut cell_r, self.style);
1458            }
1459            frame
1460                .buffer
1461                .set_fast(render_area.right().saturating_sub(1), y, cell_r);
1462        }
1463
1464        // Draw content
1465        let content_x = render_area.x + 1; // After left border
1466        let content_width = width.saturating_sub(2); // Minus borders
1467        let mut content_y = render_area.y + 1;
1468
1469        // Draw title if present
1470        if let Some(ref title) = self.content.title {
1471            let title_style = if deg.apply_styling() {
1472                self.title_style.merge(&self.style)
1473            } else {
1474                Style::default()
1475            };
1476
1477            let title_style = if deg.apply_styling() {
1478                title_style
1479            } else {
1480                Style::default()
1481            };
1482            crate::draw_text_span(
1483                frame,
1484                content_x,
1485                content_y,
1486                title,
1487                title_style,
1488                content_x + content_width,
1489            );
1490            content_y += 1;
1491        }
1492
1493        // Draw icon and message
1494        let mut msg_x = content_x;
1495
1496        if let Some(icon) = self.content.icon {
1497            let icon_char = if use_unicode {
1498                icon.as_char()
1499            } else {
1500                icon.as_ascii()
1501            };
1502
1503            let icon_style = if deg.apply_styling() {
1504                self.icon_style.merge(&self.style)
1505            } else {
1506                Style::default()
1507            };
1508            let icon_str = icon_char.to_string();
1509            msg_x = crate::draw_text_span(
1510                frame,
1511                msg_x,
1512                content_y,
1513                &icon_str,
1514                icon_style,
1515                content_x + content_width,
1516            );
1517            msg_x = crate::draw_text_span(
1518                frame,
1519                msg_x,
1520                content_y,
1521                " ",
1522                Style::default(),
1523                content_x + content_width,
1524            );
1525        }
1526
1527        // Draw message
1528        let msg_style = if deg.apply_styling() {
1529            self.style
1530        } else {
1531            Style::default()
1532        };
1533        crate::draw_text_span(
1534            frame,
1535            msg_x,
1536            content_y,
1537            &self.content.message,
1538            msg_style,
1539            content_x + content_width,
1540        );
1541
1542        // Draw action buttons if present
1543        if !self.actions.is_empty() {
1544            content_y += 1;
1545            let mut btn_x = content_x;
1546
1547            for (idx, action) in self.actions.iter().enumerate() {
1548                let is_focused = self.state.focused_action == Some(idx);
1549                let btn_style = if is_focused && deg.apply_styling() {
1550                    self.action_focus_style.merge(&self.style)
1551                } else if deg.apply_styling() {
1552                    self.action_style.merge(&self.style)
1553                } else {
1554                    Style::default()
1555                };
1556
1557                let max_x = content_x + content_width;
1558                let label = format!("[{}]", action.label);
1559                let button_x = btn_x;
1560                btn_x = crate::draw_text_span(frame, btn_x, content_y, &label, btn_style, max_x);
1561
1562                if let Some(parent) = a11y_root {
1563                    let button_width =
1564                        display_width(&label).min(max_x.saturating_sub(button_x) as usize) as u16;
1565                    let bounds = Rect::new(button_x, content_y, button_width, 1)
1566                        .intersection(&frame.buffer.current_scissor());
1567                    if !bounds.is_empty() {
1568                        let mut node = A11yNodeInfo::new(
1569                            self.accessibility_action_id(parent, idx),
1570                            A11yRole::Button,
1571                            bounds,
1572                        )
1573                        .with_parent(parent)
1574                        .with_name(&action.label);
1575                        node.state.focused = is_focused;
1576                        frame.push_a11y(node);
1577                    }
1578                }
1579
1580                // Space between buttons
1581                if idx + 1 < self.actions.len() {
1582                    btn_x = crate::draw_text_span(
1583                        frame,
1584                        btn_x,
1585                        content_y,
1586                        " ",
1587                        Style::default(),
1588                        max_x,
1589                    );
1590                }
1591            }
1592        }
1593    }
1594
1595    fn is_essential(&self) -> bool {
1596        // Toasts are informational, not essential
1597        false
1598    }
1599}
1600
1601#[cfg(test)]
1602mod tests {
1603    use super::*;
1604    use ftui_a11y::tree::{A11yTree, A11yTreeBuilder, AnnouncementReason, ScreenReaderPolicy};
1605    use ftui_render::budget::DegradationLevel;
1606    use ftui_render::grapheme_pool::GraphemePool;
1607
1608    fn cell_at(frame: &Frame, x: u16, y: u16) -> Cell {
1609        frame
1610            .buffer
1611            .get(x, y)
1612            .copied()
1613            .expect("test cell should exist")
1614    }
1615
1616    fn line_text(frame: &Frame, y: u16, width: u16) -> String {
1617        (0..width)
1618            .map(|x| {
1619                frame
1620                    .buffer
1621                    .get(x, y)
1622                    .and_then(|cell| cell.content.as_char())
1623                    .unwrap_or(' ')
1624            })
1625            .collect()
1626    }
1627
1628    fn focused_action_id(toast: &Toast) -> &str {
1629        toast
1630            .focused_action()
1631            .expect("focused action should exist")
1632            .id
1633            .as_str()
1634    }
1635
1636    fn unwrap_remaining(remaining: Option<Duration>) -> Duration {
1637        remaining.expect("remaining duration should exist")
1638    }
1639
1640    fn render_toast_a11y(toast: &Toast, area: Rect) -> A11yTree {
1641        let mut builder = A11yTreeBuilder::new();
1642        {
1643            let mut pool = GraphemePool::new();
1644            let mut frame = Frame::new(80, 24, &mut pool);
1645            frame.set_a11y(&mut builder);
1646            toast.render(area, &mut frame);
1647            frame.finish_a11y();
1648        }
1649        builder.build()
1650    }
1651
1652    #[test]
1653    fn toast_accessibility_announces_once_and_maps_error_urgency() {
1654        for (style, urgency) in [
1655            (ToastStyle::Info, LiveRegion::Polite),
1656            (ToastStyle::Error, LiveRegion::Assertive),
1657        ] {
1658            let toast = Toast::with_id(ToastId::new(700), "Disk status")
1659                .style_variant(style)
1660                .title("Storage");
1661            let tree = render_toast_a11y(&toast, Rect::new(2, 2, 30, 6));
1662            let root = tree.root().expect("toast root");
1663            assert_eq!(root.role, A11yRole::Group);
1664            assert_eq!(root.name.as_deref(), Some("Storage"));
1665            assert_eq!(root.description.as_deref(), Some("Disk status"));
1666            assert_eq!(root.live_region, Some(urgency));
1667            assert!(tree.focused().is_none());
1668
1669            let first = tree.screen_reader_announcements_since(
1670                &A11yTree::empty(),
1671                ScreenReaderPolicy::default(),
1672            );
1673            assert_eq!(first.announcements.len(), 1);
1674            assert_eq!(
1675                first.announcements[0].reason,
1676                AnnouncementReason::LiveRegionAdded
1677            );
1678            assert_eq!(first.announcements[0].urgency, urgency);
1679            let repeat =
1680                tree.screen_reader_announcements_since(&tree, ScreenReaderPolicy::default());
1681            assert!(repeat.announcements.is_empty());
1682        }
1683    }
1684
1685    #[test]
1686    fn toast_accessibility_identity_survives_geometry_and_content_changes_announce_once() {
1687        let before_toast =
1688            Toast::with_id(ToastId::new(701), "Uploading").style_variant(ToastStyle::Info);
1689        let after_toast =
1690            Toast::with_id(ToastId::new(701), "Upload complete").style_variant(ToastStyle::Info);
1691        let before = render_toast_a11y(&before_toast, Rect::new(0, 0, 30, 5));
1692        let after = render_toast_a11y(&after_toast, Rect::new(20, 10, 30, 5));
1693        assert_eq!(before.root_id(), after.root_id());
1694        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1695        assert_eq!(batch.announcements.len(), 1);
1696        assert_eq!(batch.dropped_count, 0);
1697        assert_eq!(
1698            batch.announcements[0].reason,
1699            AnnouncementReason::LiveContentChanged
1700        );
1701        assert!(batch.announcements[0].text.contains("Upload complete"));
1702    }
1703
1704    #[test]
1705    fn separate_toast_ids_with_equal_text_are_distinct_notifications() {
1706        let first = Toast::with_id(ToastId::new(702), "Saved");
1707        let second = Toast::with_id(ToastId::new(703), "Saved");
1708        let first_tree = render_toast_a11y(&first, Rect::new(0, 0, 20, 5));
1709        let second_tree = render_toast_a11y(&second, Rect::new(0, 0, 20, 5));
1710        assert_ne!(first_tree.root_id(), second_tree.root_id());
1711        let batch = second_tree
1712            .screen_reader_announcements_since(&first_tree, ScreenReaderPolicy::default());
1713        assert_eq!(batch.announcements.len(), 1);
1714        assert_eq!(
1715            batch.announcements[0].reason,
1716            AnnouncementReason::LiveRegionAdded
1717        );
1718    }
1719
1720    #[test]
1721    fn toast_action_focus_is_a_child_and_does_not_reannounce_the_live_region() {
1722        let mut toast = Toast::with_id(ToastId::new(704), "Connection failed")
1723            .style_variant(ToastStyle::Error)
1724            .action(ToastAction::new("Retry", "retry"))
1725            .action(ToastAction::new("Dismiss", "dismiss"));
1726        let before = render_toast_a11y(&toast, Rect::new(0, 0, 40, 6));
1727        assert_eq!(before.root().unwrap().children.len(), 2);
1728        assert_eq!(toast.handle_key(KeyEvent::Tab), ToastEvent::FocusChanged);
1729        let after = render_toast_a11y(&toast, Rect::new(0, 0, 40, 6));
1730        let focused = after.focused().expect("focused action");
1731        assert_eq!(focused.role, A11yRole::Button);
1732        assert_eq!(focused.name.as_deref(), Some("Retry"));
1733        assert_eq!(focused.parent, after.root_id());
1734        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1735        assert_eq!(batch.announcements.len(), 1);
1736        assert_eq!(
1737            batch.announcements[0].reason,
1738            AnnouncementReason::FocusChanged
1739        );
1740        assert_eq!(batch.announcements[0].node_id, Some(focused.id));
1741    }
1742
1743    #[test]
1744    fn hidden_or_fully_clipped_toast_contributes_no_accessibility_nodes() {
1745        let mut hidden = Toast::with_id(ToastId::new(705), "Private");
1746        hidden.dismiss_immediately();
1747        assert!(render_toast_a11y(&hidden, Rect::new(0, 0, 20, 5)).is_empty());
1748
1749        let toast = Toast::with_id(ToastId::new(706), "Clipped");
1750        let mut builder = A11yTreeBuilder::new();
1751        {
1752            let mut pool = GraphemePool::new();
1753            let mut frame = Frame::new(20, 5, &mut pool);
1754            frame.set_a11y(&mut builder);
1755            frame.buffer.push_scissor(Rect::new(19, 4, 1, 1));
1756            toast.render(Rect::new(0, 0, 10, 3), &mut frame);
1757            frame.finish_a11y();
1758        }
1759        assert!(builder.build().is_empty());
1760    }
1761
1762    #[test]
1763    fn test_toast_new() {
1764        let toast = Toast::new("Hello");
1765        assert_eq!(toast.content.message, "Hello");
1766        assert!(toast.content.icon.is_none());
1767        assert!(toast.content.title.is_none());
1768        assert!(!toast.config.duration_explicit);
1769        assert!(toast.is_visible());
1770    }
1771
1772    #[test]
1773    fn test_toast_builder() {
1774        let toast = Toast::new("Test message")
1775            .icon(ToastIcon::Success)
1776            .title("Success")
1777            .position(ToastPosition::BottomRight)
1778            .duration(Duration::from_secs(10))
1779            .max_width(60);
1780
1781        assert_eq!(toast.content.message, "Test message");
1782        assert_eq!(toast.content.icon, Some(ToastIcon::Success));
1783        assert_eq!(toast.content.title, Some("Success".to_string()));
1784        assert_eq!(toast.config.position, ToastPosition::BottomRight);
1785        assert_eq!(toast.config.duration, Some(Duration::from_secs(10)));
1786        assert!(toast.config.duration_explicit);
1787        assert_eq!(toast.config.max_width, 60);
1788    }
1789
1790    #[test]
1791    fn test_toast_persistent() {
1792        let toast = Toast::new("Persistent").persistent();
1793        assert!(toast.config.duration.is_none());
1794        assert!(toast.config.duration_explicit);
1795        assert!(!toast.is_expired());
1796    }
1797
1798    #[test]
1799    fn test_toast_dismiss() {
1800        let mut toast = Toast::new("Dismissable").no_animation();
1801        assert!(toast.is_visible());
1802        toast.dismiss();
1803        assert!(!toast.is_visible());
1804        assert!(toast.state.dismissed);
1805    }
1806
1807    #[test]
1808    fn test_toast_position_calculate() {
1809        let terminal_width = 80;
1810        let terminal_height = 24;
1811        let toast_width = 30;
1812        let toast_height = 3;
1813        let margin = 1;
1814
1815        // Top-left
1816        let (x, y) = ToastPosition::TopLeft.calculate_position(
1817            terminal_width,
1818            terminal_height,
1819            toast_width,
1820            toast_height,
1821            margin,
1822        );
1823        assert_eq!(x, 1);
1824        assert_eq!(y, 1);
1825
1826        // Top-right
1827        let (x, y) = ToastPosition::TopRight.calculate_position(
1828            terminal_width,
1829            terminal_height,
1830            toast_width,
1831            toast_height,
1832            margin,
1833        );
1834        assert_eq!(x, 80 - 30 - 1); // 49
1835        assert_eq!(y, 1);
1836
1837        // Bottom-right
1838        let (x, y) = ToastPosition::BottomRight.calculate_position(
1839            terminal_width,
1840            terminal_height,
1841            toast_width,
1842            toast_height,
1843            margin,
1844        );
1845        assert_eq!(x, 49);
1846        assert_eq!(y, 24 - 3 - 1); // 20
1847
1848        // Top-center
1849        let (x, y) = ToastPosition::TopCenter.calculate_position(
1850            terminal_width,
1851            terminal_height,
1852            toast_width,
1853            toast_height,
1854            margin,
1855        );
1856        assert_eq!(x, (80 - 30) / 2); // 25
1857        assert_eq!(y, 1);
1858    }
1859
1860    #[test]
1861    fn test_toast_icon_chars() {
1862        assert_eq!(ToastIcon::Success.as_char(), '\u{2713}');
1863        assert_eq!(ToastIcon::Error.as_char(), '\u{2717}');
1864        assert_eq!(ToastIcon::Warning.as_char(), '!');
1865        assert_eq!(ToastIcon::Info.as_char(), 'i');
1866        assert_eq!(ToastIcon::Custom('*').as_char(), '*');
1867
1868        // ASCII fallbacks
1869        assert_eq!(ToastIcon::Success.as_ascii(), '+');
1870        assert_eq!(ToastIcon::Error.as_ascii(), 'x');
1871    }
1872
1873    #[test]
1874    fn test_toast_dimensions() {
1875        let toast = Toast::new("Short");
1876        let (w, h) = toast.calculate_dimensions();
1877        // "Short" = 5 chars + 4 (padding+border) = 9
1878        assert_eq!(w, 9);
1879        assert_eq!(h, 3); // No title
1880
1881        let toast_with_title = Toast::new("Message").title("Title");
1882        let (_w, h) = toast_with_title.calculate_dimensions();
1883        assert_eq!(h, 4); // With title
1884    }
1885
1886    #[test]
1887    fn test_toast_dimensions_with_icon() {
1888        let toast = Toast::new("Message").icon(ToastIcon::Success);
1889        let (w, _h) = toast.calculate_dimensions();
1890        let mut buf = [0u8; 4];
1891        let icon = ToastIcon::Success.as_char().encode_utf8(&mut buf);
1892        let expected = display_width(icon) + 1 + display_width("Message") + 4;
1893        assert_eq!(w, expected as u16);
1894    }
1895
1896    #[test]
1897    fn test_toast_dimensions_max_width() {
1898        let toast = Toast::new("This is a very long message that exceeds max width").max_width(20);
1899        let (w, _h) = toast.calculate_dimensions();
1900        assert!(w <= 20);
1901    }
1902
1903    #[test]
1904    fn test_toast_render_basic() {
1905        let toast = Toast::new("Hello");
1906        let area = Rect::new(0, 0, 15, 5);
1907        let mut pool = GraphemePool::new();
1908        let mut frame = Frame::new(15, 5, &mut pool);
1909        toast.render(area, &mut frame);
1910
1911        // Check border corners
1912        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('\u{250C}')); // ┌
1913        assert!(frame.buffer.get(1, 1).is_some()); // Content area exists
1914    }
1915
1916    #[test]
1917    fn test_toast_render_with_icon() {
1918        let toast = Toast::new("OK").icon(ToastIcon::Success);
1919        let area = Rect::new(0, 0, 10, 5);
1920        let mut pool = GraphemePool::new();
1921        let mut frame = Frame::new(10, 5, &mut pool);
1922        toast.render(area, &mut frame);
1923
1924        // Icon should be at position (1, 1) - inside border
1925        let icon_cell = cell_at(&frame, 1, 1);
1926        let ok = if let Some(ch) = icon_cell.content.as_char() {
1927            ch == '\u{2713}'
1928        } else if let Some(id) = icon_cell.content.grapheme_id() {
1929            frame.pool.get(id) == Some("\u{2713}")
1930        } else {
1931            false
1932        };
1933        assert!(ok, "expected toast icon cell to contain ✓");
1934    }
1935
1936    #[test]
1937    fn test_toast_render_with_title() {
1938        let toast = Toast::new("Body").title("Head");
1939        let area = Rect::new(0, 0, 15, 6);
1940        let mut pool = GraphemePool::new();
1941        let mut frame = Frame::new(15, 6, &mut pool);
1942        toast.render(area, &mut frame);
1943
1944        // Title at row 1, message at row 2
1945        let title_cell = cell_at(&frame, 1, 1);
1946        assert_eq!(title_cell.content.as_char(), Some('H'));
1947    }
1948
1949    #[test]
1950    fn test_toast_render_zero_area() {
1951        let toast = Toast::new("Test");
1952        let area = Rect::new(0, 0, 0, 0);
1953        let mut pool = GraphemePool::new();
1954        let mut frame = Frame::new(1, 1, &mut pool);
1955        toast.render(area, &mut frame); // Should not panic
1956    }
1957
1958    #[test]
1959    fn test_toast_render_small_area() {
1960        let toast = Toast::new("Test");
1961        let area = Rect::new(0, 0, 2, 2);
1962        let mut pool = GraphemePool::new();
1963        let mut frame = Frame::new(2, 2, &mut pool);
1964        toast.render(area, &mut frame); // Should not render (too small)
1965    }
1966
1967    #[test]
1968    fn test_toast_not_visible_when_dismissed_clears_previous_render_area() {
1969        let mut toast = Toast::new("Test").no_animation();
1970        let area = Rect::new(0, 0, 20, 5);
1971        let mut pool = GraphemePool::new();
1972        let mut frame = Frame::new(20, 5, &mut pool);
1973        let (toast_width, toast_height) = toast.calculate_dimensions();
1974
1975        toast.render(area, &mut frame);
1976        toast.dismiss();
1977
1978        toast.render(area, &mut frame);
1979
1980        for y in 0..toast_height.min(area.height) {
1981            for x in 0..toast_width.min(area.width) {
1982                assert_eq!(cell_at(&frame, x, y).content.as_char(), Some(' '));
1983            }
1984        }
1985    }
1986
1987    #[test]
1988    fn test_toast_is_not_essential() {
1989        let toast = Toast::new("Test");
1990        assert!(!toast.is_essential());
1991    }
1992
1993    #[test]
1994    fn test_toast_simple_borders_use_ascii() {
1995        let toast = Toast::new("Hello");
1996        let area = Rect::new(0, 0, 15, 5);
1997        let mut pool = GraphemePool::new();
1998        let mut frame = Frame::new(15, 5, &mut pool);
1999        frame.buffer.degradation = DegradationLevel::SimpleBorders;
2000        toast.render(area, &mut frame);
2001
2002        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('+'));
2003        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some('-'));
2004        assert_eq!(cell_at(&frame, 0, 1).content.as_char(), Some('|'));
2005    }
2006
2007    #[test]
2008    fn test_toast_skeleton_is_noop() {
2009        let toast = Toast::new("Hello").style_variant(ToastStyle::Success);
2010        let area = Rect::new(0, 0, 15, 5);
2011        let mut pool = GraphemePool::new();
2012        let mut frame = Frame::new(15, 5, &mut pool);
2013        let mut expected_pool = GraphemePool::new();
2014        let expected = Frame::new(15, 5, &mut expected_pool);
2015        frame.buffer.degradation = DegradationLevel::Skeleton;
2016        toast.render(area, &mut frame);
2017
2018        for y in 0..5 {
2019            for x in 0..15 {
2020                assert_eq!(frame.buffer.get(x, y), expected.buffer.get(x, y));
2021            }
2022        }
2023    }
2024
2025    #[test]
2026    fn test_toast_render_shorter_message_clears_stale_suffix() {
2027        let area = Rect::new(0, 0, 20, 5);
2028        let mut pool = GraphemePool::new();
2029        let mut frame = Frame::new(20, 5, &mut pool);
2030
2031        Toast::new("Long message text")
2032            .max_width(18)
2033            .no_animation()
2034            .render(area, &mut frame);
2035        Toast::new("Hi")
2036            .max_width(18)
2037            .no_animation()
2038            .render(area, &mut frame);
2039
2040        assert_eq!(line_text(&frame, 1, 6), "│Hi  │");
2041    }
2042
2043    #[test]
2044    fn test_toast_no_styling_shorter_title_and_message_clear_stale_text() {
2045        let area = Rect::new(0, 0, 18, 6);
2046        let mut pool = GraphemePool::new();
2047        let mut frame = Frame::new(18, 6, &mut pool);
2048
2049        Toast::new("Long body")
2050            .title("LongTitle")
2051            .max_width(16)
2052            .no_animation()
2053            .render(area, &mut frame);
2054
2055        frame.buffer.degradation = DegradationLevel::NoStyling;
2056        Toast::new("Ok")
2057            .title("Hi")
2058            .max_width(16)
2059            .no_animation()
2060            .render(area, &mut frame);
2061
2062        assert_eq!(line_text(&frame, 1, 6), "|Hi  |");
2063        assert_eq!(line_text(&frame, 2, 6), "|Ok  |");
2064    }
2065
2066    #[test]
2067    fn test_toast_id_uniqueness() {
2068        let toast1 = Toast::new("A");
2069        let toast2 = Toast::new("B");
2070        assert_ne!(toast1.id, toast2.id);
2071    }
2072
2073    #[test]
2074    fn test_toast_style_variants() {
2075        let success = Toast::new("OK").style_variant(ToastStyle::Success);
2076        let error = Toast::new("Fail").style_variant(ToastStyle::Error);
2077        let warning = Toast::new("Warn").style_variant(ToastStyle::Warning);
2078        let info = Toast::new("Info").style_variant(ToastStyle::Info);
2079        let neutral = Toast::new("Neutral").style_variant(ToastStyle::Neutral);
2080
2081        assert_eq!(success.config.style_variant, ToastStyle::Success);
2082        assert_eq!(error.config.style_variant, ToastStyle::Error);
2083        assert_eq!(warning.config.style_variant, ToastStyle::Warning);
2084        assert_eq!(info.config.style_variant, ToastStyle::Info);
2085        assert_eq!(neutral.config.style_variant, ToastStyle::Neutral);
2086    }
2087
2088    #[test]
2089    fn test_toast_content_builder() {
2090        let content = ToastContent::new("Message")
2091            .with_icon(ToastIcon::Warning)
2092            .with_title("Alert");
2093
2094        assert_eq!(content.message, "Message");
2095        assert_eq!(content.icon, Some(ToastIcon::Warning));
2096        assert_eq!(content.title, Some("Alert".to_string()));
2097    }
2098
2099    // --- Animation Tests ---
2100
2101    #[test]
2102    fn test_animation_phase_default() {
2103        let toast = Toast::new("Test");
2104        assert_eq!(toast.state.animation.phase, ToastAnimationPhase::Entering);
2105    }
2106
2107    #[test]
2108    fn test_animation_phase_reduced_motion() {
2109        let toast = Toast::new("Test").reduced_motion(true);
2110        assert_eq!(toast.state.animation.phase, ToastAnimationPhase::Visible);
2111        assert!(toast.state.animation.reduced_motion);
2112    }
2113
2114    #[test]
2115    fn test_animation_no_animation() {
2116        let toast = Toast::new("Test").no_animation();
2117        assert_eq!(toast.state.animation.phase, ToastAnimationPhase::Visible);
2118        assert!(toast.config.animation.is_disabled());
2119    }
2120
2121    #[test]
2122    fn test_entrance_animation_builder() {
2123        let toast = Toast::new("Test")
2124            .entrance_animation(ToastEntranceAnimation::SlideFromTop)
2125            .entrance_duration(Duration::from_millis(300))
2126            .entrance_easing(ToastEasing::Bounce);
2127
2128        assert_eq!(
2129            toast.config.animation.entrance,
2130            ToastEntranceAnimation::SlideFromTop
2131        );
2132        assert_eq!(
2133            toast.config.animation.entrance_duration,
2134            Duration::from_millis(300)
2135        );
2136        assert_eq!(toast.config.animation.entrance_easing, ToastEasing::Bounce);
2137    }
2138
2139    #[test]
2140    fn test_exit_animation_builder() {
2141        let toast = Toast::new("Test")
2142            .exit_animation(ToastExitAnimation::SlideOut)
2143            .exit_duration(Duration::from_millis(100))
2144            .exit_easing(ToastEasing::EaseInOut);
2145
2146        assert_eq!(toast.config.animation.exit, ToastExitAnimation::SlideOut);
2147        assert_eq!(
2148            toast.config.animation.exit_duration,
2149            Duration::from_millis(100)
2150        );
2151        assert_eq!(toast.config.animation.exit_easing, ToastEasing::EaseInOut);
2152    }
2153
2154    #[test]
2155    fn test_entrance_animation_offsets() {
2156        let width = 30u16;
2157        let height = 5u16;
2158
2159        // SlideFromTop: starts above, ends at (0, 0)
2160        let (dx, dy) = ToastEntranceAnimation::SlideFromTop.initial_offset(width, height);
2161        assert_eq!(dx, 0);
2162        assert_eq!(dy, -(height as i16));
2163
2164        // At progress 0.0, should be at initial offset
2165        let (dx, dy) = ToastEntranceAnimation::SlideFromTop.offset_at_progress(0.0, width, height);
2166        assert_eq!(dx, 0);
2167        assert_eq!(dy, -(height as i16));
2168
2169        // At progress 1.0, should be at (0, 0)
2170        let (dx, dy) = ToastEntranceAnimation::SlideFromTop.offset_at_progress(1.0, width, height);
2171        assert_eq!(dx, 0);
2172        assert_eq!(dy, 0);
2173
2174        // SlideFromRight: starts to the right
2175        let (dx, dy) = ToastEntranceAnimation::SlideFromRight.initial_offset(width, height);
2176        assert_eq!(dx, width as i16);
2177        assert_eq!(dy, 0);
2178    }
2179
2180    #[test]
2181    fn test_exit_animation_offsets() {
2182        let width = 30u16;
2183        let height = 5u16;
2184        let entrance = ToastEntranceAnimation::SlideFromRight;
2185
2186        // SlideOut reverses entrance direction
2187        let (dx, dy) = ToastExitAnimation::SlideOut.final_offset(width, height, entrance);
2188        assert_eq!(dx, -(width as i16)); // Opposite of SlideFromRight
2189        assert_eq!(dy, 0);
2190
2191        // At progress 0.0, should be at (0, 0)
2192        let (dx, dy) =
2193            ToastExitAnimation::SlideOut.offset_at_progress(0.0, width, height, entrance);
2194        assert_eq!(dx, 0);
2195        assert_eq!(dy, 0);
2196
2197        // At progress 1.0, should be at final offset
2198        let (dx, dy) =
2199            ToastExitAnimation::SlideOut.offset_at_progress(1.0, width, height, entrance);
2200        assert_eq!(dx, -(width as i16));
2201        assert_eq!(dy, 0);
2202    }
2203
2204    #[test]
2205    fn test_easing_apply() {
2206        // Linear: t = t
2207        assert!((ToastEasing::Linear.apply(0.5) - 0.5).abs() < 0.001);
2208
2209        // EaseOut at 0.5 should be > 0.5 (decelerating)
2210        assert!(ToastEasing::EaseOut.apply(0.5) > 0.5);
2211
2212        // EaseIn at 0.5 should be < 0.5 (accelerating)
2213        assert!(ToastEasing::EaseIn.apply(0.5) < 0.5);
2214
2215        // All should be 0 at 0 and 1 at 1
2216        for easing in [
2217            ToastEasing::Linear,
2218            ToastEasing::EaseIn,
2219            ToastEasing::EaseOut,
2220            ToastEasing::EaseInOut,
2221            ToastEasing::Bounce,
2222        ] {
2223            assert!((easing.apply(0.0) - 0.0).abs() < 0.001, "{:?} at 0", easing);
2224            assert!((easing.apply(1.0) - 1.0).abs() < 0.001, "{:?} at 1", easing);
2225        }
2226    }
2227
2228    #[test]
2229    fn test_animation_state_progress() {
2230        let state = ToastAnimationState::new();
2231        // Just created, progress should be very small
2232        let progress = state.progress(Duration::from_millis(200));
2233        assert!(
2234            progress < 0.1,
2235            "Progress should be small immediately after creation"
2236        );
2237    }
2238
2239    #[test]
2240    fn test_animation_state_zero_duration() {
2241        let state = ToastAnimationState::new();
2242        // Zero duration should return 1.0 (complete)
2243        let progress = state.progress(Duration::ZERO);
2244        assert_eq!(progress, 1.0);
2245    }
2246
2247    #[test]
2248    fn test_dismiss_starts_exit_animation() {
2249        let mut toast = Toast::new("Test").no_animation();
2250        // First set to visible phase
2251        toast.state.animation.phase = ToastAnimationPhase::Visible;
2252        toast.state.animation.reduced_motion = false;
2253
2254        toast.dismiss();
2255
2256        assert!(toast.state.dismissed);
2257        assert_eq!(toast.state.animation.phase, ToastAnimationPhase::Exiting);
2258    }
2259
2260    #[test]
2261    fn test_dismiss_immediately() {
2262        let mut toast = Toast::new("Test");
2263        toast.dismiss_immediately();
2264
2265        assert!(toast.state.dismissed);
2266        assert_eq!(toast.state.animation.phase, ToastAnimationPhase::Hidden);
2267        assert!(!toast.is_visible());
2268    }
2269
2270    #[test]
2271    fn test_is_animating() {
2272        let toast = Toast::new("Test");
2273        assert!(toast.is_animating()); // Starts in Entering phase
2274
2275        let toast_visible = Toast::new("Test").no_animation();
2276        assert!(!toast_visible.is_animating()); // No animation = Visible phase
2277    }
2278
2279    #[test]
2280    fn test_animation_opacity_fade_in() {
2281        let config = ToastAnimationConfig {
2282            entrance: ToastEntranceAnimation::FadeIn,
2283            exit: ToastExitAnimation::FadeOut,
2284            entrance_duration: Duration::from_millis(200),
2285            exit_duration: Duration::from_millis(150),
2286            entrance_easing: ToastEasing::Linear,
2287            exit_easing: ToastEasing::Linear,
2288            respect_reduced_motion: false,
2289        };
2290
2291        // At progress 0, opacity should be 0
2292        let mut state = ToastAnimationState::new();
2293        let opacity = state.current_opacity(&config);
2294        assert!(opacity < 0.1, "Should be low opacity at start");
2295
2296        // At progress 1 (Visible phase), opacity should be 1
2297        state.phase = ToastAnimationPhase::Visible;
2298        let opacity = state.current_opacity(&config);
2299        assert!((opacity - 1.0).abs() < 0.001);
2300    }
2301
2302    #[test]
2303    fn test_animation_config_default() {
2304        let config = ToastAnimationConfig::default();
2305
2306        assert_eq!(config.entrance, ToastEntranceAnimation::SlideFromRight);
2307        assert_eq!(config.exit, ToastExitAnimation::FadeOut);
2308        assert_eq!(config.entrance_duration, Duration::from_millis(200));
2309        assert_eq!(config.exit_duration, Duration::from_millis(150));
2310        assert!(config.respect_reduced_motion);
2311    }
2312
2313    #[test]
2314    fn test_animation_affects_position() {
2315        assert!(ToastEntranceAnimation::SlideFromTop.affects_position());
2316        assert!(ToastEntranceAnimation::SlideFromRight.affects_position());
2317        assert!(!ToastEntranceAnimation::FadeIn.affects_position());
2318        assert!(!ToastEntranceAnimation::None.affects_position());
2319
2320        assert!(ToastExitAnimation::SlideOut.affects_position());
2321        assert!(ToastExitAnimation::SlideToLeft.affects_position());
2322        assert!(!ToastExitAnimation::FadeOut.affects_position());
2323        assert!(!ToastExitAnimation::None.affects_position());
2324    }
2325
2326    #[test]
2327    fn test_toast_animation_offset() {
2328        let toast = Toast::new("Test").entrance_animation(ToastEntranceAnimation::SlideFromRight);
2329        let (dx, dy) = toast.animation_offset();
2330        // Should have positive dx (sliding from right)
2331        assert!(dx > 0, "Should have positive x offset at start");
2332        assert_eq!(dy, 0);
2333    }
2334
2335    // ── Interactive Toast Action tests ─────────────────────────────────
2336
2337    #[test]
2338    fn action_builder_single() {
2339        let toast = Toast::new("msg").action(ToastAction::new("Retry", "retry"));
2340        assert_eq!(toast.actions.len(), 1);
2341        assert_eq!(toast.actions[0].label, "Retry");
2342        assert_eq!(toast.actions[0].id, "retry");
2343    }
2344
2345    #[test]
2346    fn action_builder_multiple() {
2347        let toast = Toast::new("msg")
2348            .action(ToastAction::new("Ack", "ack"))
2349            .action(ToastAction::new("Snooze", "snooze"));
2350        assert_eq!(toast.actions.len(), 2);
2351    }
2352
2353    #[test]
2354    fn action_builder_vec() {
2355        let actions = vec![
2356            ToastAction::new("A", "a"),
2357            ToastAction::new("B", "b"),
2358            ToastAction::new("C", "c"),
2359        ];
2360        let toast = Toast::new("msg").actions(actions);
2361        assert_eq!(toast.actions.len(), 3);
2362    }
2363
2364    #[test]
2365    fn action_display_width() {
2366        let a = ToastAction::new("OK", "ok");
2367        // [OK] = 4 chars
2368        assert_eq!(a.display_width(), 4);
2369    }
2370
2371    #[test]
2372    fn handle_key_esc_dismisses() {
2373        let mut toast = Toast::new("msg").no_animation();
2374        let result = toast.handle_key(KeyEvent::Esc);
2375        assert_eq!(result, ToastEvent::Dismissed);
2376    }
2377
2378    #[test]
2379    fn handle_key_esc_clears_focus_first() {
2380        let mut toast = Toast::new("msg")
2381            .action(ToastAction::new("A", "a"))
2382            .no_animation();
2383        // First tab to focus
2384        toast.handle_key(KeyEvent::Tab);
2385        assert!(toast.has_focus());
2386        // Esc clears focus rather than dismissing
2387        let result = toast.handle_key(KeyEvent::Esc);
2388        assert_eq!(result, ToastEvent::None);
2389        assert!(!toast.has_focus());
2390    }
2391
2392    #[test]
2393    fn handle_key_tab_cycles_focus() {
2394        let mut toast = Toast::new("msg")
2395            .action(ToastAction::new("A", "a"))
2396            .action(ToastAction::new("B", "b"))
2397            .no_animation();
2398
2399        let r1 = toast.handle_key(KeyEvent::Tab);
2400        assert_eq!(r1, ToastEvent::FocusChanged);
2401        assert_eq!(toast.state.focused_action, Some(0));
2402
2403        let r2 = toast.handle_key(KeyEvent::Tab);
2404        assert_eq!(r2, ToastEvent::FocusChanged);
2405        assert_eq!(toast.state.focused_action, Some(1));
2406
2407        // Wraps around
2408        let r3 = toast.handle_key(KeyEvent::Tab);
2409        assert_eq!(r3, ToastEvent::FocusChanged);
2410        assert_eq!(toast.state.focused_action, Some(0));
2411    }
2412
2413    #[test]
2414    fn handle_key_tab_no_actions_is_noop() {
2415        let mut toast = Toast::new("msg").no_animation();
2416        let result = toast.handle_key(KeyEvent::Tab);
2417        assert_eq!(result, ToastEvent::None);
2418    }
2419
2420    #[test]
2421    fn handle_key_enter_invokes_action() {
2422        let mut toast = Toast::new("msg")
2423            .action(ToastAction::new("Retry", "retry"))
2424            .no_animation();
2425        toast.handle_key(KeyEvent::Tab); // focus action 0
2426        let result = toast.handle_key(KeyEvent::Enter);
2427        assert_eq!(result, ToastEvent::Action("retry".into()));
2428    }
2429
2430    #[test]
2431    fn handle_key_enter_no_focus_is_noop() {
2432        let mut toast = Toast::new("msg")
2433            .action(ToastAction::new("A", "a"))
2434            .no_animation();
2435        let result = toast.handle_key(KeyEvent::Enter);
2436        assert_eq!(result, ToastEvent::None);
2437    }
2438
2439    #[test]
2440    fn handle_key_other_is_noop() {
2441        let mut toast = Toast::new("msg").no_animation();
2442        let result = toast.handle_key(KeyEvent::Other);
2443        assert_eq!(result, ToastEvent::None);
2444    }
2445
2446    #[test]
2447    fn handle_key_dismissed_toast_is_noop() {
2448        let mut toast = Toast::new("msg").no_animation();
2449        toast.state.dismissed = true;
2450        let result = toast.handle_key(KeyEvent::Esc);
2451        assert_eq!(result, ToastEvent::None);
2452    }
2453
2454    #[test]
2455    fn pause_timer_sets_flag() {
2456        let mut toast = Toast::new("msg").no_animation();
2457        toast.pause_timer();
2458        assert!(toast.state.timer_paused);
2459        assert!(toast.state.pause_started.is_some());
2460    }
2461
2462    #[test]
2463    fn resume_timer_accumulates_paused() {
2464        let mut toast = Toast::new("msg").no_animation();
2465        toast.pause_timer();
2466        std::thread::sleep(Duration::from_millis(10));
2467        toast.resume_timer();
2468        assert!(!toast.state.timer_paused);
2469        assert!(toast.state.total_paused >= Duration::from_millis(5));
2470    }
2471
2472    #[test]
2473    fn pause_resume_idempotent() {
2474        let mut toast = Toast::new("msg").no_animation();
2475        // Double pause should not panic
2476        toast.pause_timer();
2477        toast.pause_timer();
2478        assert!(toast.state.timer_paused);
2479        // Double resume should not panic
2480        toast.resume_timer();
2481        toast.resume_timer();
2482        assert!(!toast.state.timer_paused);
2483    }
2484
2485    #[test]
2486    fn resume_timer_saturates_paused_duration() {
2487        let mut toast = Toast::new("msg").no_animation();
2488        toast.state.total_paused = Duration::MAX;
2489        toast.pause_timer();
2490        std::thread::sleep(Duration::from_millis(1));
2491        toast.resume_timer();
2492        assert_eq!(toast.state.total_paused, Duration::MAX);
2493    }
2494
2495    #[test]
2496    fn active_pause_queries_saturate_paused_duration() {
2497        let mut toast = Toast::new("msg")
2498            .duration(Duration::from_secs(1))
2499            .no_animation();
2500        toast.state.total_paused = Duration::MAX;
2501        toast.pause_timer();
2502        std::thread::sleep(Duration::from_millis(1));
2503
2504        assert!(!toast.is_expired());
2505        assert_eq!(toast.remaining_time(), Some(Duration::from_secs(1)));
2506    }
2507
2508    #[test]
2509    fn clear_focus_resumes_timer() {
2510        let mut toast = Toast::new("msg")
2511            .action(ToastAction::new("A", "a"))
2512            .no_animation();
2513        toast.handle_key(KeyEvent::Tab);
2514        assert!(toast.state.timer_paused);
2515        toast.clear_focus();
2516        assert!(!toast.has_focus());
2517        assert!(!toast.state.timer_paused);
2518    }
2519
2520    #[test]
2521    fn focused_action_returns_correct() {
2522        let mut toast = Toast::new("msg")
2523            .action(ToastAction::new("X", "x"))
2524            .action(ToastAction::new("Y", "y"))
2525            .no_animation();
2526        assert!(toast.focused_action().is_none());
2527        toast.handle_key(KeyEvent::Tab);
2528        assert_eq!(focused_action_id(&toast), "x");
2529        toast.handle_key(KeyEvent::Tab);
2530        assert_eq!(focused_action_id(&toast), "y");
2531    }
2532
2533    #[test]
2534    fn is_expired_accounts_for_pause() {
2535        let mut toast = Toast::new("msg")
2536            .duration(Duration::from_millis(50))
2537            .no_animation();
2538        toast.pause_timer();
2539        // Sleep past the duration while paused
2540        std::thread::sleep(Duration::from_millis(60));
2541        assert!(
2542            !toast.is_expired(),
2543            "Should not expire while timer is paused"
2544        );
2545        toast.resume_timer();
2546        // Not expired yet because paused time is subtracted
2547        assert!(
2548            !toast.is_expired(),
2549            "Should not expire immediately after resume because paused time was subtracted"
2550        );
2551    }
2552
2553    #[test]
2554    fn dimensions_include_actions_row() {
2555        let toast = Toast::new("Hi")
2556            .action(ToastAction::new("OK", "ok"))
2557            .no_animation();
2558        let (_, h) = toast.calculate_dimensions();
2559        // Without actions: 3 (border + message + border)
2560        // With actions: 4 (border + message + actions + border)
2561        assert_eq!(h, 4);
2562    }
2563
2564    #[test]
2565    fn dimensions_with_title_and_actions() {
2566        let toast = Toast::new("Hi")
2567            .title("Title")
2568            .action(ToastAction::new("OK", "ok"))
2569            .no_animation();
2570        let (_, h) = toast.calculate_dimensions();
2571        // border + title + message + actions + border = 5
2572        assert_eq!(h, 5);
2573    }
2574
2575    #[test]
2576    fn dimensions_width_accounts_for_actions() {
2577        let toast = Toast::new("Hi")
2578            .action(ToastAction::new("LongButtonLabel", "lb"))
2579            .no_animation();
2580        let (w, _) = toast.calculate_dimensions();
2581        // [LongButtonLabel] = 18 chars, plus 4 for borders/padding = 22
2582        // "Hi" = 2 chars + 4 = 6, so actions width dominates
2583        assert!(w >= 20);
2584    }
2585
2586    #[test]
2587    fn render_with_actions_does_not_panic() {
2588        let toast = Toast::new("Test")
2589            .action(ToastAction::new("OK", "ok"))
2590            .action(ToastAction::new("Cancel", "cancel"))
2591            .no_animation();
2592
2593        let mut pool = GraphemePool::new();
2594        let mut frame = Frame::new(60, 20, &mut pool);
2595        let area = Rect::new(0, 0, 40, 10);
2596        toast.render(area, &mut frame);
2597    }
2598
2599    #[test]
2600    fn render_focused_action_does_not_panic() {
2601        let mut toast = Toast::new("Test")
2602            .action(ToastAction::new("OK", "ok"))
2603            .no_animation();
2604        toast.handle_key(KeyEvent::Tab); // focus first action
2605
2606        let mut pool = GraphemePool::new();
2607        let mut frame = Frame::new(60, 20, &mut pool);
2608        let area = Rect::new(0, 0, 40, 10);
2609        toast.render(area, &mut frame);
2610    }
2611
2612    #[test]
2613    fn render_actions_tiny_area_does_not_panic() {
2614        let toast = Toast::new("X")
2615            .action(ToastAction::new("A", "a"))
2616            .no_animation();
2617
2618        let mut pool = GraphemePool::new();
2619        let mut frame = Frame::new(5, 3, &mut pool);
2620        let area = Rect::new(0, 0, 5, 3);
2621        toast.render(area, &mut frame);
2622    }
2623
2624    #[test]
2625    fn toast_action_styles() {
2626        let style = Style::new().bold();
2627        let focus_style = Style::new().italic();
2628        let toast = Toast::new("msg")
2629            .action(ToastAction::new("A", "a"))
2630            .with_action_style(style)
2631            .with_action_focus_style(focus_style);
2632        assert_eq!(toast.action_style, style);
2633        assert_eq!(toast.action_focus_style, focus_style);
2634    }
2635
2636    #[test]
2637    fn persistent_toast_not_expired_with_actions() {
2638        let toast = Toast::new("msg")
2639            .persistent()
2640            .action(ToastAction::new("Dismiss", "dismiss"))
2641            .no_animation();
2642        std::thread::sleep(Duration::from_millis(10));
2643        assert!(!toast.is_expired());
2644    }
2645
2646    #[test]
2647    fn action_invoke_second_button() {
2648        let mut toast = Toast::new("msg")
2649            .action(ToastAction::new("A", "a"))
2650            .action(ToastAction::new("B", "b"))
2651            .no_animation();
2652        toast.handle_key(KeyEvent::Tab); // focus 0
2653        toast.handle_key(KeyEvent::Tab); // focus 1
2654        let result = toast.handle_key(KeyEvent::Enter);
2655        assert_eq!(result, ToastEvent::Action("b".into()));
2656    }
2657
2658    #[test]
2659    fn remaining_time_with_pause() {
2660        let toast = Toast::new("msg")
2661            .duration(Duration::from_secs(10))
2662            .no_animation();
2663        let remaining = toast.remaining_time();
2664        assert!(remaining.is_some());
2665        let r = unwrap_remaining(remaining);
2666        assert!(r > Duration::from_secs(9));
2667    }
2668
2669    // =========================================================================
2670    // Position edge cases (bd-9vqk6)
2671    // =========================================================================
2672
2673    #[test]
2674    fn position_bottom_left() {
2675        let (x, y) = ToastPosition::BottomLeft.calculate_position(80, 24, 20, 3, 1);
2676        assert_eq!(x, 1);
2677        assert_eq!(y, 24 - 3 - 1); // 20
2678    }
2679
2680    #[test]
2681    fn position_bottom_center() {
2682        let (x, y) = ToastPosition::BottomCenter.calculate_position(80, 24, 20, 3, 1);
2683        assert_eq!(x, (80 - 20) / 2); // 30
2684        assert_eq!(y, 24 - 3 - 1); // 20
2685    }
2686
2687    #[test]
2688    fn position_toast_wider_than_terminal_saturates() {
2689        // Toast is wider than the terminal — x should saturate to 0, not wrap
2690        let (x, y) = ToastPosition::TopRight.calculate_position(20, 10, 30, 3, 1);
2691        assert_eq!(x, 0); // 20 - 30 = saturates to 0, then - 1 = still 0
2692        assert_eq!(y, 1);
2693    }
2694
2695    #[test]
2696    fn position_zero_margin() {
2697        let (x, y) = ToastPosition::TopLeft.calculate_position(80, 24, 20, 3, 0);
2698        assert_eq!(x, 0);
2699        assert_eq!(y, 0);
2700
2701        let (x, y) = ToastPosition::BottomRight.calculate_position(80, 24, 20, 3, 0);
2702        assert_eq!(x, 60);
2703        assert_eq!(y, 21);
2704    }
2705
2706    #[test]
2707    fn position_toast_taller_than_terminal_saturates() {
2708        let (_, y) = ToastPosition::BottomLeft.calculate_position(80, 3, 20, 10, 1);
2709        assert_eq!(y, 0); // 3 - 10 saturates to 0, then - 1 = still 0
2710    }
2711
2712    // =========================================================================
2713    // ToastIcon edge cases (bd-9vqk6)
2714    // =========================================================================
2715
2716    #[test]
2717    fn icon_custom_non_ascii_falls_back_to_star() {
2718        let icon = ToastIcon::Custom('\u{1F525}'); // 🔥
2719        assert_eq!(icon.as_char(), '\u{1F525}');
2720        assert_eq!(icon.as_ascii(), '*');
2721    }
2722
2723    #[test]
2724    fn icon_custom_ascii_preserved() {
2725        let icon = ToastIcon::Custom('#');
2726        assert_eq!(icon.as_char(), '#');
2727        assert_eq!(icon.as_ascii(), '#');
2728    }
2729
2730    #[test]
2731    fn icon_warning_ascii_same() {
2732        assert_eq!(ToastIcon::Warning.as_ascii(), '!');
2733        assert_eq!(ToastIcon::Info.as_ascii(), 'i');
2734    }
2735
2736    // =========================================================================
2737    // Default trait coverage (bd-9vqk6)
2738    // =========================================================================
2739
2740    #[test]
2741    fn toast_position_default_is_top_right() {
2742        assert_eq!(ToastPosition::default(), ToastPosition::TopRight);
2743    }
2744
2745    #[test]
2746    fn toast_icon_default_is_info() {
2747        assert_eq!(ToastIcon::default(), ToastIcon::Info);
2748    }
2749
2750    #[test]
2751    fn toast_style_default_is_info() {
2752        assert_eq!(ToastStyle::default(), ToastStyle::Info);
2753    }
2754
2755    #[test]
2756    fn toast_animation_phase_default_is_visible() {
2757        assert_eq!(ToastAnimationPhase::default(), ToastAnimationPhase::Visible);
2758    }
2759
2760    #[test]
2761    fn toast_entrance_animation_default_is_slide_from_right() {
2762        assert_eq!(
2763            ToastEntranceAnimation::default(),
2764            ToastEntranceAnimation::SlideFromRight
2765        );
2766    }
2767
2768    #[test]
2769    fn toast_exit_animation_default_is_fade_out() {
2770        assert_eq!(ToastExitAnimation::default(), ToastExitAnimation::FadeOut);
2771    }
2772
2773    #[test]
2774    fn toast_easing_default_is_ease_out() {
2775        assert_eq!(ToastEasing::default(), ToastEasing::EaseOut);
2776    }
2777
2778    // =========================================================================
2779    // Entrance animation all variants (bd-9vqk6)
2780    // =========================================================================
2781
2782    #[test]
2783    fn entrance_slide_from_bottom_offset() {
2784        let (dx, dy) = ToastEntranceAnimation::SlideFromBottom.initial_offset(20, 5);
2785        assert_eq!(dx, 0);
2786        assert_eq!(dy, 5); // starts below
2787    }
2788
2789    #[test]
2790    fn entrance_slide_from_left_offset() {
2791        let (dx, dy) = ToastEntranceAnimation::SlideFromLeft.initial_offset(20, 5);
2792        assert_eq!(dx, -20);
2793        assert_eq!(dy, 0);
2794    }
2795
2796    #[test]
2797    fn entrance_fade_in_no_offset() {
2798        let (dx, dy) = ToastEntranceAnimation::FadeIn.initial_offset(20, 5);
2799        assert_eq!(dx, 0);
2800        assert_eq!(dy, 0);
2801    }
2802
2803    #[test]
2804    fn entrance_none_no_offset() {
2805        let (dx, dy) = ToastEntranceAnimation::None.initial_offset(20, 5);
2806        assert_eq!(dx, 0);
2807        assert_eq!(dy, 0);
2808    }
2809
2810    #[test]
2811    fn entrance_offset_progress_clamped() {
2812        // Below 0 should clamp
2813        let (dx, dy) = ToastEntranceAnimation::SlideFromTop.offset_at_progress(-0.5, 20, 5);
2814        assert_eq!(dx, 0);
2815        assert_eq!(dy, -5); // Same as progress 0.0
2816
2817        // Above 1 should clamp
2818        let (dx, dy) = ToastEntranceAnimation::SlideFromTop.offset_at_progress(2.0, 20, 5);
2819        assert_eq!(dx, 0);
2820        assert_eq!(dy, 0); // Same as progress 1.0
2821    }
2822
2823    #[test]
2824    fn entrance_offset_at_half_progress() {
2825        let (dx, dy) = ToastEntranceAnimation::SlideFromRight.offset_at_progress(0.5, 20, 5);
2826        assert_eq!(dx, 10); // Half of width
2827        assert_eq!(dy, 0);
2828    }
2829
2830    #[test]
2831    fn entrance_offsets_saturate_large_dimensions() {
2832        assert_eq!(
2833            ToastEntranceAnimation::SlideFromRight.initial_offset(u16::MAX, u16::MAX),
2834            (i16::MAX, 0)
2835        );
2836        assert_eq!(
2837            ToastEntranceAnimation::SlideFromLeft.initial_offset(u16::MAX, u16::MAX),
2838            (-i16::MAX, 0)
2839        );
2840        assert_eq!(
2841            ToastEntranceAnimation::SlideFromTop.initial_offset(u16::MAX, u16::MAX),
2842            (0, -i16::MAX)
2843        );
2844    }
2845
2846    // =========================================================================
2847    // Exit animation all variants (bd-9vqk6)
2848    // =========================================================================
2849
2850    #[test]
2851    fn exit_slide_to_top_offset() {
2852        let entrance = ToastEntranceAnimation::SlideFromRight;
2853        let (dx, dy) = ToastExitAnimation::SlideToTop.final_offset(20, 5, entrance);
2854        assert_eq!(dx, 0);
2855        assert_eq!(dy, -5);
2856    }
2857
2858    #[test]
2859    fn exit_slide_to_right_offset() {
2860        let entrance = ToastEntranceAnimation::SlideFromRight;
2861        let (dx, dy) = ToastExitAnimation::SlideToRight.final_offset(20, 5, entrance);
2862        assert_eq!(dx, 20);
2863        assert_eq!(dy, 0);
2864    }
2865
2866    #[test]
2867    fn exit_slide_to_bottom_offset() {
2868        let entrance = ToastEntranceAnimation::SlideFromRight;
2869        let (dx, dy) = ToastExitAnimation::SlideToBottom.final_offset(20, 5, entrance);
2870        assert_eq!(dx, 0);
2871        assert_eq!(dy, 5);
2872    }
2873
2874    #[test]
2875    fn exit_slide_to_left_offset() {
2876        let entrance = ToastEntranceAnimation::SlideFromRight;
2877        let (dx, dy) = ToastExitAnimation::SlideToLeft.final_offset(20, 5, entrance);
2878        assert_eq!(dx, -20);
2879        assert_eq!(dy, 0);
2880    }
2881
2882    #[test]
2883    fn exit_fade_out_no_offset() {
2884        let entrance = ToastEntranceAnimation::SlideFromRight;
2885        let (dx, dy) = ToastExitAnimation::FadeOut.final_offset(20, 5, entrance);
2886        assert_eq!(dx, 0);
2887        assert_eq!(dy, 0);
2888    }
2889
2890    #[test]
2891    fn exit_none_no_offset() {
2892        let entrance = ToastEntranceAnimation::SlideFromRight;
2893        let (dx, dy) = ToastExitAnimation::None.final_offset(20, 5, entrance);
2894        assert_eq!(dx, 0);
2895        assert_eq!(dy, 0);
2896    }
2897
2898    #[test]
2899    fn exit_offset_progress_clamped() {
2900        let entrance = ToastEntranceAnimation::SlideFromRight;
2901        let (dx, dy) = ToastExitAnimation::SlideToTop.offset_at_progress(-1.0, 20, 5, entrance);
2902        assert_eq!((dx, dy), (0, 0)); // Clamped to 0.0
2903
2904        let (dx, dy) = ToastExitAnimation::SlideToTop.offset_at_progress(5.0, 20, 5, entrance);
2905        assert_eq!((dx, dy), (0, -5)); // Clamped to 1.0
2906    }
2907
2908    #[test]
2909    fn exit_offsets_saturate_large_dimensions() {
2910        let entrance = ToastEntranceAnimation::SlideFromRight;
2911        assert_eq!(
2912            ToastExitAnimation::SlideToRight.final_offset(u16::MAX, u16::MAX, entrance),
2913            (i16::MAX, 0)
2914        );
2915        assert_eq!(
2916            ToastExitAnimation::SlideToBottom.final_offset(u16::MAX, u16::MAX, entrance),
2917            (0, i16::MAX)
2918        );
2919        assert_eq!(
2920            ToastExitAnimation::SlideOut.final_offset(u16::MAX, u16::MAX, entrance),
2921            (-i16::MAX, 0)
2922        );
2923    }
2924
2925    // =========================================================================
2926    // Easing function edge cases (bd-9vqk6)
2927    // =========================================================================
2928
2929    #[test]
2930    fn easing_clamped_below_zero() {
2931        for easing in [
2932            ToastEasing::Linear,
2933            ToastEasing::EaseIn,
2934            ToastEasing::EaseOut,
2935            ToastEasing::EaseInOut,
2936            ToastEasing::Bounce,
2937        ] {
2938            let result = easing.apply(-0.5);
2939            assert!(
2940                (result - 0.0).abs() < 0.001,
2941                "{easing:?} at -0.5 should clamp to 0"
2942            );
2943        }
2944    }
2945
2946    #[test]
2947    fn easing_clamped_above_one() {
2948        for easing in [
2949            ToastEasing::Linear,
2950            ToastEasing::EaseIn,
2951            ToastEasing::EaseOut,
2952            ToastEasing::EaseInOut,
2953            ToastEasing::Bounce,
2954        ] {
2955            let result = easing.apply(1.5);
2956            assert!(
2957                (result - 1.0).abs() < 0.001,
2958                "{easing:?} at 1.5 should clamp to 1"
2959            );
2960        }
2961    }
2962
2963    #[test]
2964    fn easing_ease_in_out_first_half() {
2965        let result = ToastEasing::EaseInOut.apply(0.25);
2966        assert!(
2967            result < 0.25,
2968            "EaseInOut at 0.25 should be < 0.25 (accelerating)"
2969        );
2970    }
2971
2972    #[test]
2973    fn easing_ease_in_out_second_half() {
2974        let result = ToastEasing::EaseInOut.apply(0.75);
2975        assert!(
2976            result > 0.75,
2977            "EaseInOut at 0.75 should be > 0.75 (decelerating)"
2978        );
2979    }
2980
2981    #[test]
2982    fn easing_bounce_monotonic_at_key_points() {
2983        let d1 = 2.75;
2984        // Sample all four branches of the bounce function
2985        let t1 = 0.2 / d1; // first branch
2986        let t2 = 1.5 / d1; // second branch
2987        let t3 = 2.3 / d1; // third branch
2988        let t4 = 2.7 / d1; // fourth branch
2989
2990        let v1 = ToastEasing::Bounce.apply(t1);
2991        let v2 = ToastEasing::Bounce.apply(t2);
2992        let v3 = ToastEasing::Bounce.apply(t3);
2993        let v4 = ToastEasing::Bounce.apply(t4);
2994
2995        assert!((0.0..=1.0).contains(&v1), "branch 1: {v1}");
2996        assert!((0.0..=1.0).contains(&v2), "branch 2: {v2}");
2997        assert!((0.0..=1.0).contains(&v3), "branch 3: {v3}");
2998        assert!((0.0..=1.0).contains(&v4), "branch 4: {v4}");
2999    }
3000
3001    // =========================================================================
3002    // Animation state transitions (bd-9vqk6)
3003    // =========================================================================
3004
3005    #[test]
3006    fn animation_state_tick_entering_to_visible() {
3007        let config = ToastAnimationConfig {
3008            entrance_duration: Duration::ZERO, // Instant transition
3009            ..ToastAnimationConfig::default()
3010        };
3011        let mut state = ToastAnimationState::new();
3012        assert_eq!(state.phase, ToastAnimationPhase::Entering);
3013
3014        let changed = state.tick(&config);
3015        assert!(changed, "Phase should change from Entering to Visible");
3016        assert_eq!(state.phase, ToastAnimationPhase::Visible);
3017    }
3018
3019    #[test]
3020    fn animation_state_tick_exiting_to_hidden() {
3021        let config = ToastAnimationConfig {
3022            exit_duration: Duration::ZERO,
3023            ..ToastAnimationConfig::default()
3024        };
3025        let mut state = ToastAnimationState::new();
3026        state.transition_to(ToastAnimationPhase::Exiting);
3027
3028        let changed = state.tick(&config);
3029        assert!(changed, "Phase should change from Exiting to Hidden");
3030        assert_eq!(state.phase, ToastAnimationPhase::Hidden);
3031    }
3032
3033    #[test]
3034    fn animation_state_tick_visible_no_change() {
3035        let config = ToastAnimationConfig::default();
3036        let mut state = ToastAnimationState::new();
3037        state.transition_to(ToastAnimationPhase::Visible);
3038
3039        let changed = state.tick(&config);
3040        assert!(!changed, "Visible phase should not auto-transition");
3041        assert_eq!(state.phase, ToastAnimationPhase::Visible);
3042    }
3043
3044    #[test]
3045    fn animation_state_tick_hidden_no_change() {
3046        let config = ToastAnimationConfig::default();
3047        let mut state = ToastAnimationState::new();
3048        state.transition_to(ToastAnimationPhase::Hidden);
3049
3050        let changed = state.tick(&config);
3051        assert!(!changed);
3052        assert_eq!(state.phase, ToastAnimationPhase::Hidden);
3053    }
3054
3055    #[test]
3056    fn animation_state_start_exit_reduced_motion_goes_to_hidden() {
3057        let mut state = ToastAnimationState::with_reduced_motion();
3058        assert_eq!(state.phase, ToastAnimationPhase::Visible);
3059        state.start_exit();
3060        assert_eq!(state.phase, ToastAnimationPhase::Hidden);
3061    }
3062
3063    #[test]
3064    fn animation_state_is_complete() {
3065        let mut state = ToastAnimationState::new();
3066        assert!(!state.is_complete());
3067        state.transition_to(ToastAnimationPhase::Hidden);
3068        assert!(state.is_complete());
3069    }
3070
3071    // =========================================================================
3072    // Animation offset and opacity in all phases (bd-9vqk6)
3073    // =========================================================================
3074
3075    #[test]
3076    fn animation_offset_visible_is_zero() {
3077        let config = ToastAnimationConfig::default();
3078        let mut state = ToastAnimationState::new();
3079        state.phase = ToastAnimationPhase::Visible;
3080        let (dx, dy) = state.current_offset(&config, 20, 5);
3081        assert_eq!((dx, dy), (0, 0));
3082    }
3083
3084    #[test]
3085    fn animation_offset_hidden_is_zero() {
3086        let config = ToastAnimationConfig::default();
3087        let mut state = ToastAnimationState::new();
3088        state.phase = ToastAnimationPhase::Hidden;
3089        let (dx, dy) = state.current_offset(&config, 20, 5);
3090        assert_eq!((dx, dy), (0, 0));
3091    }
3092
3093    #[test]
3094    fn animation_offset_reduced_motion_always_zero() {
3095        let config = ToastAnimationConfig::default();
3096        let state = ToastAnimationState::with_reduced_motion();
3097        let (dx, dy) = state.current_offset(&config, 20, 5);
3098        assert_eq!((dx, dy), (0, 0));
3099    }
3100
3101    #[test]
3102    fn animation_opacity_visible_is_one() {
3103        let config = ToastAnimationConfig::default();
3104        let mut state = ToastAnimationState::new();
3105        state.phase = ToastAnimationPhase::Visible;
3106        assert!((state.current_opacity(&config) - 1.0).abs() < 0.001);
3107    }
3108
3109    #[test]
3110    fn animation_opacity_hidden_is_zero() {
3111        let config = ToastAnimationConfig::default();
3112        let mut state = ToastAnimationState::new();
3113        state.phase = ToastAnimationPhase::Hidden;
3114        assert!((state.current_opacity(&config) - 0.0).abs() < 0.001);
3115    }
3116
3117    #[test]
3118    fn animation_opacity_reduced_motion_visible_is_one() {
3119        let config = ToastAnimationConfig::default();
3120        let mut state = ToastAnimationState::with_reduced_motion();
3121        state.phase = ToastAnimationPhase::Visible;
3122        assert!((state.current_opacity(&config) - 1.0).abs() < 0.001);
3123    }
3124
3125    #[test]
3126    fn animation_opacity_reduced_motion_hidden_is_zero() {
3127        let config = ToastAnimationConfig::default();
3128        let mut state = ToastAnimationState::with_reduced_motion();
3129        state.phase = ToastAnimationPhase::Hidden;
3130        assert!((state.current_opacity(&config) - 0.0).abs() < 0.001);
3131    }
3132
3133    #[test]
3134    fn animation_opacity_exiting_non_fade_is_one() {
3135        let config = ToastAnimationConfig {
3136            exit: ToastExitAnimation::SlideOut,
3137            ..ToastAnimationConfig::default()
3138        };
3139        let mut state = ToastAnimationState::new();
3140        state.phase = ToastAnimationPhase::Exiting;
3141        // Non-FadeOut exit keeps opacity at 1.0
3142        assert!((state.current_opacity(&config) - 1.0).abs() < 0.001);
3143    }
3144
3145    #[test]
3146    fn animation_opacity_entering_non_fade_is_one() {
3147        let config = ToastAnimationConfig {
3148            entrance: ToastEntranceAnimation::SlideFromTop,
3149            ..ToastAnimationConfig::default()
3150        };
3151        let mut state = ToastAnimationState::new();
3152        state.phase = ToastAnimationPhase::Entering;
3153        // Non-FadeIn entrance keeps opacity at 1.0
3154        assert!((state.current_opacity(&config) - 1.0).abs() < 0.001);
3155    }
3156
3157    // =========================================================================
3158    // Toast API coverage (bd-9vqk6)
3159    // =========================================================================
3160
3161    #[test]
3162    fn toast_with_id() {
3163        let toast = Toast::with_id(ToastId::new(42), "Custom ID");
3164        assert_eq!(toast.id, ToastId::new(42));
3165        assert_eq!(toast.content.message, "Custom ID");
3166    }
3167
3168    #[test]
3169    fn toast_tick_animation_returns_true_on_phase_change() {
3170        let mut toast = Toast::new("Test").entrance_duration(Duration::ZERO);
3171        assert_eq!(toast.state.animation.phase, ToastAnimationPhase::Entering);
3172        let changed = toast.tick_animation();
3173        assert!(changed);
3174        assert_eq!(toast.state.animation.phase, ToastAnimationPhase::Visible);
3175    }
3176
3177    #[test]
3178    fn toast_tick_animation_returns_false_when_stable() {
3179        let mut toast = Toast::new("Test").no_animation();
3180        assert_eq!(toast.state.animation.phase, ToastAnimationPhase::Visible);
3181        let changed = toast.tick_animation();
3182        assert!(!changed);
3183    }
3184
3185    #[test]
3186    fn toast_animation_phase_accessor() {
3187        let toast = Toast::new("Test").no_animation();
3188        assert_eq!(toast.animation_phase(), ToastAnimationPhase::Visible);
3189    }
3190
3191    #[test]
3192    fn toast_animation_opacity_accessor() {
3193        let toast = Toast::new("Test").no_animation();
3194        assert!((toast.animation_opacity() - 1.0).abs() < 0.001);
3195    }
3196
3197    #[test]
3198    fn toast_remaining_time_persistent_is_none() {
3199        let toast = Toast::new("msg").persistent().no_animation();
3200        assert!(toast.remaining_time().is_none());
3201    }
3202
3203    #[test]
3204    fn toast_dismiss_twice_idempotent() {
3205        let mut toast = Toast::new("msg").no_animation();
3206        toast.state.animation.reduced_motion = false;
3207        toast.dismiss();
3208        assert!(toast.state.dismissed);
3209        let phase_after_first = toast.state.animation.phase;
3210        toast.dismiss(); // Should not change phase again
3211        assert_eq!(toast.state.animation.phase, phase_after_first);
3212    }
3213
3214    #[test]
3215    fn toast_non_dismissable_esc_noop() {
3216        let mut toast = Toast::new("msg").dismissable(false).no_animation();
3217        let result = toast.handle_key(KeyEvent::Esc);
3218        assert_eq!(result, ToastEvent::None);
3219        assert!(toast.is_visible());
3220    }
3221
3222    #[test]
3223    fn toast_margin_builder() {
3224        let toast = Toast::new("msg").margin(5);
3225        assert_eq!(toast.config.margin, 5);
3226    }
3227
3228    #[test]
3229    fn toast_with_icon_style_builder() {
3230        let style = Style::new().italic();
3231        let toast = Toast::new("msg").with_icon_style(style);
3232        assert_eq!(toast.icon_style, style);
3233    }
3234
3235    #[test]
3236    fn toast_with_title_style_builder() {
3237        let style = Style::new().bold();
3238        let toast = Toast::new("msg").with_title_style(style);
3239        assert_eq!(toast.title_style, style);
3240    }
3241
3242    // =========================================================================
3243    // ToastConfig defaults (bd-9vqk6)
3244    // =========================================================================
3245
3246    #[test]
3247    fn toast_config_default_values() {
3248        let config = ToastConfig::default();
3249        assert_eq!(config.position, ToastPosition::TopRight);
3250        assert_eq!(config.duration, Some(Duration::from_secs(5)));
3251        assert!(!config.duration_explicit);
3252        assert_eq!(config.style_variant, ToastStyle::Info);
3253        assert_eq!(config.max_width, 50);
3254        assert_eq!(config.margin, 1);
3255        assert!(config.dismissable);
3256    }
3257
3258    // =========================================================================
3259    // ToastAnimationConfig (bd-9vqk6)
3260    // =========================================================================
3261
3262    #[test]
3263    fn animation_config_none_fields() {
3264        let config = ToastAnimationConfig::none();
3265        assert_eq!(config.entrance, ToastEntranceAnimation::None);
3266        assert_eq!(config.exit, ToastExitAnimation::None);
3267        assert_eq!(config.entrance_duration, Duration::ZERO);
3268        assert_eq!(config.exit_duration, Duration::ZERO);
3269        assert!(config.is_disabled());
3270    }
3271
3272    #[test]
3273    fn animation_config_is_disabled_false_for_default() {
3274        let config = ToastAnimationConfig::default();
3275        assert!(!config.is_disabled());
3276    }
3277
3278    // =========================================================================
3279    // ToastId and trait coverage (bd-9vqk6)
3280    // =========================================================================
3281
3282    #[test]
3283    fn toast_id_hash_consistent() {
3284        use std::collections::HashSet;
3285        let mut set = HashSet::new();
3286        set.insert(ToastId::new(1));
3287        set.insert(ToastId::new(2));
3288        set.insert(ToastId::new(1)); // Duplicate
3289        assert_eq!(set.len(), 2);
3290    }
3291
3292    #[test]
3293    fn toast_id_debug() {
3294        let id = ToastId::new(42);
3295        let dbg = format!("{:?}", id);
3296        assert!(dbg.contains("42"), "Debug: {dbg}");
3297    }
3298
3299    #[test]
3300    fn toast_event_debug_clone() {
3301        let event = ToastEvent::Action("test".into());
3302        let dbg = format!("{:?}", event);
3303        assert!(dbg.contains("Action"), "Debug: {dbg}");
3304        let cloned = event.clone();
3305        assert_eq!(cloned, ToastEvent::Action("test".into()));
3306    }
3307
3308    #[test]
3309    fn key_event_traits() {
3310        let key = KeyEvent::Tab;
3311        let copy = key; // Copy
3312        assert_eq!(key, copy);
3313        let dbg = format!("{:?}", key);
3314        assert!(dbg.contains("Tab"), "Debug: {dbg}");
3315    }
3316
3317    // =========================================================================
3318    // Tick with reduced motion in entering phase (bd-9vqk6)
3319    // =========================================================================
3320
3321    #[test]
3322    fn animation_tick_entering_reduced_motion_transitions_immediately() {
3323        let config = ToastAnimationConfig::default();
3324        let mut state = ToastAnimationState {
3325            phase: ToastAnimationPhase::Entering,
3326            phase_started: Instant::now(),
3327            reduced_motion: true,
3328        };
3329        // With reduced_motion, entering duration is treated as ZERO → immediate transition
3330        let changed = state.tick(&config);
3331        assert!(changed);
3332        assert_eq!(state.phase, ToastAnimationPhase::Visible);
3333    }
3334
3335    #[test]
3336    fn animation_tick_exiting_reduced_motion_transitions_immediately() {
3337        let config = ToastAnimationConfig::default();
3338        let mut state = ToastAnimationState {
3339            phase: ToastAnimationPhase::Exiting,
3340            phase_started: Instant::now(),
3341            reduced_motion: true,
3342        };
3343        let changed = state.tick(&config);
3344        assert!(changed);
3345        assert_eq!(state.phase, ToastAnimationPhase::Hidden);
3346    }
3347}