Skip to main content

ftui_widgets/
validation_error.rs

1#![forbid(unsafe_code)]
2
3//! Inline validation error display widget.
4//!
5//! Displays validation errors near form fields with:
6//! - Configurable error styling (default: red text with icon)
7//! - Smooth appearance animation via opacity interpolation
8//! - Screen reader accessibility (ARIA error association via semantic info)
9//!
10//! # Example
11//!
12//! ```ignore
13//! use ftui_widgets::{ValidationErrorDisplay, ValidationErrorState};
14//!
15//! // Simple inline error
16//! let error = ValidationErrorDisplay::new("This field is required");
17//! let mut state = ValidationErrorState::default();
18//! error.render(area, &mut frame, &mut state);
19//!
20//! // With custom styling
21//! let error = ValidationErrorDisplay::new("Invalid email address")
22//!     .with_icon("!")
23//!     .with_style(Style::new().fg(PackedRgba::rgb(255, 100, 100)));
24//! ```
25//!
26//! # Invariants (Alien Artifact)
27//!
28//! 1. **Icon presence**: Icon is always rendered when error is visible
29//! 2. **Animation bounds**: Opacity is clamped to [0.0, 1.0]
30//! 3. **Width calculation**: Total width = icon_width + 1 + message_width
31//! 4. **Accessibility**: When rendered, screen readers can announce error text
32//!
33//! # Failure Modes
34//!
35//! | Scenario | Behavior |
36//! |----------|----------|
37//! | Empty message | Renders icon only |
38//! | Zero-width area | No-op, state unchanged |
39//! | Very narrow area | Truncates message with ellipsis |
40//! | Animation overflow | Saturates at 0.0 or 1.0 |
41
42use web_time::{Duration, Instant};
43
44use ftui_core::geometry::Rect;
45use ftui_render::cell::PackedRgba;
46use ftui_render::frame::Frame;
47use ftui_style::Style;
48use ftui_text::{display_width, grapheme_width};
49
50use crate::{StatefulWidget, Widget, clear_text_row, draw_text_span};
51use ftui_a11y::node::{A11yNodeInfo, A11yRole, LiveRegion};
52
53// ---------------------------------------------------------------------------
54// Constants
55// ---------------------------------------------------------------------------
56
57/// Default error foreground color (red).
58pub const ERROR_FG_DEFAULT: PackedRgba = PackedRgba::rgb(220, 60, 60);
59
60/// Default error background color (dark red).
61pub const ERROR_BG_DEFAULT: PackedRgba = PackedRgba::rgb(40, 0, 0);
62
63/// Default error icon.
64pub const ERROR_ICON_DEFAULT: &str = "⚠";
65
66/// Default animation duration.
67pub const ANIMATION_DURATION_MS: u64 = 150;
68
69// ---------------------------------------------------------------------------
70// ValidationErrorDisplay
71// ---------------------------------------------------------------------------
72
73/// A widget for displaying inline validation errors.
74///
75/// Renders an error message with an icon, styled for visibility and
76/// accessibility. Supports smooth appearance/disappearance animations.
77#[derive(Debug, Clone)]
78pub struct ValidationErrorDisplay {
79    /// The error message to display.
80    message: String,
81    /// Optional error code (for programmatic handling).
82    error_code: Option<&'static str>,
83    /// Icon to show before the message.
84    icon: String,
85    /// Style for the error text.
86    style: Style,
87    /// Style for the icon.
88    icon_style: Style,
89    /// Animation duration for appearance.
90    animation_duration: Duration,
91    /// Whether to show the message (vs icon only when narrow).
92    show_message: bool,
93    /// Whether to push this error's own accessibility node.
94    accessibility_node: bool,
95}
96
97impl Default for ValidationErrorDisplay {
98    fn default() -> Self {
99        Self {
100            message: String::new(),
101            error_code: None,
102            icon: ERROR_ICON_DEFAULT.to_string(),
103            style: Style::new().fg(ERROR_FG_DEFAULT),
104            icon_style: Style::new().fg(ERROR_FG_DEFAULT),
105            animation_duration: Duration::from_millis(ANIMATION_DURATION_MS),
106            show_message: true,
107            accessibility_node: true,
108        }
109    }
110}
111
112impl ValidationErrorDisplay {
113    /// Create a new validation error display with the given message.
114    #[must_use]
115    pub fn new(message: impl Into<String>) -> Self {
116        Self {
117            message: message.into(),
118            ..Default::default()
119        }
120    }
121
122    /// Create from an error code and message.
123    #[must_use]
124    pub fn with_code(error_code: &'static str, message: impl Into<String>) -> Self {
125        Self {
126            message: message.into(),
127            error_code: Some(error_code),
128            ..Default::default()
129        }
130    }
131
132    /// Set a custom icon (default: "⚠").
133    #[must_use]
134    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
135        self.icon = icon.into();
136        self
137    }
138
139    /// Set the error text style.
140    #[must_use]
141    pub fn with_style(mut self, style: Style) -> Self {
142        self.style = style;
143        self
144    }
145
146    /// Set the icon style.
147    #[must_use]
148    pub fn with_icon_style(mut self, style: Style) -> Self {
149        self.icon_style = style;
150        self
151    }
152
153    /// Set the animation duration.
154    #[must_use]
155    pub fn with_animation_duration(mut self, duration: Duration) -> Self {
156        self.animation_duration = duration;
157        self
158    }
159
160    /// Disable message display (icon only).
161    #[must_use]
162    pub fn icon_only(mut self) -> Self {
163        self.show_message = false;
164        self
165    }
166
167    /// Push no accessibility node of its own.
168    ///
169    /// For a widget that already puts this error on its own node, as `Form`
170    /// does on the field the error belongs to. Otherwise screen readers hear
171    /// the error twice, and an unfocused field's error becomes a live region.
172    #[must_use]
173    pub fn without_accessibility_node(mut self) -> Self {
174        self.accessibility_node = false;
175        self
176    }
177
178    /// Get the error message.
179    #[must_use]
180    pub fn message(&self) -> &str {
181        &self.message
182    }
183
184    /// Get the error code, if any.
185    #[must_use = "use the error code (if any) for telemetry/diagnostics"]
186    pub fn error_code(&self) -> Option<&'static str> {
187        self.error_code
188    }
189
190    /// Accessibility node id: derived from the state's `aria_id` when the
191    /// caller set one, so the node keeps its identity as the layout moves;
192    /// otherwise from the rendered row, the same fallback other widgets use.
193    fn accessibility_id(aria_id: u32, bounds: Rect) -> u64 {
194        if aria_id == 0 {
195            return A11yNodeInfo::stable_id_for(A11yRole::Label, bounds);
196        }
197        use std::hash::{Hash, Hasher};
198        let mut hasher = std::collections::hash_map::DefaultHasher::new();
199        ("ftui.validation_error", aria_id).hash(&mut hasher);
200        hasher.finish()
201    }
202
203    /// Calculate the minimum width needed to display the error.
204    #[must_use]
205    pub fn min_width(&self) -> u16 {
206        let icon_width = display_width(self.icon.as_str()) as u16;
207        if self.show_message && !self.message.is_empty() {
208            let msg_width = display_width(self.message.as_str()) as u16;
209            icon_width.saturating_add(1).saturating_add(msg_width)
210        } else {
211            icon_width
212        }
213    }
214}
215
216// ---------------------------------------------------------------------------
217// ValidationErrorState
218// ---------------------------------------------------------------------------
219
220/// State for validation error animation and accessibility.
221#[derive(Debug, Clone)]
222pub struct ValidationErrorState {
223    /// Whether the error is currently visible.
224    visible: bool,
225    /// Animation start time.
226    animation_start: Option<Instant>,
227    /// Current opacity (0.0 = hidden, 1.0 = fully visible).
228    opacity: f32,
229    /// Whether the error was just shown (for screen reader announcement).
230    just_shown: bool,
231    /// Unique ID for ARIA association.
232    aria_id: u32,
233}
234
235impl Default for ValidationErrorState {
236    fn default() -> Self {
237        Self {
238            visible: false,
239            animation_start: None,
240            opacity: 0.0,
241            just_shown: false,
242            aria_id: 0,
243        }
244    }
245}
246
247impl ValidationErrorState {
248    /// Create a new state with the given ARIA ID.
249    #[must_use]
250    pub fn with_aria_id(mut self, id: u32) -> Self {
251        self.aria_id = id;
252        self
253    }
254
255    /// Show the error (triggers animation).
256    pub fn show(&mut self) {
257        if !self.visible {
258            self.visible = true;
259            self.animation_start = Some(Instant::now());
260            self.just_shown = true;
261        }
262    }
263
264    /// Hide the error (triggers fade-out animation).
265    pub fn hide(&mut self) {
266        if self.visible {
267            self.visible = false;
268            self.animation_start = Some(Instant::now());
269        }
270    }
271
272    /// Set visibility directly (for immediate show/hide).
273    pub fn set_visible(&mut self, visible: bool) {
274        if visible {
275            self.show();
276        } else {
277            self.hide();
278        }
279    }
280
281    /// Check if the error is currently visible.
282    #[inline]
283    #[must_use]
284    pub fn is_visible(&self) -> bool {
285        self.visible
286    }
287
288    /// Check if the error is fully visible (animation complete).
289    #[must_use]
290    pub fn is_fully_visible(&self) -> bool {
291        self.visible && self.opacity >= 1.0
292    }
293
294    /// Get the current opacity.
295    #[must_use]
296    pub fn opacity(&self) -> f32 {
297        self.opacity
298    }
299
300    /// Check and clear the "just shown" flag (for screen reader announcements).
301    pub fn take_just_shown(&mut self) -> bool {
302        std::mem::take(&mut self.just_shown)
303    }
304
305    /// Get the ARIA ID for accessibility association.
306    #[must_use]
307    pub fn aria_id(&self) -> u32 {
308        self.aria_id
309    }
310
311    /// Update animation state. Call this each frame.
312    pub fn tick(&mut self, animation_duration: Duration) {
313        if let Some(start) = self.animation_start {
314            let elapsed = start.elapsed();
315            let progress = if animation_duration.is_zero() {
316                1.0
317            } else {
318                (elapsed.as_secs_f32() / animation_duration.as_secs_f32()).clamp(0.0, 1.0)
319            };
320
321            if self.visible {
322                // Fade in
323                self.opacity = progress;
324            } else {
325                // Fade out
326                self.opacity = 1.0 - progress;
327            }
328
329            // Animation complete
330            if progress >= 1.0 {
331                self.animation_start = None;
332                self.opacity = if self.visible { 1.0 } else { 0.0 };
333            }
334        }
335    }
336
337    /// Check if an animation is currently in progress.
338    #[must_use]
339    pub fn is_animating(&self) -> bool {
340        self.animation_start.is_some()
341    }
342}
343
344// ---------------------------------------------------------------------------
345// Widget Implementation
346// ---------------------------------------------------------------------------
347
348impl StatefulWidget for ValidationErrorDisplay {
349    type State = ValidationErrorState;
350
351    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
352        #[cfg(feature = "tracing")]
353        let _span = tracing::debug_span!(
354            "widget_render",
355            widget = "ValidationErrorDisplay",
356            x = area.x,
357            y = area.y,
358            w = area.width,
359            h = area.height
360        )
361        .entered();
362
363        if area.is_empty() || area.height < 1 {
364            return;
365        }
366
367        let row_area = Rect::new(area.x, area.y, area.width, 1);
368
369        // Update animation
370        state.tick(self.animation_duration);
371
372        // Skip rendering if fully invisible
373        if state.opacity <= 0.0 && !state.visible {
374            clear_text_row(frame, row_area, Style::default());
375            return;
376        }
377
378        // Invariant 4 says screen readers can announce the error, and nothing
379        // did: this widget pushed no accessibility node, and the
380        // `take_just_shown` / `aria_id` hooks meant for it had no callers, so
381        // an error a sighted user could see did not exist in the tree. The
382        // node carries the full message even when the row truncates it or
383        // shows only the icon, and is a polite live region - the politeness
384        // `Form` uses for a field error - so it is announced when it appears
385        // without interrupting typing. Pushed before any degradation-dependent
386        // styling, as toast does: reduced rendering must not hide an error.
387        if self.accessibility_node && frame.a11y_enabled() {
388            let bounds = row_area.intersection(&frame.buffer.current_scissor());
389            if !bounds.is_empty() {
390                let name = if self.message.is_empty() {
391                    "Validation error".to_string()
392                } else {
393                    self.message.clone()
394                };
395                frame.push_a11y(
396                    A11yNodeInfo::new(
397                        Self::accessibility_id(state.aria_id, bounds),
398                        A11yRole::Label,
399                        bounds,
400                    )
401                    .with_name(name)
402                    .with_live_region(LiveRegion::Polite),
403                );
404            }
405        }
406
407        let deg = frame.buffer.degradation;
408
409        // Calculate effective opacity for styling
410        let effective_opacity = (state.opacity * 255.0) as u8;
411
412        // Adjust style with opacity
413        let icon_style = if deg.apply_styling() && effective_opacity < 255 {
414            let fg = self.icon_style.fg.unwrap_or(ERROR_FG_DEFAULT);
415            Style::new().fg(PackedRgba::rgba(fg.r(), fg.g(), fg.b(), effective_opacity))
416        } else if deg.apply_styling() {
417            self.icon_style
418        } else {
419            Style::default()
420        };
421
422        let text_style = if deg.apply_styling() && effective_opacity < 255 {
423            let fg = self.style.fg.unwrap_or(ERROR_FG_DEFAULT);
424            Style::new().fg(PackedRgba::rgba(fg.r(), fg.g(), fg.b(), effective_opacity))
425        } else if deg.apply_styling() {
426            self.style
427        } else {
428            Style::default()
429        };
430
431        clear_text_row(frame, row_area, Style::default());
432
433        // Draw icon
434        let y = area.y;
435        let mut x = area.x;
436        let max_x = area.right();
437
438        x = draw_text_span(frame, x, y, &self.icon, icon_style, max_x);
439
440        // Draw space separator
441        if x < max_x && self.show_message && !self.message.is_empty() {
442            x = draw_text_span(frame, x, y, " ", Style::default(), max_x);
443
444            // Draw message (truncate with ellipsis if needed)
445            let remaining_width = max_x.saturating_sub(x) as usize;
446            let msg_width = display_width(self.message.as_str());
447
448            if msg_width <= remaining_width {
449                draw_text_span(frame, x, y, &self.message, text_style, max_x);
450            } else if remaining_width >= 4 {
451                // Truncate with ellipsis
452                let mut truncated = String::new();
453                let mut w = 0;
454                let limit = remaining_width.saturating_sub(1); // Leave room for "…"
455
456                for grapheme in unicode_segmentation::UnicodeSegmentation::graphemes(
457                    self.message.as_str(),
458                    true,
459                ) {
460                    let gw = grapheme_width(grapheme);
461                    if w + gw > limit {
462                        break;
463                    }
464                    truncated.push_str(grapheme);
465                    w += gw;
466                }
467                truncated.push('…');
468
469                draw_text_span(frame, x, y, &truncated, text_style, max_x);
470            } else if remaining_width >= 1 {
471                // Just ellipsis
472                draw_text_span(frame, x, y, "…", text_style, max_x);
473            }
474        }
475    }
476}
477
478impl Widget for ValidationErrorDisplay {
479    fn render(&self, area: Rect, frame: &mut Frame) {
480        let mut state = ValidationErrorState {
481            visible: true,
482            opacity: 1.0,
483            ..Default::default()
484        };
485        StatefulWidget::render(self, area, frame, &mut state);
486    }
487
488    fn is_essential(&self) -> bool {
489        // Errors are essential - users need to see them
490        true
491    }
492}
493
494// ---------------------------------------------------------------------------
495// Tests
496// ---------------------------------------------------------------------------
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use ftui_render::cell::Cell;
502    use ftui_render::grapheme_pool::GraphemePool;
503
504    // -- Construction tests --
505
506    #[test]
507    fn new_creates_with_message() {
508        let error = ValidationErrorDisplay::new("Required field");
509        assert_eq!(error.message(), "Required field");
510        assert_eq!(error.error_code(), None);
511    }
512
513    #[test]
514    fn with_code_sets_error_code() {
515        let error = ValidationErrorDisplay::with_code("required", "This field is required");
516        assert_eq!(error.error_code(), Some("required"));
517        assert_eq!(error.message(), "This field is required");
518    }
519
520    #[test]
521    fn with_icon_overrides_default() {
522        let error = ValidationErrorDisplay::new("Error").with_icon("!");
523        assert_eq!(error.icon, "!");
524    }
525
526    #[test]
527    fn icon_only_disables_message() {
528        let error = ValidationErrorDisplay::new("Error").icon_only();
529        assert!(!error.show_message);
530    }
531
532    #[test]
533    fn default_uses_warning_icon() {
534        let error = ValidationErrorDisplay::default();
535        assert_eq!(error.icon, ERROR_ICON_DEFAULT);
536    }
537
538    // -- Min width calculation --
539
540    #[test]
541    fn min_width_icon_only() {
542        let error = ValidationErrorDisplay::new("Error").icon_only();
543        // Warning icon is 1 cell wide (may vary by font but assume 2 for emoji)
544        let icon_width = display_width(ERROR_ICON_DEFAULT) as u16;
545        assert_eq!(error.min_width(), icon_width);
546    }
547
548    #[test]
549    fn min_width_with_message() {
550        let error = ValidationErrorDisplay::new("Error");
551        let icon_width = display_width(ERROR_ICON_DEFAULT) as u16;
552        let msg_width = 5u16; // "Error"
553        assert_eq!(error.min_width(), icon_width + 1 + msg_width);
554    }
555
556    #[test]
557    fn min_width_empty_message() {
558        let error = ValidationErrorDisplay::new("");
559        let icon_width = display_width(ERROR_ICON_DEFAULT) as u16;
560        assert_eq!(error.min_width(), icon_width);
561    }
562
563    // -- State tests --
564
565    #[test]
566    fn state_default_is_hidden() {
567        let state = ValidationErrorState::default();
568        assert!(!state.is_visible());
569        assert_eq!(state.opacity(), 0.0);
570    }
571
572    #[test]
573    fn show_sets_visible_and_starts_animation() {
574        let mut state = ValidationErrorState::default();
575        state.show();
576        assert!(state.is_visible());
577        assert!(state.is_animating());
578        assert!(state.take_just_shown());
579    }
580
581    #[test]
582    fn hide_clears_visible() {
583        let mut state = ValidationErrorState::default();
584        state.show();
585        state.opacity = 1.0;
586        state.animation_start = None;
587        state.hide();
588        assert!(!state.is_visible());
589        assert!(state.is_animating());
590    }
591
592    #[test]
593    fn show_twice_is_noop() {
594        let mut state = ValidationErrorState::default();
595        state.show();
596        let start1 = state.animation_start;
597        state.just_shown = false;
598        state.show();
599        assert_eq!(state.animation_start, start1);
600        assert!(!state.just_shown); // Not re-triggered
601    }
602
603    #[test]
604    fn take_just_shown_clears_flag() {
605        let mut state = ValidationErrorState::default();
606        state.show();
607        assert!(state.take_just_shown());
608        assert!(!state.take_just_shown());
609    }
610
611    #[test]
612    fn tick_advances_opacity() {
613        let mut state = ValidationErrorState::default();
614        state.show();
615        // Simulate time passing
616        state.animation_start = Some(Instant::now() - Duration::from_millis(100));
617        state.tick(Duration::from_millis(150));
618        assert!(state.opacity > 0.0);
619        assert!(state.opacity < 1.0);
620    }
621
622    #[test]
623    fn tick_completes_animation() {
624        let mut state = ValidationErrorState::default();
625        state.show();
626        state.animation_start = Some(Instant::now() - Duration::from_millis(200));
627        state.tick(Duration::from_millis(150));
628        assert_eq!(state.opacity, 1.0);
629        assert!(!state.is_animating());
630    }
631
632    #[test]
633    fn tick_fade_out() {
634        let mut state = ValidationErrorState {
635            visible: false,
636            opacity: 1.0,
637            animation_start: Some(Instant::now() - Duration::from_millis(75)),
638            ..Default::default()
639        };
640        state.tick(Duration::from_millis(150));
641        assert!(state.opacity < 1.0);
642        assert!(state.opacity > 0.0);
643    }
644
645    #[test]
646    fn is_fully_visible_requires_complete_animation() {
647        let mut state = ValidationErrorState::default();
648        state.show();
649        assert!(!state.is_fully_visible());
650        state.opacity = 1.0;
651        state.animation_start = None;
652        assert!(state.is_fully_visible());
653    }
654
655    #[test]
656    fn aria_id_can_be_set() {
657        let state = ValidationErrorState::default().with_aria_id(42);
658        assert_eq!(state.aria_id(), 42);
659    }
660
661    // -- Rendering tests --
662
663    #[test]
664    fn render_draws_icon() {
665        let error = ValidationErrorDisplay::new("Error");
666        let area = Rect::new(0, 0, 20, 1);
667        let mut pool = GraphemePool::new();
668        let mut frame = Frame::new(20, 1, &mut pool);
669        Widget::render(&error, area, &mut frame);
670
671        // Icon should be at position 0
672        // Note: emoji width varies, but we check something was drawn
673        let cell = frame.buffer.get(0, 0).unwrap();
674        assert!(!cell.is_empty());
675    }
676
677    #[test]
678    fn render_draws_message() {
679        let error = ValidationErrorDisplay::new("Required").with_icon("!");
680        let area = Rect::new(0, 0, 20, 1);
681        let mut pool = GraphemePool::new();
682        let mut frame = Frame::new(20, 1, &mut pool);
683        Widget::render(&error, area, &mut frame);
684
685        // "!" at 0, space at 1, "Required" starts at 2
686        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('!'));
687        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('R'));
688    }
689
690    #[test]
691    fn render_clears_separator_cell() {
692        let error = ValidationErrorDisplay::new("Required").with_icon("!");
693        let area = Rect::new(0, 0, 20, 1);
694        let mut pool = GraphemePool::new();
695        let mut frame = Frame::new(20, 1, &mut pool);
696        frame.buffer.set_fast(1, 0, Cell::from_char('X'));
697        Widget::render(&error, area, &mut frame);
698
699        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some(' '));
700    }
701
702    #[test]
703    fn render_truncates_long_message() {
704        let error = ValidationErrorDisplay::new("This is a very long error message").with_icon("!");
705        let area = Rect::new(0, 0, 12, 1);
706        let mut pool = GraphemePool::new();
707        let mut frame = Frame::new(12, 1, &mut pool);
708        Widget::render(&error, area, &mut frame);
709
710        // Should end with ellipsis somewhere
711        let mut found_ellipsis = false;
712        for x in 0..12 {
713            if let Some(cell) = frame.buffer.get(x, 0)
714                && cell.content.as_char() == Some('…')
715            {
716                found_ellipsis = true;
717                break;
718            }
719        }
720        assert!(found_ellipsis);
721    }
722
723    #[test]
724    fn render_empty_area_is_noop() {
725        let error = ValidationErrorDisplay::new("Error");
726        let area = Rect::new(0, 0, 0, 0);
727        let mut pool = GraphemePool::new();
728        let mut frame = Frame::new(1, 1, &mut pool);
729        let mut state = ValidationErrorState::default();
730        StatefulWidget::render(&error, area, &mut frame, &mut state);
731        // Should not panic
732    }
733
734    #[test]
735    fn render_hidden_state_draws_nothing() {
736        let error = ValidationErrorDisplay::new("Error");
737        let area = Rect::new(0, 0, 20, 1);
738        let mut pool = GraphemePool::new();
739        let mut frame = Frame::new(20, 1, &mut pool);
740        let mut state = ValidationErrorState::default(); // Not visible
741        StatefulWidget::render(&error, area, &mut frame, &mut state);
742
743        // Hidden state should leave a cleared row behind.
744        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
745    }
746
747    #[test]
748    fn render_hidden_state_clears_stale_row() {
749        let error = ValidationErrorDisplay::new("Error").with_icon("!");
750        let area = Rect::new(0, 0, 20, 1);
751        let mut pool = GraphemePool::new();
752        let mut frame = Frame::new(20, 1, &mut pool);
753        let mut visible = ValidationErrorState {
754            visible: true,
755            opacity: 1.0,
756            ..Default::default()
757        };
758        let mut hidden = ValidationErrorState::default();
759
760        StatefulWidget::render(&error, area, &mut frame, &mut visible);
761        StatefulWidget::render(&error, area, &mut frame, &mut hidden);
762
763        for x in 0..20u16 {
764            assert_eq!(frame.buffer.get(x, 0).unwrap().content.as_char(), Some(' '));
765        }
766    }
767
768    #[test]
769    fn render_visible_state_draws_content() {
770        let error = ValidationErrorDisplay::new("Error").with_icon("!");
771        let area = Rect::new(0, 0, 20, 1);
772        let mut pool = GraphemePool::new();
773        let mut frame = Frame::new(20, 1, &mut pool);
774        let mut state = ValidationErrorState {
775            visible: true,
776            opacity: 1.0,
777            ..Default::default()
778        };
779        StatefulWidget::render(&error, area, &mut frame, &mut state);
780
781        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('!'));
782    }
783
784    #[test]
785    fn render_icon_only_mode() {
786        let error = ValidationErrorDisplay::new("This error should not appear")
787            .with_icon("X")
788            .icon_only();
789        let area = Rect::new(0, 0, 20, 1);
790        let mut pool = GraphemePool::new();
791        let mut frame = Frame::new(20, 1, &mut pool);
792        Widget::render(&error, area, &mut frame);
793
794        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('X'));
795        // Position 1+ should be cleared (no message)
796        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some(' '));
797    }
798
799    #[test]
800    fn render_shorter_message_clears_stale_suffix() {
801        let long = ValidationErrorDisplay::new("Long validation error").with_icon("!");
802        let short = ValidationErrorDisplay::new("No").with_icon("!");
803        let area = Rect::new(0, 0, 20, 1);
804        let mut pool = GraphemePool::new();
805        let mut frame = Frame::new(20, 1, &mut pool);
806
807        Widget::render(&long, area, &mut frame);
808        Widget::render(&short, area, &mut frame);
809
810        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('!'));
811        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some(' '));
812        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('N'));
813        assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some('o'));
814        assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some(' '));
815        assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some(' '));
816    }
817
818    #[test]
819    fn is_essential_returns_true() {
820        let error = ValidationErrorDisplay::new("Error");
821        assert!(error.is_essential());
822    }
823
824    // -- Property tests --
825
826    #[test]
827    fn opacity_always_clamped() {
828        let mut state = ValidationErrorState::default();
829        state.show();
830        state.animation_start = Some(Instant::now() - Duration::from_secs(10));
831        state.tick(Duration::from_millis(100));
832        assert!(state.opacity >= 0.0);
833        assert!(state.opacity <= 1.0);
834    }
835
836    #[test]
837    fn animation_duration_zero_is_immediate() {
838        let mut state = ValidationErrorState::default();
839        state.show();
840        state.tick(Duration::ZERO);
841        assert_eq!(state.opacity, 1.0);
842        assert!(!state.is_animating());
843    }
844
845    // -- Style tests --
846
847    #[test]
848    fn style_is_applied_to_message() {
849        let custom_style = Style::new().fg(PackedRgba::rgb(100, 200, 50));
850        let error = ValidationErrorDisplay::new("Error")
851            .with_icon("!")
852            .with_style(custom_style);
853        let area = Rect::new(0, 0, 20, 1);
854        let mut pool = GraphemePool::new();
855        let mut frame = Frame::new(20, 1, &mut pool);
856        Widget::render(&error, area, &mut frame);
857
858        // Check message cell has custom fg color
859        let cell = frame.buffer.get(2, 0).unwrap(); // 'R' of "Required"
860        assert_eq!(
861            cell.fg,
862            PackedRgba::rgb(100, 200, 50),
863            "message cell should use the custom fg color"
864        );
865    }
866
867    #[test]
868    fn icon_style_separate_from_message_style() {
869        let error = ValidationErrorDisplay::new("Error")
870            .with_icon("!")
871            .with_icon_style(Style::new().fg(PackedRgba::rgb(255, 255, 0)))
872            .with_style(Style::new().fg(PackedRgba::rgb(255, 0, 0)));
873        let area = Rect::new(0, 0, 20, 1);
874        let mut pool = GraphemePool::new();
875        let mut frame = Frame::new(20, 1, &mut pool);
876        Widget::render(&error, area, &mut frame);
877
878        let icon_cell = frame.buffer.get(0, 0).unwrap();
879        let msg_cell = frame.buffer.get(2, 0).unwrap();
880        // Icon should have yellow, message should have red
881        assert_ne!(icon_cell.fg, msg_cell.fg);
882    }
883
884    // -- Accessibility (invariant 4) --
885
886    fn render_a11y(
887        error: &ValidationErrorDisplay,
888        area: Rect,
889        state: &mut ValidationErrorState,
890    ) -> ftui_a11y::tree::A11yTree {
891        let mut builder = ftui_a11y::tree::A11yTreeBuilder::new();
892        {
893            let mut pool = GraphemePool::new();
894            let mut frame = Frame::new(80, 24, &mut pool);
895            frame.set_a11y(&mut builder);
896            StatefulWidget::render(error, area, &mut frame, state);
897            frame.finish_a11y();
898        }
899        builder.build()
900    }
901
902    fn shown() -> ValidationErrorState {
903        let mut state = ValidationErrorState::default();
904        state.set_visible(true);
905        state
906    }
907
908    /// The module promises screen readers can announce the error; the widget
909    /// used to push no accessibility node at all.
910    #[test]
911    fn a_visible_error_is_announced_with_its_full_message() {
912        let message = "Email address must contain an @ and a domain";
913        for (label, error, width) in [
914            ("full row", ValidationErrorDisplay::new(message), 60),
915            // The row truncates this with an ellipsis; the name must not.
916            ("truncated row", ValidationErrorDisplay::new(message), 12),
917            (
918                "icon only",
919                ValidationErrorDisplay::new(message).icon_only(),
920                60,
921            ),
922        ] {
923            let tree = render_a11y(&error, Rect::new(0, 0, width, 1), &mut shown());
924            let nodes: Vec<_> = tree.nodes().collect();
925            assert_eq!(nodes.len(), 1, "{label}");
926            assert_eq!(nodes[0].role, A11yRole::Label, "{label}");
927            assert_eq!(nodes[0].name.as_deref(), Some(message), "{label}");
928            assert_eq!(nodes[0].live_region, Some(LiveRegion::Polite), "{label}");
929        }
930    }
931
932    #[test]
933    fn a_hidden_error_is_not_in_the_accessibility_tree() {
934        let error = ValidationErrorDisplay::new("Required");
935        let tree = render_a11y(
936            &error,
937            Rect::new(0, 0, 40, 1),
938            &mut ValidationErrorState::default(),
939        );
940        assert_eq!(tree.node_count(), 0);
941    }
942
943    /// `Form` puts each field's error on the field's own node. Its embedded
944    /// display pushing a second one announced every error twice, including
945    /// errors on fields without focus.
946    #[test]
947    fn an_embedding_widget_can_keep_the_error_off_the_tree() {
948        let error = ValidationErrorDisplay::new("Required").without_accessibility_node();
949        let tree = render_a11y(&error, Rect::new(0, 0, 40, 1), &mut shown());
950        assert_eq!(tree.node_count(), 0);
951    }
952
953    /// With an `aria_id` the node keeps its identity as the layout moves, so a
954    /// tree diff sees one error that moved rather than one gone and one new -
955    /// which would announce it again.
956    #[test]
957    fn the_node_id_follows_aria_id_across_layout_changes() {
958        let error = ValidationErrorDisplay::new("Required");
959        let id_at = |area: Rect, aria_id: u32| {
960            let mut state = shown().with_aria_id(aria_id);
961            render_a11y(&error, area, &mut state)
962                .nodes()
963                .next()
964                .expect("a node")
965                .id
966        };
967        let (here, there) = (Rect::new(0, 2, 30, 1), Rect::new(4, 9, 50, 1));
968        assert_eq!(id_at(here, 7), id_at(there, 7));
969        assert_ne!(id_at(here, 7), id_at(here, 8));
970        assert_ne!(
971            id_at(here, 0),
972            id_at(there, 0),
973            "no aria_id: geometry fallback"
974        );
975    }
976}