Skip to main content

ftui_widgets/modal/
container.rs

1#![forbid(unsafe_code)]
2
3//! Modal container widget with backdrop, positioning, and size constraints.
4//!
5//! This widget renders:
6//! 1) a full-screen backdrop (tinted overlay), then
7//! 2) the content widget in a positioned rectangle.
8//!
9//! Optionally registers hit regions for backdrop vs content so callers can
10//! implement close-on-backdrop click behavior using the hit grid.
11
12use crate::Widget;
13use crate::set_style_area;
14use ftui_a11y::node::{A11yNodeInfo, A11yRole};
15use ftui_core::event::{
16    Event, KeyCode, KeyEvent, KeyEventKind, MouseButton, MouseEvent, MouseEventKind,
17};
18use ftui_core::geometry::{Rect, Size};
19use ftui_render::cell::PackedRgba;
20use ftui_render::frame::{Frame, HitData, HitId, HitRegion};
21use ftui_style::Style;
22
23/// Hit region tag for the modal backdrop.
24///
25/// # `Custom` discriminant allocation
26///
27/// `HitRegion::Custom(n)` is a single namespace *per `HitId`*, and a
28/// [`Dialog`](super::Dialog) renders inside a `Modal` under the **same** id -
29/// the container registers the backdrop and content first, then the dialog
30/// overlays its own regions on top. So these and `dialog`'s must not collide.
31/// Every value in use across this module:
32///
33/// | value | constant |
34/// |---|---|
35/// | 1 | [`MODAL_HIT_BACKDROP`] |
36/// | 2 | [`MODAL_HIT_CONTENT`] |
37/// | 3 | [`DIALOG_HIT_INPUT`](super::DIALOG_HIT_INPUT) |
38///
39/// `hit_regions_do_not_collide_across_the_modal_module` holds this table to
40/// its word.
41pub const MODAL_HIT_BACKDROP: HitRegion = HitRegion::Custom(1);
42/// Hit region tag for the modal content.
43///
44/// See the allocation table on [`MODAL_HIT_BACKDROP`].
45pub const MODAL_HIT_CONTENT: HitRegion = HitRegion::Custom(2);
46
47/// Modal action emitted by `ModalState::handle_event`.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum ModalAction {
50    /// The modal should close.
51    Close,
52    /// Backdrop was clicked.
53    BackdropClicked,
54    /// Escape was pressed.
55    EscapePressed,
56}
57
58/// Backdrop configuration (color + opacity).
59#[derive(Debug, Clone, Copy, PartialEq)]
60pub struct BackdropConfig {
61    /// Backdrop color (alpha will be scaled by `opacity`).
62    pub color: PackedRgba,
63    /// Opacity in `[0.0, 1.0]`.
64    pub opacity: f32,
65}
66
67impl BackdropConfig {
68    /// Create a new backdrop config.
69    pub fn new(color: PackedRgba, opacity: f32) -> Self {
70        Self { color, opacity }
71    }
72
73    /// Set backdrop color.
74    #[must_use]
75    pub fn color(mut self, color: PackedRgba) -> Self {
76        self.color = color;
77        self
78    }
79
80    /// Set backdrop opacity.
81    #[must_use]
82    pub fn opacity(mut self, opacity: f32) -> Self {
83        self.opacity = opacity;
84        self
85    }
86}
87
88impl Default for BackdropConfig {
89    fn default() -> Self {
90        Self {
91            color: PackedRgba::rgb(0, 0, 0),
92            opacity: 0.6,
93        }
94    }
95}
96
97/// Modal size constraints (min/max width/height).
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
99pub struct ModalSizeConstraints {
100    pub min_width: Option<u16>,
101    pub max_width: Option<u16>,
102    pub min_height: Option<u16>,
103    pub max_height: Option<u16>,
104}
105
106impl ModalSizeConstraints {
107    /// Create an unconstrained size spec.
108    pub const fn new() -> Self {
109        Self {
110            min_width: None,
111            max_width: None,
112            min_height: None,
113            max_height: None,
114        }
115    }
116
117    /// Set minimum width.
118    #[must_use]
119    pub fn min_width(mut self, value: u16) -> Self {
120        self.min_width = Some(value);
121        self
122    }
123
124    /// Set maximum width.
125    #[must_use]
126    pub fn max_width(mut self, value: u16) -> Self {
127        self.max_width = Some(value);
128        self
129    }
130
131    /// Set minimum height.
132    #[must_use]
133    pub fn min_height(mut self, value: u16) -> Self {
134        self.min_height = Some(value);
135        self
136    }
137
138    /// Set maximum height.
139    #[must_use]
140    pub fn max_height(mut self, value: u16) -> Self {
141        self.max_height = Some(value);
142        self
143    }
144
145    /// Clamp the given size to these constraints (but never exceed available).
146    pub fn clamp(self, available: Size) -> Size {
147        let mut width = available.width;
148        let mut height = available.height;
149
150        if let Some(max_width) = self.max_width {
151            width = width.min(max_width);
152        }
153        if let Some(max_height) = self.max_height {
154            height = height.min(max_height);
155        }
156        if let Some(min_width) = self.min_width {
157            width = width.max(min_width).min(available.width);
158        }
159        if let Some(min_height) = self.min_height {
160            height = height.max(min_height).min(available.height);
161        }
162
163        Size::new(width, height)
164    }
165}
166
167/// Modal positioning options.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
169pub enum ModalPosition {
170    #[default]
171    Center,
172    CenterOffset {
173        x: i16,
174        y: i16,
175    },
176    TopCenter {
177        margin: u16,
178    },
179    Custom {
180        x: u16,
181        y: u16,
182    },
183}
184
185impl ModalPosition {
186    fn resolve(self, area: Rect, size: Size) -> Rect {
187        let base_x = area.x as i32;
188        let base_y = area.y as i32;
189        let max_x = base_x + (area.width as i32 - size.width as i32);
190        let max_y = base_y + (area.height as i32 - size.height as i32);
191
192        let (mut x, mut y) = match self {
193            Self::Center => (
194                base_x + (area.width as i32 - size.width as i32) / 2,
195                base_y + (area.height as i32 - size.height as i32) / 2,
196            ),
197            Self::CenterOffset { x, y } => (
198                base_x + (area.width as i32 - size.width as i32) / 2 + x as i32,
199                base_y + (area.height as i32 - size.height as i32) / 2 + y as i32,
200            ),
201            Self::TopCenter { margin } => (
202                base_x + (area.width as i32 - size.width as i32) / 2,
203                base_y + margin as i32,
204            ),
205            Self::Custom { x, y } => (x as i32, y as i32),
206        };
207
208        x = x.clamp(base_x, max_x);
209        y = y.clamp(base_y, max_y);
210
211        Rect::new(x as u16, y as u16, size.width, size.height)
212    }
213}
214
215/// Modal configuration.
216#[derive(Debug, Clone)]
217pub struct ModalConfig {
218    pub position: ModalPosition,
219    pub backdrop: BackdropConfig,
220    pub size: ModalSizeConstraints,
221    pub close_on_backdrop: bool,
222    pub close_on_escape: bool,
223    pub hit_id: Option<HitId>,
224    /// Optional accessible name for the semantic dialog container.
225    pub accessibility_name: Option<String>,
226    /// Optional stable identity for the semantic dialog container.
227    pub accessibility_id: Option<u64>,
228    /// Whether this generic modal should contribute its own Dialog container.
229    ///
230    /// Composite widgets such as the built-in Dialog disable this because they
231    /// already provide a richer named dialog node from their stateful render path.
232    pub accessibility_container: bool,
233}
234
235impl Default for ModalConfig {
236    fn default() -> Self {
237        Self {
238            position: ModalPosition::Center,
239            backdrop: BackdropConfig::default(),
240            size: ModalSizeConstraints::default(),
241            close_on_backdrop: true,
242            close_on_escape: true,
243            hit_id: None,
244            accessibility_name: None,
245            accessibility_id: None,
246            accessibility_container: true,
247        }
248    }
249}
250
251impl ModalConfig {
252    #[must_use]
253    pub fn position(mut self, position: ModalPosition) -> Self {
254        self.position = position;
255        self
256    }
257
258    #[must_use]
259    pub fn backdrop(mut self, backdrop: BackdropConfig) -> Self {
260        self.backdrop = backdrop;
261        self
262    }
263
264    #[must_use]
265    pub fn size(mut self, size: ModalSizeConstraints) -> Self {
266        self.size = size;
267        self
268    }
269
270    #[must_use]
271    pub fn close_on_backdrop(mut self, close: bool) -> Self {
272        self.close_on_backdrop = close;
273        self
274    }
275
276    #[must_use]
277    pub fn close_on_escape(mut self, close: bool) -> Self {
278        self.close_on_escape = close;
279        self
280    }
281
282    #[must_use]
283    pub fn hit_id(mut self, id: HitId) -> Self {
284        self.hit_id = Some(id);
285        self
286    }
287
288    /// Set the accessible name of the generic modal container.
289    #[must_use]
290    pub fn accessibility_name(mut self, name: impl Into<String>) -> Self {
291        self.accessibility_name = Some(name.into());
292        self
293    }
294
295    /// Set a stable accessibility identity independent of modal geometry.
296    #[must_use]
297    pub fn accessibility_id(mut self, id: u64) -> Self {
298        self.accessibility_id = Some(id);
299        self
300    }
301
302    /// Enable or suppress the generic semantic Dialog wrapper.
303    #[must_use]
304    pub fn accessibility_container(mut self, enabled: bool) -> Self {
305        self.accessibility_container = enabled;
306        self
307    }
308}
309
310/// Stateful helper for modal close behavior.
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312pub struct ModalState {
313    open: bool,
314}
315
316impl Default for ModalState {
317    fn default() -> Self {
318        Self { open: true }
319    }
320}
321
322impl ModalState {
323    #[inline]
324    pub fn is_open(&self) -> bool {
325        self.open
326    }
327
328    pub fn open(&mut self) {
329        self.open = true;
330    }
331
332    pub fn close(&mut self) {
333        self.open = false;
334    }
335
336    /// Handle events and return a modal action if triggered.
337    ///
338    /// The caller should pass the hit-test result for the mouse event
339    /// (usually from the last rendered frame).
340    pub fn handle_event(
341        &mut self,
342        event: &Event,
343        hit: Option<(HitId, HitRegion, HitData)>,
344        config: &ModalConfig,
345    ) -> Option<ModalAction> {
346        if !self.open {
347            return None;
348        }
349
350        match event {
351            Event::Key(KeyEvent {
352                code: KeyCode::Escape,
353                kind: KeyEventKind::Press,
354                ..
355            }) if config.close_on_escape => {
356                self.open = false;
357                return Some(ModalAction::EscapePressed);
358            }
359            Event::Mouse(MouseEvent {
360                kind: MouseEventKind::Down(MouseButton::Left),
361                ..
362            }) if config.close_on_backdrop => {
363                if let (Some((id, region, _)), Some(expected)) = (hit, config.hit_id)
364                    && id == expected
365                    && region == MODAL_HIT_BACKDROP
366                {
367                    self.open = false;
368                    return Some(ModalAction::BackdropClicked);
369                }
370            }
371            _ => {}
372        }
373
374        None
375    }
376}
377
378/// Modal container widget.
379///
380/// Invariants:
381/// - `content_rect()` is always clamped within the given `area`.
382/// - Size constraints are applied before positioning and never exceed `area`.
383///
384/// Failure modes:
385/// - If the available `area` is empty or constraints clamp to zero size,
386///   the content is not rendered.
387/// - `close_on_backdrop` requires `hit_id` to be set; otherwise backdrop clicks
388///   cannot be distinguished from content clicks.
389#[derive(Debug, Clone)]
390pub struct Modal<C> {
391    content: C,
392    config: ModalConfig,
393}
394
395impl<C> Modal<C> {
396    /// Create a new modal with content.
397    pub fn new(content: C) -> Self {
398        Self {
399            content,
400            config: ModalConfig::default(),
401        }
402    }
403
404    /// Set modal configuration.
405    #[must_use]
406    pub fn config(mut self, config: ModalConfig) -> Self {
407        self.config = config;
408        self
409    }
410
411    /// Set modal position.
412    #[must_use]
413    pub fn position(mut self, position: ModalPosition) -> Self {
414        self.config.position = position;
415        self
416    }
417
418    /// Set backdrop configuration.
419    #[must_use]
420    pub fn backdrop(mut self, backdrop: BackdropConfig) -> Self {
421        self.config.backdrop = backdrop;
422        self
423    }
424
425    /// Set size constraints.
426    #[must_use]
427    pub fn size(mut self, size: ModalSizeConstraints) -> Self {
428        self.config.size = size;
429        self
430    }
431
432    /// Set close-on-backdrop behavior.
433    #[must_use]
434    pub fn close_on_backdrop(mut self, close: bool) -> Self {
435        self.config.close_on_backdrop = close;
436        self
437    }
438
439    /// Set close-on-escape behavior.
440    #[must_use]
441    pub fn close_on_escape(mut self, close: bool) -> Self {
442        self.config.close_on_escape = close;
443        self
444    }
445
446    /// Set the hit id used for backdrop/content hit regions.
447    #[must_use]
448    pub fn hit_id(mut self, id: HitId) -> Self {
449        self.config.hit_id = Some(id);
450        self
451    }
452
453    /// Set the accessible name of the generic modal container.
454    #[must_use]
455    pub fn accessibility_name(mut self, name: impl Into<String>) -> Self {
456        self.config.accessibility_name = Some(name.into());
457        self
458    }
459
460    /// Set a stable accessibility identity independent of modal geometry.
461    #[must_use]
462    pub fn accessibility_id(mut self, id: u64) -> Self {
463        self.config.accessibility_id = Some(id);
464        self
465    }
466
467    /// Enable or suppress the generic semantic Dialog wrapper.
468    #[must_use]
469    pub fn accessibility_container(mut self, enabled: bool) -> Self {
470        self.config.accessibility_container = enabled;
471        self
472    }
473
474    /// Compute the content rectangle for the given area.
475    pub fn content_rect(&self, area: Rect) -> Rect {
476        let available = Size::new(area.width, area.height);
477        let size = self.config.size.clamp(available);
478        if size.width == 0 || size.height == 0 {
479            return Rect::new(area.x, area.y, 0, 0);
480        }
481        self.config.position.resolve(area, size)
482    }
483}
484
485impl<C: Widget> Widget for Modal<C> {
486    fn render(&self, area: Rect, frame: &mut Frame) {
487        if area.is_empty() {
488            return;
489        }
490
491        // Backdrop (full area), preserving existing glyphs.
492        let opacity = self.config.backdrop.opacity.clamp(0.0, 1.0);
493        if opacity > 0.0 {
494            let bg = self.config.backdrop.color.with_opacity(opacity);
495            set_style_area(&mut frame.buffer, area, Style::new().bg(bg));
496        }
497
498        // Register hit regions BEFORE content renders so the inner widget
499        // (e.g. Dialog) can overlay more specific hits (buttons) on top.
500        let content_area = self.content_rect(area);
501        if let Some(hit_id) = self.config.hit_id {
502            frame.register_hit(area, hit_id, MODAL_HIT_BACKDROP, 0);
503            if !content_area.is_empty() {
504                frame.register_hit(content_area, hit_id, MODAL_HIT_CONTENT, 0);
505            }
506        }
507
508        if !content_area.is_empty() {
509            let bounds = content_area.intersection(&frame.buffer.current_scissor());
510            if self.config.accessibility_container && frame.a11y_enabled() && !bounds.is_empty() {
511                let id = self.config.accessibility_id.unwrap_or_else(|| {
512                    self.config.hit_id.map_or_else(
513                        || A11yNodeInfo::stable_id_for(A11yRole::Dialog, content_area),
514                        |hit| u64::from(hit.id()),
515                    )
516                });
517                let node = A11yNodeInfo::new(id, A11yRole::Dialog, bounds)
518                    .with_name(self.config.accessibility_name.as_deref().unwrap_or("Modal"));
519                frame.with_a11y_scope(node, |frame| self.content.render(content_area, frame));
520            } else {
521                self.content.render(content_area, frame);
522            }
523        }
524    }
525}
526
527#[cfg(test)]
528mod tests {
529    use super::*;
530    use ftui_a11y::node::{A11yNodeInfo, A11yRole};
531    use ftui_a11y::tree::{A11yTree, A11yTreeBuilder, ScreenReaderPolicy};
532    use ftui_render::frame::Frame;
533    use ftui_render::grapheme_pool::GraphemePool;
534
535    #[derive(Debug, Clone)]
536    struct Stub;
537
538    impl Widget for Stub {
539        fn render(&self, _area: Rect, _frame: &mut Frame) {}
540    }
541
542    #[derive(Debug, Clone)]
543    struct AccessibleStub;
544
545    impl Widget for AccessibleStub {
546        fn render(&self, area: Rect, frame: &mut Frame) {
547            let mut node = A11yNodeInfo::new(9001, A11yRole::Button, area).with_name("Continue");
548            node.state.focused = true;
549            frame.push_a11y(node);
550        }
551    }
552
553    fn render_modal_a11y(modal: &Modal<AccessibleStub>, area: Rect) -> A11yTree {
554        let mut builder = A11yTreeBuilder::new();
555        {
556            let mut pool = GraphemePool::new();
557            let mut frame = Frame::new(80, 24, &mut pool);
558            frame.set_a11y(&mut builder);
559            modal.render(area, &mut frame);
560            frame.finish_a11y();
561        }
562        builder.build()
563    }
564
565    #[test]
566    fn generic_modal_scopes_accessible_content_under_a_dialog() {
567        let modal = Modal::new(AccessibleStub)
568            .size(
569                ModalSizeConstraints::new()
570                    .min_width(20)
571                    .max_width(20)
572                    .min_height(6)
573                    .max_height(6),
574            )
575            .accessibility_name("Preferences")
576            .accessibility_id(8001);
577        let tree = render_modal_a11y(&modal, Rect::new(0, 0, 60, 20));
578        assert_eq!(tree.root_id(), Some(8001));
579        let root = tree.root().unwrap();
580        assert_eq!(root.role, A11yRole::Dialog);
581        assert_eq!(root.name.as_deref(), Some("Preferences"));
582        assert_eq!(root.children, vec![9001]);
583        assert_eq!(tree.node(9001).unwrap().parent, Some(8001));
584        assert_eq!(tree.focused_id(), Some(9001));
585
586        let first = tree
587            .screen_reader_announcements_since(&A11yTree::empty(), ScreenReaderPolicy::default());
588        assert_eq!(first.announcements.len(), 1);
589    }
590
591    #[test]
592    fn modal_hit_id_stabilizes_semantic_identity_across_geometry_changes() {
593        let modal = Modal::new(AccessibleStub)
594            .size(
595                ModalSizeConstraints::new()
596                    .min_width(12)
597                    .max_width(12)
598                    .min_height(4)
599                    .max_height(4),
600            )
601            .hit_id(HitId::new(77))
602            .accessibility_name("Stable");
603        let before = render_modal_a11y(&modal, Rect::new(0, 0, 40, 12));
604        let after = render_modal_a11y(&modal, Rect::new(5, 3, 50, 18));
605        assert_eq!(before.root_id(), Some(77));
606        assert_eq!(before.root_id(), after.root_id());
607        assert_eq!(before.focused_id(), after.focused_id());
608        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
609        assert!(batch.announcements.is_empty());
610    }
611
612    #[test]
613    fn modal_semantic_wrapper_can_be_suppressed_for_richer_composites() {
614        let modal = Modal::new(AccessibleStub)
615            .accessibility_container(false)
616            .accessibility_name("Ignored");
617        let tree = render_modal_a11y(&modal, Rect::new(0, 0, 20, 6));
618        assert_eq!(tree.node_count(), 1);
619        assert_eq!(tree.root_id(), Some(9001));
620        assert_eq!(tree.root().unwrap().role, A11yRole::Button);
621    }
622
623    #[test]
624    fn center_positioning() {
625        let modal = Modal::new(Stub).size(
626            ModalSizeConstraints::new()
627                .min_width(10)
628                .max_width(10)
629                .min_height(4)
630                .max_height(4),
631        );
632        let area = Rect::new(0, 0, 40, 20);
633        let rect = modal.content_rect(area);
634        assert_eq!(rect, Rect::new(15, 8, 10, 4));
635    }
636
637    #[test]
638    fn offset_positioning() {
639        let modal = Modal::new(Stub)
640            .size(
641                ModalSizeConstraints::new()
642                    .min_width(10)
643                    .max_width(10)
644                    .min_height(4)
645                    .max_height(4),
646            )
647            .position(ModalPosition::CenterOffset { x: -2, y: 3 });
648        let area = Rect::new(0, 0, 40, 20);
649        let rect = modal.content_rect(area);
650        assert_eq!(rect, Rect::new(13, 11, 10, 4));
651    }
652
653    #[test]
654    fn size_constraints_respect_available() {
655        let modal = Modal::new(Stub).size(
656            ModalSizeConstraints::new()
657                .min_width(10)
658                .max_width(30)
659                .min_height(6)
660                .max_height(20),
661        );
662        let area = Rect::new(0, 0, 8, 4);
663        let rect = modal.content_rect(area);
664        assert_eq!(rect.width, 8);
665        assert_eq!(rect.height, 4);
666    }
667
668    #[test]
669    fn hit_regions_registered() {
670        let modal = Modal::new(Stub)
671            .size(
672                ModalSizeConstraints::new()
673                    .min_width(6)
674                    .max_width(6)
675                    .min_height(3)
676                    .max_height(3),
677            )
678            .hit_id(HitId::new(7));
679
680        let mut pool = GraphemePool::new();
681        let mut frame = Frame::with_hit_grid(20, 10, &mut pool);
682        let area = Rect::new(0, 0, 20, 10);
683        modal.render(area, &mut frame);
684
685        let backdrop_hit = frame.hit_test(0, 0);
686        assert_eq!(backdrop_hit, Some((HitId::new(7), MODAL_HIT_BACKDROP, 0)));
687
688        let content = modal.content_rect(area);
689        let cx = content.x + 1;
690        let cy = content.y + 1;
691        let content_hit = frame.hit_test(cx, cy);
692        assert_eq!(content_hit, Some((HitId::new(7), MODAL_HIT_CONTENT, 0)));
693    }
694
695    #[test]
696    fn backdrop_click_triggers_close() {
697        let mut state = ModalState::default();
698        let config = ModalConfig::default().hit_id(HitId::new(9));
699        let hit = Some((HitId::new(9), MODAL_HIT_BACKDROP, 0));
700        let event = Event::Mouse(MouseEvent::new(
701            MouseEventKind::Down(MouseButton::Left),
702            0,
703            0,
704        ));
705
706        let action = state.handle_event(&event, hit, &config);
707        assert_eq!(action, Some(ModalAction::BackdropClicked));
708        assert!(!state.is_open());
709    }
710
711    #[test]
712    fn content_rect_within_bounds_for_positions() {
713        let base_constraints = ModalSizeConstraints::new()
714            .min_width(2)
715            .min_height(2)
716            .max_width(30)
717            .max_height(10);
718        let positions = [
719            ModalPosition::Center,
720            ModalPosition::CenterOffset { x: 3, y: -2 },
721            ModalPosition::TopCenter { margin: 1 },
722            ModalPosition::Custom { x: 100, y: 100 },
723        ];
724        let areas = [
725            Rect::new(0, 0, 10, 6),
726            Rect::new(2, 3, 40, 20),
727            Rect::new(5, 1, 8, 4),
728        ];
729
730        for area in areas {
731            for &position in &positions {
732                let modal = Modal::new(Stub).size(base_constraints).position(position);
733                let rect = modal.content_rect(area);
734                if rect.is_empty() {
735                    continue;
736                }
737                assert!(rect.x >= area.x);
738                assert!(rect.y >= area.y);
739                assert!(rect.right() <= area.right());
740                assert!(rect.bottom() <= area.bottom());
741            }
742        }
743    }
744
745    // --- BackdropConfig tests ---
746
747    #[test]
748    fn backdrop_config_default() {
749        let bd = BackdropConfig::default();
750        assert_eq!(bd.color, PackedRgba::rgb(0, 0, 0));
751        assert!((bd.opacity - 0.6).abs() < f32::EPSILON);
752    }
753
754    #[test]
755    fn backdrop_config_new_and_builders() {
756        let bd = BackdropConfig::new(PackedRgba::rgb(255, 0, 0), 0.8)
757            .color(PackedRgba::rgb(0, 255, 0))
758            .opacity(0.3);
759        assert_eq!(bd.color, PackedRgba::rgb(0, 255, 0));
760        assert!((bd.opacity - 0.3).abs() < f32::EPSILON);
761    }
762
763    // --- ModalSizeConstraints tests ---
764
765    #[test]
766    fn size_constraints_unconstrained() {
767        let c = ModalSizeConstraints::new();
768        let result = c.clamp(Size::new(40, 20));
769        assert_eq!(result, Size::new(40, 20));
770    }
771
772    #[test]
773    fn size_constraints_max_only() {
774        let c = ModalSizeConstraints::new().max_width(10).max_height(5);
775        let result = c.clamp(Size::new(40, 20));
776        assert_eq!(result, Size::new(10, 5));
777    }
778
779    #[test]
780    fn size_constraints_min_only() {
781        let c = ModalSizeConstraints::new().min_width(10).min_height(5);
782        // Available is larger than min: result = available
783        assert_eq!(c.clamp(Size::new(40, 20)), Size::new(40, 20));
784    }
785
786    #[test]
787    fn size_constraints_min_exceeds_available() {
788        let c = ModalSizeConstraints::new().min_width(50).min_height(30);
789        // min > available: clamped back to available
790        let result = c.clamp(Size::new(10, 6));
791        assert_eq!(result, Size::new(10, 6));
792    }
793
794    #[test]
795    fn size_constraints_zero_available() {
796        let c = ModalSizeConstraints::new()
797            .min_width(10)
798            .max_width(20)
799            .min_height(5)
800            .max_height(10);
801        let result = c.clamp(Size::new(0, 0));
802        assert_eq!(result, Size::new(0, 0));
803    }
804
805    #[test]
806    fn size_constraints_min_and_max_equal() {
807        let c = ModalSizeConstraints::new()
808            .min_width(10)
809            .max_width(10)
810            .min_height(5)
811            .max_height(5);
812        let result = c.clamp(Size::new(40, 20));
813        assert_eq!(result, Size::new(10, 5));
814    }
815
816    #[test]
817    fn size_constraints_default_is_unconstrained() {
818        let c = ModalSizeConstraints::default();
819        assert_eq!(c.min_width, None);
820        assert_eq!(c.max_width, None);
821        assert_eq!(c.min_height, None);
822        assert_eq!(c.max_height, None);
823    }
824
825    // --- ModalPosition tests ---
826
827    #[test]
828    fn position_top_center() {
829        let pos = ModalPosition::TopCenter { margin: 2 };
830        let area = Rect::new(0, 0, 40, 20);
831        let size = Size::new(10, 4);
832        let rect = pos.resolve(area, size);
833        assert_eq!(rect.x, 15); // centered: (40-10)/2 = 15
834        assert_eq!(rect.y, 2); // margin from top
835        assert_eq!(rect.width, 10);
836        assert_eq!(rect.height, 4);
837    }
838
839    #[test]
840    fn position_custom_within_bounds() {
841        let pos = ModalPosition::Custom { x: 5, y: 3 };
842        let area = Rect::new(0, 0, 40, 20);
843        let size = Size::new(10, 4);
844        let rect = pos.resolve(area, size);
845        assert_eq!(rect, Rect::new(5, 3, 10, 4));
846    }
847
848    #[test]
849    fn position_custom_clamped_to_area() {
850        // Custom position beyond area bounds gets clamped
851        let pos = ModalPosition::Custom { x: 100, y: 100 };
852        let area = Rect::new(0, 0, 40, 20);
853        let size = Size::new(10, 4);
854        let rect = pos.resolve(area, size);
855        assert_eq!(rect.x, 30); // max_x = 40-10
856        assert_eq!(rect.y, 16); // max_y = 20-4
857    }
858
859    #[test]
860    fn position_center_offset_clamped() {
861        // Large negative offset gets clamped to area origin
862        let pos = ModalPosition::CenterOffset { x: -100, y: -100 };
863        let area = Rect::new(0, 0, 40, 20);
864        let size = Size::new(10, 4);
865        let rect = pos.resolve(area, size);
866        assert_eq!(rect.x, 0);
867        assert_eq!(rect.y, 0);
868    }
869
870    #[test]
871    fn position_default_is_center() {
872        assert_eq!(ModalPosition::default(), ModalPosition::Center);
873    }
874
875    #[test]
876    fn position_resolve_with_nonzero_area_origin() {
877        let pos = ModalPosition::Center;
878        let area = Rect::new(10, 5, 40, 20);
879        let size = Size::new(10, 4);
880        let rect = pos.resolve(area, size);
881        // center_x = 10 + (40-10)/2 = 25
882        // center_y = 5 + (20-4)/2 = 13
883        assert_eq!(rect, Rect::new(25, 13, 10, 4));
884    }
885
886    #[test]
887    fn position_top_center_with_area_offset() {
888        let pos = ModalPosition::TopCenter { margin: 1 };
889        let area = Rect::new(5, 3, 20, 10);
890        let size = Size::new(8, 4);
891        let rect = pos.resolve(area, size);
892        // center_x = 5 + (20-8)/2 = 11
893        // y = 3 + 1 = 4
894        assert_eq!(rect, Rect::new(11, 4, 8, 4));
895    }
896
897    // --- ModalConfig tests ---
898
899    #[test]
900    fn modal_config_default_values() {
901        let config = ModalConfig::default();
902        assert_eq!(config.position, ModalPosition::Center);
903        assert!(config.close_on_backdrop);
904        assert!(config.close_on_escape);
905        assert!(config.hit_id.is_none());
906    }
907
908    #[test]
909    fn modal_config_builder_chain() {
910        let config = ModalConfig::default()
911            .position(ModalPosition::TopCenter { margin: 5 })
912            .backdrop(BackdropConfig::new(PackedRgba::rgb(255, 0, 0), 0.5))
913            .size(ModalSizeConstraints::new().max_width(20))
914            .close_on_backdrop(false)
915            .close_on_escape(false)
916            .hit_id(HitId::new(42));
917        assert_eq!(config.position, ModalPosition::TopCenter { margin: 5 });
918        assert!(!config.close_on_backdrop);
919        assert!(!config.close_on_escape);
920        assert_eq!(config.hit_id, Some(HitId::new(42)));
921    }
922
923    // --- ModalState tests ---
924
925    #[test]
926    fn modal_state_default_is_open() {
927        let state = ModalState::default();
928        assert!(state.is_open());
929    }
930
931    #[test]
932    fn modal_state_open_close_lifecycle() {
933        let mut state = ModalState::default();
934        assert!(state.is_open());
935        state.close();
936        assert!(!state.is_open());
937        state.open();
938        assert!(state.is_open());
939    }
940
941    #[test]
942    fn modal_state_escape_closes() {
943        let mut state = ModalState::default();
944        let config = ModalConfig::default();
945        let event = Event::Key(KeyEvent::new(KeyCode::Escape));
946        let action = state.handle_event(&event, None, &config);
947        assert_eq!(action, Some(ModalAction::EscapePressed));
948        assert!(!state.is_open());
949    }
950
951    #[test]
952    fn modal_state_escape_disabled() {
953        let mut state = ModalState::default();
954        let config = ModalConfig::default().close_on_escape(false);
955        let event = Event::Key(KeyEvent::new(KeyCode::Escape));
956        let action = state.handle_event(&event, None, &config);
957        assert_eq!(action, None);
958        assert!(state.is_open());
959    }
960
961    #[test]
962    fn modal_state_closed_ignores_events() {
963        let mut state = ModalState::default();
964        state.close();
965        let config = ModalConfig::default();
966        let event = Event::Key(KeyEvent::new(KeyCode::Escape));
967        let action = state.handle_event(&event, None, &config);
968        assert_eq!(action, None);
969        assert!(!state.is_open());
970    }
971
972    #[test]
973    fn modal_state_content_click_does_not_close() {
974        let mut state = ModalState::default();
975        let config = ModalConfig::default().hit_id(HitId::new(1));
976        let hit = Some((HitId::new(1), MODAL_HIT_CONTENT, 0));
977        let event = Event::Mouse(MouseEvent::new(
978            MouseEventKind::Down(MouseButton::Left),
979            5,
980            5,
981        ));
982        let action = state.handle_event(&event, hit, &config);
983        assert_eq!(action, None);
984        assert!(state.is_open());
985    }
986
987    #[test]
988    fn modal_state_backdrop_click_wrong_hit_id() {
989        let mut state = ModalState::default();
990        let config = ModalConfig::default().hit_id(HitId::new(1));
991        // Hit id doesn't match config
992        let hit = Some((HitId::new(999), MODAL_HIT_BACKDROP, 0));
993        let event = Event::Mouse(MouseEvent::new(
994            MouseEventKind::Down(MouseButton::Left),
995            0,
996            0,
997        ));
998        let action = state.handle_event(&event, hit, &config);
999        assert_eq!(action, None);
1000        assert!(state.is_open());
1001    }
1002
1003    #[test]
1004    fn modal_state_backdrop_click_no_hit_id_in_config() {
1005        let mut state = ModalState::default();
1006        // close_on_backdrop is true, but config has no hit_id
1007        let config = ModalConfig::default();
1008        let hit = Some((HitId::new(1), MODAL_HIT_BACKDROP, 0));
1009        let event = Event::Mouse(MouseEvent::new(
1010            MouseEventKind::Down(MouseButton::Left),
1011            0,
1012            0,
1013        ));
1014        let action = state.handle_event(&event, hit, &config);
1015        assert_eq!(action, None);
1016        assert!(state.is_open());
1017    }
1018
1019    #[test]
1020    fn modal_state_backdrop_click_disabled() {
1021        let mut state = ModalState::default();
1022        let config = ModalConfig::default()
1023            .hit_id(HitId::new(1))
1024            .close_on_backdrop(false);
1025        let hit = Some((HitId::new(1), MODAL_HIT_BACKDROP, 0));
1026        let event = Event::Mouse(MouseEvent::new(
1027            MouseEventKind::Down(MouseButton::Left),
1028            0,
1029            0,
1030        ));
1031        let action = state.handle_event(&event, hit, &config);
1032        assert_eq!(action, None);
1033        assert!(state.is_open());
1034    }
1035
1036    #[test]
1037    fn modal_state_right_click_does_not_close() {
1038        let mut state = ModalState::default();
1039        let config = ModalConfig::default().hit_id(HitId::new(1));
1040        let hit = Some((HitId::new(1), MODAL_HIT_BACKDROP, 0));
1041        let event = Event::Mouse(MouseEvent::new(
1042            MouseEventKind::Down(MouseButton::Right),
1043            0,
1044            0,
1045        ));
1046        let action = state.handle_event(&event, hit, &config);
1047        assert_eq!(action, None);
1048        assert!(state.is_open());
1049    }
1050
1051    #[test]
1052    fn modal_state_no_hit_data_backdrop_click() {
1053        let mut state = ModalState::default();
1054        let config = ModalConfig::default().hit_id(HitId::new(1));
1055        // No hit (mouse missed all regions)
1056        let event = Event::Mouse(MouseEvent::new(
1057            MouseEventKind::Down(MouseButton::Left),
1058            0,
1059            0,
1060        ));
1061        let action = state.handle_event(&event, None, &config);
1062        assert_eq!(action, None);
1063        assert!(state.is_open());
1064    }
1065
1066    // --- Modal widget tests ---
1067
1068    #[test]
1069    fn modal_content_rect_zero_area() {
1070        let modal = Modal::new(Stub);
1071        let area = Rect::new(0, 0, 0, 0);
1072        let rect = modal.content_rect(area);
1073        assert!(rect.is_empty());
1074    }
1075
1076    #[test]
1077    fn modal_render_empty_area_does_nothing() {
1078        let modal = Modal::new(Stub);
1079        let mut pool = GraphemePool::new();
1080        let mut frame = Frame::with_hit_grid(10, 10, &mut pool);
1081        // Empty area should be a no-op
1082        modal.render(Rect::new(0, 0, 0, 0), &mut frame);
1083        // No hits registered
1084        assert_eq!(frame.hit_test(0, 0), None);
1085    }
1086
1087    #[test]
1088    fn modal_no_hit_regions_without_hit_id() {
1089        let modal = Modal::new(Stub).size(
1090            ModalSizeConstraints::new()
1091                .min_width(4)
1092                .max_width(4)
1093                .min_height(2)
1094                .max_height(2),
1095        );
1096        let mut pool = GraphemePool::new();
1097        let mut frame = Frame::with_hit_grid(20, 10, &mut pool);
1098        modal.render(Rect::new(0, 0, 20, 10), &mut frame);
1099        // No hit_id -> no hit regions
1100        assert_eq!(frame.hit_test(0, 0), None);
1101        assert_eq!(frame.hit_test(10, 5), None);
1102    }
1103
1104    #[test]
1105    fn modal_builder_methods() {
1106        let modal = Modal::new(Stub)
1107            .position(ModalPosition::TopCenter { margin: 3 })
1108            .backdrop(BackdropConfig::new(PackedRgba::rgb(0, 0, 0), 0.5))
1109            .size(ModalSizeConstraints::new().max_width(10).max_height(5))
1110            .close_on_backdrop(false)
1111            .close_on_escape(false)
1112            .hit_id(HitId::new(99));
1113
1114        assert_eq!(
1115            modal.config.position,
1116            ModalPosition::TopCenter { margin: 3 }
1117        );
1118        assert!(!modal.config.close_on_backdrop);
1119        assert!(!modal.config.close_on_escape);
1120        assert_eq!(modal.config.hit_id, Some(HitId::new(99)));
1121    }
1122
1123    #[test]
1124    fn modal_config_method_replaces_full_config() {
1125        let config = ModalConfig::default()
1126            .close_on_escape(false)
1127            .hit_id(HitId::new(5));
1128        let modal = Modal::new(Stub).config(config);
1129        assert!(!modal.config.close_on_escape);
1130        assert_eq!(modal.config.hit_id, Some(HitId::new(5)));
1131    }
1132
1133    #[test]
1134    fn modal_content_rect_size_bigger_than_area() {
1135        // When content size exceeds area, it gets clamped
1136        let modal = Modal::new(Stub).size(
1137            ModalSizeConstraints::new()
1138                .min_width(100)
1139                .max_width(100)
1140                .min_height(100)
1141                .max_height(100),
1142        );
1143        let area = Rect::new(0, 0, 20, 10);
1144        let rect = modal.content_rect(area);
1145        // min > available: clamped to available
1146        assert_eq!(rect.width, 20);
1147        assert_eq!(rect.height, 10);
1148    }
1149
1150    // --- ModalAction tests ---
1151
1152    #[test]
1153    fn modal_action_variants_are_distinct() {
1154        assert_ne!(ModalAction::Close, ModalAction::BackdropClicked);
1155        assert_ne!(ModalAction::Close, ModalAction::EscapePressed);
1156        assert_ne!(ModalAction::BackdropClicked, ModalAction::EscapePressed);
1157    }
1158
1159    // --- Hit region constants ---
1160
1161    #[test]
1162    fn hit_region_constants_are_distinct() {
1163        assert_ne!(MODAL_HIT_BACKDROP, MODAL_HIT_CONTENT);
1164    }
1165}