Skip to main content

native_gui_core/
focus.rs

1//! Focus and tab-order model.
2//!
3//! Portable focusability (per-kind defaults plus a `WidgetSpec` override),
4//! 2D directional projection navigation engine ([`FocusDirection::Up`],
5//! [`FocusDirection::Down`], [`FocusDirection::Left`], [`FocusDirection::Right`]),
6//! sequential tab traversal ([`FocusDirection::TabNext`], [`FocusDirection::TabPrev`]),
7//! spatial candidate scoring, and focus ring styling metrics conforming to
8//! platform guidelines and WCAG 2.4.7 / 2.4.11 / 2.4.13 requirements.
9//!
10//! See the `cap-002b-native-focus-contract.md` decision record for the normative contract.
11#![allow(unexpected_cfgs)]
12
13#[cfg(all(test, not(test_standalone)))]
14use crate::widgets::abstractable_widget_types;
15#[cfg(not(test_standalone))]
16use crate::widgets::{CanvasRect, Color, WidgetId, WidgetKind, WidgetSpec};
17
18#[cfg(test_standalone)]
19pub use standalone_stubs::*;
20
21#[cfg(test_standalone)]
22mod standalone_stubs {
23    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24    pub struct Color {
25        pub r: u8,
26        pub g: u8,
27        pub b: u8,
28    }
29
30    impl Color {
31        pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
32            Self { r, g, b }
33        }
34    }
35
36    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37    pub struct CanvasRect {
38        pub x: i32,
39        pub y: i32,
40        pub width: i32,
41        pub height: i32,
42    }
43
44    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45    pub struct WidgetId(pub u64);
46
47    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48    pub enum WidgetKind {
49        Window,
50        Container,
51        Label,
52        Button,
53        RadioButton,
54        #[cfg(feature = "widgets-range")]
55        Slider,
56        #[cfg(feature = "widgets-range")]
57        SpinBox,
58        #[cfg(feature = "widgets-containers")]
59        Separator,
60        #[cfg(feature = "widgets-containers")]
61        GroupBox,
62        #[cfg(feature = "widgets-containers")]
63        Tabs,
64        #[cfg(feature = "widgets-media")]
65        Image,
66        #[cfg(feature = "widgets-pickers")]
67        DatePicker,
68        #[cfg(feature = "widgets-text")]
69        LinkLabel,
70        #[cfg(feature = "widgets-data")]
71        ListView,
72        #[cfg(feature = "widgets-data")]
73        TreeView,
74        #[cfg(feature = "widgets-containers")]
75        SplitPane,
76        #[cfg(feature = "widgets-pickers")]
77        FileChooserDialog,
78        #[cfg(feature = "widgets-containers")]
79        AlertDialog,
80        #[cfg(feature = "widgets-text")]
81        TextInput,
82        #[cfg(feature = "widgets-text")]
83        TextArea,
84        #[cfg(feature = "widgets-canvas")]
85        VulkanCanvas,
86        Checkbox,
87        ComboBox,
88        #[cfg(feature = "widgets-range")]
89        ProgressBar,
90        #[cfg(feature = "widgets-data")]
91        DataList,
92        #[cfg(feature = "widgets-data")]
93        DataGrid,
94        #[cfg(feature = "widgets-canvas")]
95        Canvas,
96        #[cfg(feature = "widgets-pickers")]
97        ColorDialog,
98        #[cfg(feature = "widgets-pickers")]
99        FontDialog,
100        Toolbar,
101        #[cfg(feature = "widgets-pickers")]
102        Calendar,
103    }
104
105    pub fn abstractable_widget_types() -> &'static [WidgetKind] {
106        &[
107            WidgetKind::Window,
108            WidgetKind::Container,
109            WidgetKind::Label,
110            WidgetKind::Button,
111            #[cfg(feature = "widgets-choice")]
112            WidgetKind::RadioButton,
113            #[cfg(feature = "widgets-range")]
114            WidgetKind::Slider,
115            #[cfg(feature = "widgets-range")]
116            WidgetKind::SpinBox,
117            #[cfg(feature = "widgets-containers")]
118            WidgetKind::Separator,
119            #[cfg(feature = "widgets-containers")]
120            WidgetKind::GroupBox,
121            #[cfg(feature = "widgets-containers")]
122            WidgetKind::Tabs,
123            #[cfg(feature = "widgets-media")]
124            WidgetKind::Image,
125            #[cfg(feature = "widgets-pickers")]
126            WidgetKind::DatePicker,
127            #[cfg(feature = "widgets-text")]
128            WidgetKind::LinkLabel,
129            #[cfg(feature = "widgets-data")]
130            WidgetKind::ListView,
131            #[cfg(feature = "widgets-data")]
132            WidgetKind::TreeView,
133            #[cfg(feature = "widgets-containers")]
134            WidgetKind::SplitPane,
135            #[cfg(feature = "widgets-pickers")]
136            WidgetKind::FileChooserDialog,
137            #[cfg(feature = "widgets-containers")]
138            WidgetKind::AlertDialog,
139            #[cfg(feature = "widgets-text")]
140            WidgetKind::TextInput,
141            #[cfg(feature = "widgets-text")]
142            WidgetKind::TextArea,
143            #[cfg(feature = "widgets-canvas")]
144            WidgetKind::VulkanCanvas,
145            #[cfg(feature = "widgets-choice")]
146            WidgetKind::Checkbox,
147            #[cfg(feature = "widgets-choice")]
148            WidgetKind::ComboBox,
149            #[cfg(feature = "widgets-range")]
150            WidgetKind::ProgressBar,
151            #[cfg(feature = "widgets-data")]
152            WidgetKind::DataList,
153            #[cfg(feature = "widgets-data")]
154            WidgetKind::DataGrid,
155            #[cfg(feature = "widgets-canvas")]
156            WidgetKind::Canvas,
157            #[cfg(feature = "widgets-pickers")]
158            WidgetKind::ColorDialog,
159            #[cfg(feature = "widgets-pickers")]
160            WidgetKind::FontDialog,
161            WidgetKind::Toolbar,
162        ]
163    }
164
165    pub struct WidgetSpec {
166        pub id: WidgetId,
167        pub kind: WidgetKind,
168        pub focusable: Option<bool>,
169        pub enabled: bool,
170        pub visible: bool,
171    }
172
173    impl WidgetSpec {
174        pub fn new(id: WidgetId, kind: WidgetKind) -> Self {
175            Self {
176                id,
177                kind,
178                focusable: None,
179                enabled: true,
180                visible: true,
181            }
182        }
183    }
184}
185
186// ---------------------------------------------------------------------------
187// 1. Natural Focusability Vocabulary
188// ---------------------------------------------------------------------------
189
190/// Whether a widget kind is keyboard-focusable by default.
191///
192/// Layout, decoration, and static display kinds are not focusable;
193/// interactive controls are. The match is exhaustive on purpose: adding a
194/// `WidgetKind` fails to compile until its default has been chosen.
195pub fn default_focusable(kind: WidgetKind) -> bool {
196    match kind {
197        WidgetKind::Window | WidgetKind::Container | WidgetKind::Label | WidgetKind::Toolbar => {
198            false
199        }
200        #[cfg(feature = "widgets-containers")]
201        WidgetKind::Separator | WidgetKind::GroupBox | WidgetKind::SplitPane => false,
202        #[cfg(feature = "widgets-range")]
203        WidgetKind::ProgressBar => false,
204        #[cfg(feature = "widgets-canvas")]
205        WidgetKind::VulkanCanvas | WidgetKind::MetalCanvas => false,
206        #[cfg(feature = "widgets-media")]
207        WidgetKind::Image => false,
208        WidgetKind::Button => true,
209        #[cfg(feature = "widgets-text")]
210        WidgetKind::TextInput
211        | WidgetKind::TextArea
212        | WidgetKind::LinkLabel
213        | WidgetKind::RichText => true,
214        #[cfg(feature = "widgets-pickers")]
215        WidgetKind::DatePicker
216        | WidgetKind::FileChooserDialog
217        | WidgetKind::ColorDialog
218        | WidgetKind::FontDialog
219        | WidgetKind::Calendar => true,
220        #[cfg(feature = "widgets-containers")]
221        WidgetKind::Tabs | WidgetKind::AlertDialog => true,
222        #[cfg(feature = "widgets-data")]
223        WidgetKind::ListView
224        | WidgetKind::TreeView
225        | WidgetKind::DataList
226        | WidgetKind::DataGrid => true,
227        #[cfg(feature = "widgets-choice")]
228        WidgetKind::Checkbox
229        | WidgetKind::RadioButton
230        | WidgetKind::ComboBox
231        | WidgetKind::MultiSelect => true,
232        #[cfg(feature = "widgets-range")]
233        WidgetKind::Slider | WidgetKind::SpinBox => true,
234        #[cfg(feature = "widgets-canvas")]
235        WidgetKind::Canvas => true,
236    }
237}
238
239/// Resolves a widget's focusability: the explicit `WidgetSpec.focusable`
240/// override when present, otherwise the per-kind default.
241pub fn is_focusable(spec: &WidgetSpec) -> bool {
242    spec.focusable
243        .unwrap_or_else(|| default_focusable(spec.kind))
244}
245
246// ---------------------------------------------------------------------------
247// 2. Focus Direction & Geometry
248// ---------------------------------------------------------------------------
249
250/// Direction for keyboard, gamepad, and programmatic focus navigation.
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252pub enum FocusDirection {
253    /// Navigate upwards to the nearest spatial control in 2D layout.
254    Up,
255    /// Navigate downwards to the nearest spatial control in 2D layout.
256    Down,
257    /// Navigate leftwards to the nearest spatial control in 2D layout.
258    Left,
259    /// Navigate rightwards to the nearest spatial control in 2D layout.
260    Right,
261    /// Advance to the next eligible control in sequential tab / reading order.
262    TabNext,
263    /// Retreat to the preceding eligible control in sequential tab / reading order.
264    TabPrev,
265}
266
267impl FocusDirection {
268    /// Returns `true` if the direction is a 2D spatial movement (`Up`, `Down`, `Left`, `Right`).
269    pub const fn is_directional(&self) -> bool {
270        matches!(
271            self,
272            FocusDirection::Up
273                | FocusDirection::Down
274                | FocusDirection::Left
275                | FocusDirection::Right
276        )
277    }
278
279    /// Returns `true` if the direction is a 1D sequential movement (`TabNext`, `TabPrev`).
280    pub const fn is_tab(&self) -> bool {
281        matches!(self, FocusDirection::TabNext | FocusDirection::TabPrev)
282    }
283
284    /// Returns the opposite navigation direction.
285    pub const fn opposite(&self) -> Self {
286        match self {
287            FocusDirection::Up => FocusDirection::Down,
288            FocusDirection::Down => FocusDirection::Up,
289            FocusDirection::Left => FocusDirection::Right,
290            FocusDirection::Right => FocusDirection::Left,
291            FocusDirection::TabNext => FocusDirection::TabPrev,
292            FocusDirection::TabPrev => FocusDirection::TabNext,
293        }
294    }
295
296    /// Returns the unit vector `(dx, dy)` corresponding to directional navigation,
297    /// or `None` for sequential tab navigation.
298    pub const fn unit_vector(&self) -> Option<(i32, i32)> {
299        match self {
300            FocusDirection::Up => Some((0, -1)),
301            FocusDirection::Down => Some((0, 1)),
302            FocusDirection::Left => Some((-1, 0)),
303            FocusDirection::Right => Some((1, 0)),
304            FocusDirection::TabNext | FocusDirection::TabPrev => None,
305        }
306    }
307}
308
309/// A 2D bounding rectangle in logical coordinates used for spatial focus calculation.
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
311pub struct FocusRect {
312    /// Left coordinate in parent/window space.
313    pub x: i32,
314    /// Top coordinate in parent/window space.
315    pub y: i32,
316    /// Width in logical pixels.
317    pub width: i32,
318    /// Height in logical pixels.
319    pub height: i32,
320}
321
322impl FocusRect {
323    /// Creates a new rectangle from position and dimensions.
324    pub const fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
325        Self {
326            x,
327            y,
328            width,
329            height,
330        }
331    }
332
333    /// Converts a [`CanvasRect`] into a [`FocusRect`].
334    pub const fn from_canvas_rect(rect: CanvasRect) -> Self {
335        Self {
336            x: rect.x,
337            y: rect.y,
338            width: rect.width,
339            height: rect.height,
340        }
341    }
342
343    /// Converts this [`FocusRect`] into a [`CanvasRect`].
344    pub const fn to_canvas_rect(&self) -> CanvasRect {
345        CanvasRect {
346            x: self.x,
347            y: self.y,
348            width: self.width,
349            height: self.height,
350        }
351    }
352
353    /// Returns the left edge coordinate.
354    pub const fn left(&self) -> i32 {
355        self.x
356    }
357
358    /// Returns the top edge coordinate.
359    pub const fn top(&self) -> i32 {
360        self.y
361    }
362
363    /// Returns the right edge coordinate (`x + width`).
364    pub const fn right(&self) -> i32 {
365        self.x + self.width
366    }
367
368    /// Returns the bottom edge coordinate (`y + height`).
369    pub const fn bottom(&self) -> i32 {
370        self.y + self.height
371    }
372
373    /// Returns the horizontal center point.
374    pub fn center_x(&self) -> f64 {
375        self.x as f64 + (self.width as f64 / 2.0)
376    }
377
378    /// Returns the vertical center point.
379    pub fn center_y(&self) -> f64 {
380        self.y as f64 + (self.height as f64 / 2.0)
381    }
382
383    /// Returns the `(x, y)` center coordinates.
384    pub fn center(&self) -> (f64, f64) {
385        (self.center_x(), self.center_y())
386    }
387
388    /// Returns `true` if the rectangle has non-positive area.
389    pub const fn is_empty(&self) -> bool {
390        self.width <= 0 || self.height <= 0
391    }
392
393    /// Returns `true` if the rectangle contains the given point.
394    pub const fn contains_point(&self, px: i32, py: i32) -> bool {
395        px >= self.x && px < self.x + self.width && py >= self.y && py < self.y + self.height
396    }
397
398    /// Returns `true` if this rectangle intersects `other`.
399    pub const fn intersects(&self, other: &Self) -> bool {
400        self.x < other.x + other.width
401            && self.x + self.width > other.x
402            && self.y < other.y + other.height
403            && self.y + self.height > other.y
404    }
405
406    /// Returns the aspect ratio of the rectangle (`width / height`).
407    /// If height is 0 or negative, returns 1.0.
408    pub fn aspect_ratio(&self) -> f64 {
409        if self.height > 0 {
410            self.width as f64 / self.height as f64
411        } else {
412            1.0
413        }
414    }
415}
416
417/// A spatial node candidate for focus navigation.
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct FocusCandidate<T = WidgetId> {
420    /// Unique identifier of the candidate control.
421    pub id: T,
422    /// Spatial bounding box in logical coordinates.
423    pub rect: FocusRect,
424    /// Whether the candidate is currently eligible to receive focus.
425    pub focusable: bool,
426    /// Explicit tab index or order hint (lower values navigate first).
427    pub tab_index: Option<i32>,
428}
429
430impl<T> FocusCandidate<T> {
431    /// Creates a focusable candidate with natural tab order.
432    pub fn new(id: T, rect: FocusRect) -> Self {
433        Self {
434            id,
435            rect,
436            focusable: true,
437            tab_index: None,
438        }
439    }
440
441    /// Configures whether this candidate is eligible to receive focus.
442    pub fn with_focusable(mut self, focusable: bool) -> Self {
443        self.focusable = focusable;
444        self
445    }
446
447    /// Configures an explicit tab order index.
448    pub fn with_tab_index(mut self, tab_index: i32) -> Self {
449        self.tab_index = Some(tab_index);
450        self
451    }
452}
453
454// ---------------------------------------------------------------------------
455// 3. 2D Directional Projection Navigation Engine
456// ---------------------------------------------------------------------------
457
458/// Detailed projection metric breakdown for spatial navigation ranking.
459#[derive(Debug, Clone, Copy, PartialEq)]
460pub struct FocusProjectionScore {
461    /// Whether the candidate intersects the direct axial projection beam of the source rect.
462    pub in_beam: bool,
463    /// Distance along the primary axis of navigation.
464    pub primary_distance: f64,
465    /// Distance along the orthogonal axis (perpendicular to navigation direction).
466    pub orthogonal_distance: f64,
467    /// Projected overlap length along the orthogonal axis (0 if not in beam).
468    pub overlap: f64,
469    /// Overall weighted distance score (lower is better).
470    pub weighted_score: f64,
471}
472
473impl FocusProjectionScore {
474    /// Compares two projection scores: returns `true` if `self` is a better focus target than `other`.
475    pub fn is_better_than(&self, other: &Self) -> bool {
476        if self.in_beam != other.in_beam {
477            return self.in_beam;
478        }
479        self.weighted_score < other.weighted_score
480    }
481}
482
483/// Tuning parameters for spatial 2D projection scoring, including primary/orthogonal weights
484/// and aspect-ratio distance weighting.
485#[derive(Debug, Clone, Copy, PartialEq)]
486pub struct ProjectionOptions {
487    /// Primary axis distance multiplier (default: 13.0).
488    pub primary_weight: f64,
489    /// Orthogonal axis distance multiplier for in-beam candidates (default: 1.0).
490    pub orthogonal_weight_in_beam: f64,
491    /// Orthogonal axis distance multiplier for off-beam candidates (default: 5.0).
492    pub orthogonal_weight_off_beam: f64,
493    /// Overlap bonus multiplier along orthogonal axis (default: 0.1).
494    pub overlap_weight: f64,
495    /// Penalty added for off-beam candidates (default: 1000.0).
496    pub off_beam_penalty: f64,
497    /// Aspect-ratio distance weighting exponent (default: 0.0 = neutral/unweighted,
498    /// > 0 modulates orthogonal vs primary balance by aspect ratio).
499    pub aspect_ratio_weight: f64,
500}
501
502impl Default for ProjectionOptions {
503    fn default() -> Self {
504        Self {
505            primary_weight: 13.0,
506            orthogonal_weight_in_beam: 1.0,
507            orthogonal_weight_off_beam: 5.0,
508            overlap_weight: 0.1,
509            off_beam_penalty: 1000.0,
510            aspect_ratio_weight: 0.0,
511        }
512    }
513}
514
515impl ProjectionOptions {
516    /// Standard baseline projection options (aspect-ratio weighting disabled).
517    pub const fn standard() -> Self {
518        Self {
519            primary_weight: 13.0,
520            orthogonal_weight_in_beam: 1.0,
521            orthogonal_weight_off_beam: 5.0,
522            overlap_weight: 0.1,
523            off_beam_penalty: 1000.0,
524            aspect_ratio_weight: 0.0,
525        }
526    }
527
528    /// Creates options with aspect-ratio distance weighting enabled.
529    pub const fn with_aspect_ratio_weighting(weight: f64) -> Self {
530        Self {
531            primary_weight: 13.0,
532            orthogonal_weight_in_beam: 1.0,
533            orthogonal_weight_off_beam: 5.0,
534            overlap_weight: 0.1,
535            off_beam_penalty: 1000.0,
536            aspect_ratio_weight: weight,
537        }
538    }
539
540    /// Sets the aspect-ratio weighting exponent.
541    pub fn with_aspect_ratio_weight(mut self, weight: f64) -> Self {
542        self.aspect_ratio_weight = weight;
543        self
544    }
545}
546
547/// Computes the directional projection score from `source` to `target` in `direction`
548/// with custom projection and aspect-ratio weighting options.
549///
550/// Returns `None` if `target` does not lie in the forward navigation half-plane or is degenerate.
551pub fn compute_projection_score_options(
552    source: &FocusRect,
553    target: &FocusRect,
554    direction: FocusDirection,
555    options: &ProjectionOptions,
556) -> Option<FocusProjectionScore> {
557    if source.is_empty() || target.is_empty() {
558        return None;
559    }
560
561    match direction {
562        FocusDirection::Right => {
563            // Must lie strictly to the right: center must advance, and left edge must not be behind source left
564            if target.center_x() <= source.center_x() || target.left() < source.left() {
565                return None;
566            }
567
568            let primary_distance = if target.left() >= source.right() {
569                (target.left() - source.right()) as f64
570            } else {
571                target.center_x() - source.center_x()
572            };
573
574            let overlap_start = source.top().max(target.top());
575            let overlap_end = source.bottom().min(target.bottom());
576            let in_beam = overlap_end > overlap_start;
577            let overlap = if in_beam {
578                (overlap_end - overlap_start) as f64
579            } else {
580                0.0
581            };
582
583            let orthogonal_distance = if in_beam {
584                (source.center_y() - target.center_y()).abs() * 0.5
585            } else {
586                let gap = if target.top() >= source.bottom() {
587                    (target.top() - source.bottom()) as f64
588                } else {
589                    (source.top() - target.bottom()) as f64
590                };
591                gap + (source.center_y() - target.center_y()).abs() * 0.5
592            };
593
594            let ar = target.aspect_ratio();
595            let ar_mod = if options.aspect_ratio_weight > 0.0 && ar > 0.0 {
596                ar.powf(options.aspect_ratio_weight)
597            } else {
598                1.0
599            };
600            let effective_orthogonal = orthogonal_distance / ar_mod;
601
602            let weighted_score = if in_beam {
603                options.primary_weight * primary_distance
604                    + options.orthogonal_weight_in_beam * effective_orthogonal
605                    - (overlap * options.overlap_weight)
606            } else {
607                options.primary_weight * primary_distance
608                    + options.orthogonal_weight_off_beam * effective_orthogonal
609                    + options.off_beam_penalty
610            };
611
612            Some(FocusProjectionScore {
613                in_beam,
614                primary_distance,
615                orthogonal_distance,
616                overlap,
617                weighted_score,
618            })
619        }
620        FocusDirection::Left => {
621            if target.center_x() >= source.center_x() || target.right() > source.right() {
622                return None;
623            }
624
625            let primary_distance = if target.right() <= source.left() {
626                (source.left() - target.right()) as f64
627            } else {
628                source.center_x() - target.center_x()
629            };
630
631            let overlap_start = source.top().max(target.top());
632            let overlap_end = source.bottom().min(target.bottom());
633            let in_beam = overlap_end > overlap_start;
634            let overlap = if in_beam {
635                (overlap_end - overlap_start) as f64
636            } else {
637                0.0
638            };
639
640            let orthogonal_distance = if in_beam {
641                (source.center_y() - target.center_y()).abs() * 0.5
642            } else {
643                let gap = if target.top() >= source.bottom() {
644                    (target.top() - source.bottom()) as f64
645                } else {
646                    (source.top() - target.bottom()) as f64
647                };
648                gap + (source.center_y() - target.center_y()).abs() * 0.5
649            };
650
651            let ar = target.aspect_ratio();
652            let ar_mod = if options.aspect_ratio_weight > 0.0 && ar > 0.0 {
653                ar.powf(options.aspect_ratio_weight)
654            } else {
655                1.0
656            };
657            let effective_orthogonal = orthogonal_distance / ar_mod;
658
659            let weighted_score = if in_beam {
660                options.primary_weight * primary_distance
661                    + options.orthogonal_weight_in_beam * effective_orthogonal
662                    - (overlap * options.overlap_weight)
663            } else {
664                options.primary_weight * primary_distance
665                    + options.orthogonal_weight_off_beam * effective_orthogonal
666                    + options.off_beam_penalty
667            };
668
669            Some(FocusProjectionScore {
670                in_beam,
671                primary_distance,
672                orthogonal_distance,
673                overlap,
674                weighted_score,
675            })
676        }
677        FocusDirection::Down => {
678            if target.center_y() <= source.center_y() || target.top() < source.top() {
679                return None;
680            }
681
682            let primary_distance = if target.top() >= source.bottom() {
683                (target.top() - source.bottom()) as f64
684            } else {
685                target.center_y() - source.center_y()
686            };
687
688            let overlap_start = source.left().max(target.left());
689            let overlap_end = source.right().min(target.right());
690            let in_beam = overlap_end > overlap_start;
691            let overlap = if in_beam {
692                (overlap_end - overlap_start) as f64
693            } else {
694                0.0
695            };
696
697            let orthogonal_distance = if in_beam {
698                (source.center_x() - target.center_x()).abs() * 0.5
699            } else {
700                let gap = if target.left() >= source.right() {
701                    (target.left() - source.right()) as f64
702                } else {
703                    (source.left() - target.right()) as f64
704                };
705                gap + (source.center_x() - target.center_x()).abs() * 0.5
706            };
707
708            let ar = target.aspect_ratio();
709            let ar_vert = if ar > 0.0 { 1.0 / ar } else { 1.0 };
710            let ar_mod = if options.aspect_ratio_weight > 0.0 && ar_vert > 0.0 {
711                ar_vert.powf(options.aspect_ratio_weight)
712            } else {
713                1.0
714            };
715            let effective_orthogonal = orthogonal_distance / ar_mod;
716
717            let weighted_score = if in_beam {
718                options.primary_weight * primary_distance
719                    + options.orthogonal_weight_in_beam * effective_orthogonal
720                    - (overlap * options.overlap_weight)
721            } else {
722                options.primary_weight * primary_distance
723                    + options.orthogonal_weight_off_beam * effective_orthogonal
724                    + options.off_beam_penalty
725            };
726
727            Some(FocusProjectionScore {
728                in_beam,
729                primary_distance,
730                orthogonal_distance,
731                overlap,
732                weighted_score,
733            })
734        }
735        FocusDirection::Up => {
736            if target.center_y() >= source.center_y() || target.bottom() > source.bottom() {
737                return None;
738            }
739
740            let primary_distance = if target.bottom() <= source.top() {
741                (source.top() - target.bottom()) as f64
742            } else {
743                source.center_y() - target.center_y()
744            };
745
746            let overlap_start = source.left().max(target.left());
747            let overlap_end = source.right().min(target.right());
748            let in_beam = overlap_end > overlap_start;
749            let overlap = if in_beam {
750                (overlap_end - overlap_start) as f64
751            } else {
752                0.0
753            };
754
755            let orthogonal_distance = if in_beam {
756                (source.center_x() - target.center_x()).abs() * 0.5
757            } else {
758                let gap = if target.left() >= source.right() {
759                    (target.left() - source.right()) as f64
760                } else {
761                    (source.left() - target.right()) as f64
762                };
763                gap + (source.center_x() - target.center_x()).abs() * 0.5
764            };
765
766            let ar = target.aspect_ratio();
767            let ar_vert = if ar > 0.0 { 1.0 / ar } else { 1.0 };
768            let ar_mod = if options.aspect_ratio_weight > 0.0 && ar_vert > 0.0 {
769                ar_vert.powf(options.aspect_ratio_weight)
770            } else {
771                1.0
772            };
773            let effective_orthogonal = orthogonal_distance / ar_mod;
774
775            let weighted_score = if in_beam {
776                options.primary_weight * primary_distance
777                    + options.orthogonal_weight_in_beam * effective_orthogonal
778                    - (overlap * options.overlap_weight)
779            } else {
780                options.primary_weight * primary_distance
781                    + options.orthogonal_weight_off_beam * effective_orthogonal
782                    + options.off_beam_penalty
783            };
784
785            Some(FocusProjectionScore {
786                in_beam,
787                primary_distance,
788                orthogonal_distance,
789                overlap,
790                weighted_score,
791            })
792        }
793        FocusDirection::TabNext | FocusDirection::TabPrev => None,
794    }
795}
796
797/// Computes the directional projection score from `source` to `target` in `direction`
798/// using default standard projection weights.
799///
800/// Returns `None` if `target` does not lie in the forward navigation half-plane or is degenerate.
801pub fn compute_projection_score(
802    source: &FocusRect,
803    target: &FocusRect,
804    direction: FocusDirection,
805) -> Option<FocusProjectionScore> {
806    compute_projection_score_options(source, target, direction, &ProjectionOptions::default())
807}
808
809/// Finds the next focus target in 2D spatial layout using directional beam projection
810/// and standard default projection options.
811///
812/// If no candidate lies directly in the specified direction and `wrap_around` is `true`,
813/// wraps to the opposite boundary of the layout.
814pub fn find_next_focus_2d<'a, T: Clone>(
815    current_rect: &FocusRect,
816    candidates: &'a [FocusCandidate<T>],
817    direction: FocusDirection,
818    wrap_around: bool,
819) -> Option<&'a FocusCandidate<T>> {
820    find_next_focus_2d_options(
821        current_rect,
822        candidates,
823        direction,
824        wrap_around,
825        &ProjectionOptions::default(),
826    )
827}
828
829/// Finds the next focus target in 2D spatial layout using directional beam projection
830/// with custom projection and aspect-ratio weighting options.
831pub fn find_next_focus_2d_options<'a, T: Clone>(
832    current_rect: &FocusRect,
833    candidates: &'a [FocusCandidate<T>],
834    direction: FocusDirection,
835    wrap_around: bool,
836    options: &ProjectionOptions,
837) -> Option<&'a FocusCandidate<T>> {
838    if !direction.is_directional() || candidates.is_empty() {
839        return None;
840    }
841
842    let mut best_candidate: Option<(&'a FocusCandidate<T>, FocusProjectionScore)> = None;
843
844    for candidate in candidates {
845        if !candidate.focusable || candidate.rect.is_empty() || &candidate.rect == current_rect {
846            continue;
847        }
848
849        if let Some(score) =
850            compute_projection_score_options(current_rect, &candidate.rect, direction, options)
851        {
852            match &best_candidate {
853                None => best_candidate = Some((candidate, score)),
854                Some((_, best_score)) => {
855                    if score.is_better_than(best_score) {
856                        best_candidate = Some((candidate, score));
857                    }
858                }
859            }
860        }
861    }
862
863    if let Some((best, _)) = best_candidate {
864        return Some(best);
865    }
866
867    // Wrap-around logic when no forward candidate was found
868    if wrap_around {
869        let eligible: Vec<&'a FocusCandidate<T>> = candidates
870            .iter()
871            .filter(|c| c.focusable && !c.rect.is_empty() && &c.rect != current_rect)
872            .collect();
873
874        if eligible.is_empty() {
875            return None;
876        }
877
878        return match direction {
879            FocusDirection::Right => {
880                // Wrap to the leftmost eligible candidate (lowest x)
881                eligible.into_iter().min_by_key(|c| c.rect.left())
882            }
883            FocusDirection::Left => {
884                // Wrap to the rightmost eligible candidate (highest right)
885                eligible.into_iter().max_by_key(|c| c.rect.right())
886            }
887            FocusDirection::Down => {
888                // Wrap to the topmost eligible candidate (lowest y)
889                eligible.into_iter().min_by_key(|c| c.rect.top())
890            }
891            FocusDirection::Up => {
892                // Wrap to the bottommost eligible candidate (highest bottom)
893                eligible.into_iter().max_by_key(|c| c.rect.bottom())
894            }
895            FocusDirection::TabNext | FocusDirection::TabPrev => None,
896        };
897    }
898
899    None
900}
901
902/// Finds the next focus target in sequential tab / reading order.
903///
904/// Order precedence:
905/// 1. Explicit `tab_index` ascending (e.g. `Some(1)`, `Some(2)`), followed by un-indexed controls.
906/// 2. Geometric reading order: top-to-bottom, left-to-right.
907pub fn find_next_focus_tab<'a, T: Clone + PartialEq>(
908    current_id: Option<&T>,
909    candidates: &'a [FocusCandidate<T>],
910    direction: FocusDirection,
911    wrap_around: bool,
912) -> Option<&'a FocusCandidate<T>> {
913    if !direction.is_tab() || candidates.is_empty() {
914        return None;
915    }
916
917    let mut eligible: Vec<&'a FocusCandidate<T>> =
918        candidates.iter().filter(|c| c.focusable).collect();
919
920    if eligible.is_empty() {
921        return None;
922    }
923
924    // Stable sort by explicit tab_index, then by geometric reading order (y row bucket, then x)
925    eligible.sort_by(|a, b| {
926        match (a.tab_index, b.tab_index) {
927            (Some(idx_a), Some(idx_b)) => idx_a.cmp(&idx_b),
928            (Some(_), None) => std::cmp::Ordering::Less,
929            (None, Some(_)) => std::cmp::Ordering::Greater,
930            (None, None) => {
931                // Reading order: group into 8px vertical bands to handle slight misalignments
932                let row_a = a.rect.top() / 8;
933                let row_b = b.rect.top() / 8;
934                if row_a != row_b {
935                    row_a.cmp(&row_b)
936                } else {
937                    a.rect.left().cmp(&b.rect.left())
938                }
939            }
940        }
941    });
942
943    let current_index = current_id.and_then(|id| eligible.iter().position(|c| &c.id == id));
944
945    match direction {
946        FocusDirection::TabNext => match current_index {
947            Some(idx) => {
948                if idx + 1 < eligible.len() {
949                    Some(eligible[idx + 1])
950                } else if wrap_around {
951                    Some(eligible[0])
952                } else {
953                    None
954                }
955            }
956            None => eligible.first().copied(),
957        },
958        FocusDirection::TabPrev => match current_index {
959            Some(idx) => {
960                if idx > 0 {
961                    Some(eligible[idx - 1])
962                } else if wrap_around {
963                    eligible.last().copied()
964                } else {
965                    None
966                }
967            }
968            None => eligible.last().copied(),
969        },
970        _ => None,
971    }
972}
973
974/// Unified focus navigation dispatch across 2D directional and 1D sequential modes.
975pub fn find_next_focus<'a, T: Clone + PartialEq>(
976    current_id: Option<&T>,
977    current_rect: Option<&FocusRect>,
978    candidates: &'a [FocusCandidate<T>],
979    direction: FocusDirection,
980    wrap_around: bool,
981) -> Option<&'a FocusCandidate<T>> {
982    if direction.is_tab() {
983        find_next_focus_tab(current_id, candidates, direction, wrap_around)
984    } else if direction.is_directional() {
985        if let Some(rect) = current_rect {
986            find_next_focus_2d(rect, candidates, direction, wrap_around)
987        } else if let Some(id) = current_id {
988            if let Some(candidate) = candidates.iter().find(|c| &c.id == id) {
989                find_next_focus_2d(&candidate.rect, candidates, direction, wrap_around)
990            } else {
991                candidates.iter().find(|c| c.focusable)
992            }
993        } else {
994            candidates.iter().find(|c| c.focusable)
995        }
996    } else {
997        None
998    }
999}
1000
1001// ---------------------------------------------------------------------------
1002// 4. Multi-Column Container Navigation & Acceleration
1003// ---------------------------------------------------------------------------
1004
1005/// Boundary wrap-around mode for multi-column grid navigation.
1006#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1007pub enum GridWrapMode {
1008    /// No wrapping: navigation stops at grid boundaries.
1009    #[default]
1010    None,
1011    /// Toroidal / axis wrap: navigation wraps around within the same row or column.
1012    /// Moving Right wraps to the start of the same row; moving Down wraps to the top of the same column.
1013    Axis,
1014    /// Linear / continuous reading-order wrap:
1015    /// Moving Right past the end of a row advances to the start of the next row.
1016    /// Moving Left past the start of a row retreats to the end of the previous row.
1017    /// Moving past the last/first row wraps to the other end of the grid.
1018    Flow,
1019}
1020
1021/// Acceleration tracker for repeated directional navigation in multi-column grids and containers.
1022#[derive(Debug, Clone, Copy, PartialEq)]
1023pub struct GridAccelerator {
1024    /// Number of consecutive directional steps required before acceleration activates.
1025    pub threshold: usize,
1026    /// Multiplier added to step distance per step above threshold.
1027    pub step_multiplier: usize,
1028    /// Maximum step jump allowed.
1029    pub max_step: usize,
1030    /// Current consecutive steps taken in `last_direction`.
1031    pub consecutive_count: usize,
1032    /// Direction of the previous navigation step.
1033    pub last_direction: Option<FocusDirection>,
1034}
1035
1036impl Default for GridAccelerator {
1037    fn default() -> Self {
1038        Self {
1039            threshold: 2,
1040            step_multiplier: 1,
1041            max_step: 4,
1042            consecutive_count: 0,
1043            last_direction: None,
1044        }
1045    }
1046}
1047
1048impl GridAccelerator {
1049    /// Creates an accelerator with specific threshold, multiplier, and max step limits.
1050    pub const fn new(threshold: usize, step_multiplier: usize, max_step: usize) -> Self {
1051        Self {
1052            threshold,
1053            step_multiplier,
1054            max_step,
1055            consecutive_count: 0,
1056            last_direction: None,
1057        }
1058    }
1059
1060    /// Resets the acceleration state.
1061    pub fn reset(&mut self) {
1062        self.consecutive_count = 0;
1063        self.last_direction = None;
1064    }
1065
1066    /// Records a navigation step in `direction` and returns the accelerated step distance
1067    /// (number of grid units to advance).
1068    pub fn record_step(&mut self, direction: FocusDirection) -> usize {
1069        if self.last_direction == Some(direction) {
1070            self.consecutive_count = self.consecutive_count.saturating_add(1);
1071        } else {
1072            self.last_direction = Some(direction);
1073            self.consecutive_count = 1;
1074        }
1075
1076        self.current_step()
1077    }
1078
1079    /// Returns the current step distance based on `consecutive_count`.
1080    pub fn current_step(&self) -> usize {
1081        if self.consecutive_count <= self.threshold {
1082            1
1083        } else {
1084            let extra = self.consecutive_count - self.threshold;
1085            let step = 1 + extra * self.step_multiplier;
1086            step.min(self.max_step).max(1)
1087        }
1088    }
1089}
1090
1091/// A structured 2D multi-column container for deterministic grid navigation,
1092/// boundary wrapping, and accelerated directional stepping.
1093#[derive(Debug, Clone, PartialEq)]
1094pub struct FocusGrid<T = WidgetId> {
1095    /// Number of columns in the grid.
1096    pub columns: usize,
1097    /// Number of rows in the grid.
1098    pub rows: usize,
1099    /// Cells arranged in row-major order (`index = row * columns + col`).
1100    pub cells: Vec<Option<FocusCandidate<T>>>,
1101    /// Boundary wrapping policy when reaching edges.
1102    pub wrap_mode: GridWrapMode,
1103    /// Optional navigation accelerator.
1104    pub accelerator: Option<GridAccelerator>,
1105}
1106
1107impl<T: Clone + PartialEq> FocusGrid<T> {
1108    /// Creates a new empty focus grid with the specified dimensions.
1109    pub fn new(columns: usize, rows: usize) -> Self {
1110        let total = columns * rows;
1111        Self {
1112            columns,
1113            rows,
1114            cells: vec![None; total],
1115            wrap_mode: GridWrapMode::None,
1116            accelerator: None,
1117        }
1118    }
1119
1120    /// Populates a grid from a list of candidates in row-major order.
1121    pub fn from_candidates(columns: usize, candidates: Vec<FocusCandidate<T>>) -> Self {
1122        let columns = columns.max(1);
1123        let rows = if candidates.is_empty() {
1124            0
1125        } else {
1126            candidates.len().div_ceil(columns)
1127        };
1128        let mut cells = vec![None; columns * rows];
1129        for (i, c) in candidates.into_iter().enumerate() {
1130            cells[i] = Some(c);
1131        }
1132        Self {
1133            columns,
1134            rows,
1135            cells,
1136            wrap_mode: GridWrapMode::None,
1137            accelerator: None,
1138        }
1139    }
1140
1141    /// Configures the grid boundary wrap mode.
1142    pub fn with_wrap_mode(mut self, wrap_mode: GridWrapMode) -> Self {
1143        self.wrap_mode = wrap_mode;
1144        self
1145    }
1146
1147    /// Enables navigation acceleration with the provided accelerator.
1148    pub fn with_accelerator(mut self, accelerator: GridAccelerator) -> Self {
1149        self.accelerator = Some(accelerator);
1150        self
1151    }
1152
1153    /// Resets the internal accelerator if present.
1154    pub fn reset_accelerator(&mut self) {
1155        if let Some(ref mut accel) = self.accelerator {
1156            accel.reset();
1157        }
1158    }
1159
1160    /// Sets the candidate at cell coordinate `(col, row)`.
1161    pub fn set_cell(&mut self, col: usize, row: usize, candidate: Option<FocusCandidate<T>>) {
1162        if col < self.columns && row < self.rows {
1163            self.cells[row * self.columns + col] = candidate;
1164        }
1165    }
1166
1167    /// Retrieves the candidate at cell coordinate `(col, row)`.
1168    pub fn get_cell(&self, col: usize, row: usize) -> Option<&FocusCandidate<T>> {
1169        if col < self.columns && row < self.rows {
1170            self.cells[row * self.columns + col].as_ref()
1171        } else {
1172            None
1173        }
1174    }
1175
1176    /// Returns `true` if the cell at `(col, row)` exists and is focusable.
1177    pub fn is_cell_focusable(&self, col: usize, row: usize) -> bool {
1178        self.get_cell(col, row).is_some_and(|c| c.focusable)
1179    }
1180
1181    /// Finds the `(col, row)` coordinates of a candidate by its ID.
1182    pub fn find_position(&self, id: &T) -> Option<(usize, usize)> {
1183        for row in 0..self.rows {
1184            for col in 0..self.columns {
1185                if let Some(candidate) = &self.cells[row * self.columns + col] {
1186                    if &candidate.id == id {
1187                        return Some((col, row));
1188                    }
1189                }
1190            }
1191        }
1192        None
1193    }
1194
1195    /// Navigates from `current_id` in `direction` using a specified step distance and grid wrap mode.
1196    ///
1197    /// Skips empty or non-focusable cells along the path to find the next valid focusable candidate.
1198    pub fn navigate_step(
1199        &self,
1200        current_id: &T,
1201        direction: FocusDirection,
1202        step: usize,
1203    ) -> Option<&FocusCandidate<T>> {
1204        let (start_col, start_row) = self.find_position(current_id)?;
1205        self.navigate_from_coords(start_col, start_row, direction, step)
1206    }
1207
1208    /// Navigates from `current_id` in `direction` applying the internal accelerator if configured.
1209    pub fn navigate_accelerated(
1210        &mut self,
1211        current_id: &T,
1212        direction: FocusDirection,
1213    ) -> Option<&FocusCandidate<T>> {
1214        let step = if let Some(ref mut accel) = self.accelerator {
1215            accel.record_step(direction)
1216        } else {
1217            1
1218        };
1219
1220        self.navigate_step(current_id, direction, step)
1221    }
1222
1223    /// Navigates from `(start_col, start_row)` in `direction` by `step` units.
1224    pub fn navigate_from_coords(
1225        &self,
1226        start_col: usize,
1227        start_row: usize,
1228        direction: FocusDirection,
1229        step: usize,
1230    ) -> Option<&FocusCandidate<T>> {
1231        if self.columns == 0 || self.rows == 0 || step == 0 {
1232            return None;
1233        }
1234
1235        match direction {
1236            FocusDirection::Right => match self.wrap_mode {
1237                GridWrapMode::None => {
1238                    let target_col = (start_col + step).min(self.columns - 1);
1239                    if target_col == start_col {
1240                        return None;
1241                    }
1242                    if self.is_cell_focusable(target_col, start_row) {
1243                        return self.get_cell(target_col, start_row);
1244                    }
1245                    for c in (start_col + 1..=target_col).rev() {
1246                        if self.is_cell_focusable(c, start_row) {
1247                            return self.get_cell(c, start_row);
1248                        }
1249                    }
1250                    for c in (target_col + 1)..self.columns {
1251                        if self.is_cell_focusable(c, start_row) {
1252                            return self.get_cell(c, start_row);
1253                        }
1254                    }
1255                    None
1256                }
1257                GridWrapMode::Axis => {
1258                    let target_col = (start_col + step) % self.columns;
1259                    if target_col != start_col && self.is_cell_focusable(target_col, start_row) {
1260                        return self.get_cell(target_col, start_row);
1261                    }
1262                    for offset in 1..self.columns {
1263                        let c = (start_col + step + offset) % self.columns;
1264                        if c != start_col && self.is_cell_focusable(c, start_row) {
1265                            return self.get_cell(c, start_row);
1266                        }
1267                    }
1268                    None
1269                }
1270                GridWrapMode::Flow => {
1271                    let total = self.columns * self.rows;
1272                    let start_idx = start_row * self.columns + start_col;
1273                    let target_idx = (start_idx + step) % total;
1274                    let tr = target_idx / self.columns;
1275                    let tc = target_idx % self.columns;
1276                    if target_idx != start_idx && self.is_cell_focusable(tc, tr) {
1277                        return self.get_cell(tc, tr);
1278                    }
1279                    for offset in 1..total {
1280                        let idx = (start_idx + step + offset) % total;
1281                        if idx == start_idx {
1282                            continue;
1283                        }
1284                        let r = idx / self.columns;
1285                        let c = idx % self.columns;
1286                        if self.is_cell_focusable(c, r) {
1287                            return self.get_cell(c, r);
1288                        }
1289                    }
1290                    None
1291                }
1292            },
1293            FocusDirection::Left => match self.wrap_mode {
1294                GridWrapMode::None => {
1295                    if start_col == 0 {
1296                        return None;
1297                    }
1298                    let target_col = start_col.saturating_sub(step);
1299                    if self.is_cell_focusable(target_col, start_row) {
1300                        return self.get_cell(target_col, start_row);
1301                    }
1302                    for c in (target_col..start_col).rev() {
1303                        if self.is_cell_focusable(c, start_row) {
1304                            return self.get_cell(c, start_row);
1305                        }
1306                    }
1307                    None
1308                }
1309                GridWrapMode::Axis => {
1310                    let step_rem = step % self.columns;
1311                    let target_col = (start_col + self.columns - step_rem) % self.columns;
1312                    if target_col != start_col && self.is_cell_focusable(target_col, start_row) {
1313                        return self.get_cell(target_col, start_row);
1314                    }
1315                    for offset in 1..self.columns {
1316                        let c =
1317                            (target_col + self.columns - (offset % self.columns)) % self.columns;
1318                        if c != start_col && self.is_cell_focusable(c, start_row) {
1319                            return self.get_cell(c, start_row);
1320                        }
1321                    }
1322                    None
1323                }
1324                GridWrapMode::Flow => {
1325                    let total = self.columns * self.rows;
1326                    let start_idx = start_row * self.columns + start_col;
1327                    let step_rem = step % total;
1328                    let target_idx = (start_idx + total - step_rem) % total;
1329                    let tr = target_idx / self.columns;
1330                    let tc = target_idx % self.columns;
1331                    if target_idx != start_idx && self.is_cell_focusable(tc, tr) {
1332                        return self.get_cell(tc, tr);
1333                    }
1334                    for offset in 1..total {
1335                        let idx = (target_idx + total - (offset % total)) % total;
1336                        if idx == start_idx {
1337                            continue;
1338                        }
1339                        let r = idx / self.columns;
1340                        let c = idx % self.columns;
1341                        if self.is_cell_focusable(c, r) {
1342                            return self.get_cell(c, r);
1343                        }
1344                    }
1345                    None
1346                }
1347            },
1348            FocusDirection::Down => match self.wrap_mode {
1349                GridWrapMode::None => {
1350                    let target_row = (start_row + step).min(self.rows - 1);
1351                    if target_row == start_row {
1352                        return None;
1353                    }
1354                    if self.is_cell_focusable(start_col, target_row) {
1355                        return self.get_cell(start_col, target_row);
1356                    }
1357                    for r in (start_row + 1..=target_row).rev() {
1358                        if self.is_cell_focusable(start_col, r) {
1359                            return self.get_cell(start_col, r);
1360                        }
1361                    }
1362                    for r in (target_row + 1)..self.rows {
1363                        if self.is_cell_focusable(start_col, r) {
1364                            return self.get_cell(start_col, r);
1365                        }
1366                    }
1367                    None
1368                }
1369                GridWrapMode::Axis | GridWrapMode::Flow => {
1370                    let target_row = (start_row + step) % self.rows;
1371                    if target_row != start_row && self.is_cell_focusable(start_col, target_row) {
1372                        return self.get_cell(start_col, target_row);
1373                    }
1374                    for offset in 1..self.rows {
1375                        let r = (start_row + step + offset) % self.rows;
1376                        if r != start_row && self.is_cell_focusable(start_col, r) {
1377                            return self.get_cell(start_col, r);
1378                        }
1379                    }
1380                    None
1381                }
1382            },
1383            FocusDirection::Up => match self.wrap_mode {
1384                GridWrapMode::None => {
1385                    if start_row == 0 {
1386                        return None;
1387                    }
1388                    let target_row = start_row.saturating_sub(step);
1389                    if self.is_cell_focusable(start_col, target_row) {
1390                        return self.get_cell(start_col, target_row);
1391                    }
1392                    for r in (target_row..start_row).rev() {
1393                        if self.is_cell_focusable(start_col, r) {
1394                            return self.get_cell(start_col, r);
1395                        }
1396                    }
1397                    None
1398                }
1399                GridWrapMode::Axis | GridWrapMode::Flow => {
1400                    let step_rem = step % self.rows;
1401                    let target_row = (start_row + self.rows - step_rem) % self.rows;
1402                    if target_row != start_row && self.is_cell_focusable(start_col, target_row) {
1403                        return self.get_cell(start_col, target_row);
1404                    }
1405                    for offset in 1..self.rows {
1406                        let r = (target_row + self.rows - (offset % self.rows)) % self.rows;
1407                        if r != start_row && self.is_cell_focusable(start_col, r) {
1408                            return self.get_cell(start_col, r);
1409                        }
1410                    }
1411                    None
1412                }
1413            },
1414            FocusDirection::TabNext => {
1415                let total = self.columns * self.rows;
1416                let start_idx = start_row * self.columns + start_col;
1417                for offset in 1..total {
1418                    let idx = start_idx + offset;
1419                    if idx >= total && self.wrap_mode == GridWrapMode::None {
1420                        return None;
1421                    }
1422                    let wrapped_idx = idx % total;
1423                    let r = wrapped_idx / self.columns;
1424                    let c = wrapped_idx % self.columns;
1425                    if self.is_cell_focusable(c, r) {
1426                        return self.get_cell(c, r);
1427                    }
1428                }
1429                None
1430            }
1431            FocusDirection::TabPrev => {
1432                let total = self.columns * self.rows;
1433                let start_idx = start_row * self.columns + start_col;
1434                for offset in 1..total {
1435                    if start_idx < offset && self.wrap_mode == GridWrapMode::None {
1436                        return None;
1437                    }
1438                    let wrapped_idx = (start_idx + total - (offset % total)) % total;
1439                    let r = wrapped_idx / self.columns;
1440                    let c = wrapped_idx % self.columns;
1441                    if self.is_cell_focusable(c, r) {
1442                        return self.get_cell(c, r);
1443                    }
1444                }
1445                None
1446            }
1447        }
1448    }
1449}
1450
1451// ---------------------------------------------------------------------------
1452// 5. Directional Focus Trap Primitives
1453// ---------------------------------------------------------------------------
1454
1455/// Policy governing boundary containment behavior when focus navigation
1456/// reaches the boundary edge of a focus trap.
1457#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1458pub enum FocusTrapBoundaryPolicy {
1459    /// Focus wraps around to the opposite edge within the trap.
1460    #[default]
1461    Wrap,
1462    /// Focus clamps at the boundary element within the trap (no change in focused target).
1463    Clamp,
1464    /// Navigation stops; returns None, leaving focus on the current element without wrapping.
1465    Stop,
1466}
1467
1468/// The result outcome of navigating within a directional focus trap.
1469#[derive(Debug, Clone, PartialEq, Eq)]
1470pub enum FocusTrapOutcome<'a, T> {
1471    /// Focus moved forward to a new candidate within the trap.
1472    Moved(&'a FocusCandidate<T>),
1473    /// Focus reached the trap boundary and wrapped to the opposite side within the trap.
1474    Wrapped(&'a FocusCandidate<T>),
1475    /// Focus reached the trap boundary and was clamped to the boundary candidate.
1476    Clamped(&'a FocusCandidate<T>),
1477    /// Focus reached the trap boundary and was stopped (no eligible target).
1478    Stopped,
1479    /// Navigation exited the trap via an explicitly allowed exit direction.
1480    Exited(&'a FocusCandidate<T>),
1481}
1482
1483impl<'a, T> FocusTrapOutcome<'a, T> {
1484    /// Returns the target candidate if navigation produced one (whether moved, wrapped, clamped, or exited).
1485    pub fn candidate(&self) -> Option<&'a FocusCandidate<T>> {
1486        match self {
1487            Self::Moved(c) | Self::Wrapped(c) | Self::Clamped(c) | Self::Exited(c) => Some(c),
1488            Self::Stopped => None,
1489        }
1490    }
1491}
1492
1493/// Directional focus trap primitive that confines keyboard and spatial focus navigation
1494/// to an enclosed container, dialog, or subset of widgets.
1495#[derive(Debug, Clone, PartialEq)]
1496pub struct FocusTrap<T = WidgetId> {
1497    /// Optional container identifier associated with this trap.
1498    pub container_id: Option<T>,
1499    /// Optional spatial bounding rectangle of the trap in logical coordinates.
1500    pub bounds: Option<FocusRect>,
1501    /// List of widget IDs belonging to the trapped scope.
1502    pub members: Vec<T>,
1503    /// Boundary policy applied when navigating at the trap's edge.
1504    pub boundary_policy: FocusTrapBoundaryPolicy,
1505    /// Directions that are permitted to escape the trap (e.g. Tab out or Down out).
1506    pub exit_directions: Vec<FocusDirection>,
1507    /// Whether the trap is currently active.
1508    pub active: bool,
1509}
1510
1511impl<T: Clone + PartialEq> FocusTrap<T> {
1512    /// Creates an active focus trap with the specified member IDs and default Wrap policy.
1513    pub fn new(members: Vec<T>) -> Self {
1514        Self {
1515            container_id: None,
1516            bounds: None,
1517            members,
1518            boundary_policy: FocusTrapBoundaryPolicy::Wrap,
1519            exit_directions: Vec::new(),
1520            active: true,
1521        }
1522    }
1523
1524    /// Associates a container ID with this trap.
1525    pub fn with_container_id(mut self, container_id: T) -> Self {
1526        self.container_id = Some(container_id);
1527        self
1528    }
1529
1530    /// Sets the spatial bounding box enclosing the trap.
1531    pub fn with_bounds(mut self, bounds: FocusRect) -> Self {
1532        self.bounds = Some(bounds);
1533        self
1534    }
1535
1536    /// Configures the boundary policy (Wrap, Clamp, Stop).
1537    pub fn with_boundary_policy(mut self, policy: FocusTrapBoundaryPolicy) -> Self {
1538        self.boundary_policy = policy;
1539        self
1540    }
1541
1542    /// Adds an allowed exit direction to allow directional escape.
1543    pub fn with_exit_direction(mut self, direction: FocusDirection) -> Self {
1544        if !self.exit_directions.contains(&direction) {
1545            self.exit_directions.push(direction);
1546        }
1547        self
1548    }
1549
1550    /// Sets whether the trap is active.
1551    pub fn with_active(mut self, active: bool) -> Self {
1552        self.active = active;
1553        self
1554    }
1555
1556    /// Activates the focus trap.
1557    pub fn activate(&mut self) {
1558        self.active = true;
1559    }
1560
1561    /// Deactivates the focus trap.
1562    pub fn deactivate(&mut self) {
1563        self.active = false;
1564    }
1565
1566    /// Returns `true` if `id` is a member of this trap or lies within its spatial bounds.
1567    pub fn contains_candidate(&self, candidate: &FocusCandidate<T>) -> bool {
1568        if self.members.contains(&candidate.id) {
1569            return true;
1570        }
1571        if let Some(bounds) = self.bounds {
1572            if bounds.contains_point(candidate.rect.x, candidate.rect.y)
1573                || bounds.intersects(&candidate.rect)
1574            {
1575                return true;
1576            }
1577        }
1578        false
1579    }
1580
1581    /// Returns `true` if `id` is explicitly in `self.members`.
1582    pub fn contains_id(&self, id: &T) -> bool {
1583        self.members.contains(id)
1584    }
1585
1586    /// Returns `true` if navigation in `direction` is trapped (not in `exit_directions`).
1587    pub fn is_direction_trapped(&self, direction: FocusDirection) -> bool {
1588        self.active && !self.exit_directions.contains(&direction)
1589    }
1590
1591    /// Navigates within or out of the focus trap according to directional policies.
1592    pub fn navigate<'a>(
1593        &self,
1594        current_id: &T,
1595        current_rect: &FocusRect,
1596        candidates: &'a [FocusCandidate<T>],
1597        direction: FocusDirection,
1598    ) -> FocusTrapOutcome<'a, T> {
1599        // If inactive or current control not in trap, normal navigation
1600        if !self.active || !self.contains_id(current_id) {
1601            let next = find_next_focus(
1602                Some(current_id),
1603                Some(current_rect),
1604                candidates,
1605                direction,
1606                false,
1607            );
1608            return match next {
1609                Some(c) => FocusTrapOutcome::Moved(c),
1610                None => FocusTrapOutcome::Stopped,
1611            };
1612        }
1613
1614        // Check if direction is an allowed exit direction
1615        if self.exit_directions.contains(&direction) {
1616            let next = find_next_focus(
1617                Some(current_id),
1618                Some(current_rect),
1619                candidates,
1620                direction,
1621                false,
1622            );
1623            return match next {
1624                Some(c) => {
1625                    if self.contains_id(&c.id) {
1626                        FocusTrapOutcome::Moved(c)
1627                    } else {
1628                        FocusTrapOutcome::Exited(c)
1629                    }
1630                }
1631                None => FocusTrapOutcome::Stopped,
1632            };
1633        }
1634
1635        // Direction is trapped! Filter candidates to those within the trap
1636        let trapped_candidates: Vec<FocusCandidate<T>> = candidates
1637            .iter()
1638            .filter(|c| self.contains_candidate(c))
1639            .cloned()
1640            .collect();
1641
1642        // 1. Try finding next candidate within the trap without wrap
1643        if let Some(next) = find_next_focus(
1644            Some(current_id),
1645            Some(current_rect),
1646            &trapped_candidates,
1647            direction,
1648            false,
1649        ) {
1650            if let Some(original) = candidates.iter().find(|c| c.id == next.id) {
1651                return FocusTrapOutcome::Moved(original);
1652            }
1653        }
1654
1655        // 2. No forward candidate inside the trap: apply boundary policy
1656        match self.boundary_policy {
1657            FocusTrapBoundaryPolicy::Wrap => {
1658                if let Some(wrapped) = find_next_focus(
1659                    Some(current_id),
1660                    Some(current_rect),
1661                    &trapped_candidates,
1662                    direction,
1663                    true,
1664                ) {
1665                    if let Some(original) = candidates.iter().find(|c| c.id == wrapped.id) {
1666                        return FocusTrapOutcome::Wrapped(original);
1667                    }
1668                }
1669                FocusTrapOutcome::Stopped
1670            }
1671            FocusTrapBoundaryPolicy::Clamp => {
1672                if let Some(curr) = candidates.iter().find(|c| &c.id == current_id) {
1673                    FocusTrapOutcome::Clamped(curr)
1674                } else {
1675                    FocusTrapOutcome::Stopped
1676                }
1677            }
1678            FocusTrapBoundaryPolicy::Stop => FocusTrapOutcome::Stopped,
1679        }
1680    }
1681}
1682
1683// ---------------------------------------------------------------------------
1684// 6. Focus Ring Styling Metrics & WCAG Conformance
1685// ---------------------------------------------------------------------------
1686
1687/// Visual style pattern for focus indicator borders.
1688#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1689pub enum FocusRingStyle {
1690    /// Standard continuous solid border.
1691    #[default]
1692    Solid,
1693    /// Dotted indicator (e.g. classic Win32 `DrawFocusRect`).
1694    Dotted,
1695    /// Dashed indicator.
1696    Dashed,
1697    /// High-contrast double-ring (inner white ring, outer dark ring) for WCAG 2.4.11 / 2.4.13.
1698    DoubleRing,
1699}
1700
1701/// Metrics and styling parameters for rendering a native-grade visual focus ring
1702/// conforming to platform guidelines and WCAG 2.4.7 / 2.4.11 / 2.4.13 requirements.
1703#[derive(Debug, Clone, Copy, PartialEq)]
1704pub struct FocusRingMetrics {
1705    /// Border thickness of the focus ring in pixels.
1706    pub thickness: f32,
1707    /// Distance (gap) between the widget outer boundary and the focus ring.
1708    /// Positive values place the ring outside the widget; negative values inset it.
1709    pub offset: f32,
1710    /// Corner rounding radius for rounded focus rings in pixels.
1711    pub corner_radius: f32,
1712    /// Primary stroke color of the focus ring.
1713    pub color: Color,
1714    /// Optional secondary contrasting color (used for dual-tone high-contrast rings or dotted alternating pixels).
1715    pub secondary_color: Option<Color>,
1716    /// Visual pattern of the focus indicator.
1717    pub style: FocusRingStyle,
1718}
1719
1720impl Default for FocusRingMetrics {
1721    fn default() -> Self {
1722        Self::gtk()
1723    }
1724}
1725
1726impl FocusRingMetrics {
1727    /// Preset conforming to modern Windows 11 Fluent Design guidelines (2px solid accent ring with 1px margin).
1728    pub const fn win32() -> Self {
1729        Self {
1730            thickness: 2.0,
1731            offset: 1.0,
1732            corner_radius: 4.0,
1733            color: Color::rgb(0, 103, 192), // Windows 11 Accent Blue
1734            secondary_color: None,
1735            style: FocusRingStyle::Solid,
1736        }
1737    }
1738
1739    /// Preset conforming to classic Windows Win32 `DrawFocusRect` (1px dotted black outline, 0px offset).
1740    pub const fn win32_classic() -> Self {
1741        Self {
1742            thickness: 1.0,
1743            offset: 0.0,
1744            corner_radius: 0.0,
1745            color: Color::rgb(0, 0, 0),
1746            secondary_color: None,
1747            style: FocusRingStyle::Dotted,
1748        }
1749    }
1750
1751    /// Preset conforming to Linux GTK4 / GNOME Adwaita guidelines (2px solid accent ring with 2px offset).
1752    pub const fn gtk() -> Self {
1753        Self {
1754            thickness: 2.0,
1755            offset: 2.0,
1756            corner_radius: 4.0,
1757            color: Color::rgb(53, 132, 228), // Adwaita Blue
1758            secondary_color: None,
1759            style: FocusRingStyle::Solid,
1760        }
1761    }
1762
1763    /// Preset conforming to macOS AppKit / Cocoa focus halo standards (3px prominent halo with 1px offset).
1764    pub const fn cocoa() -> Self {
1765        Self {
1766            thickness: 3.0,
1767            offset: 1.0,
1768            corner_radius: 5.0,
1769            color: Color::rgb(10, 132, 255), // Apple System Blue
1770            secondary_color: None,
1771            style: FocusRingStyle::Solid,
1772        }
1773    }
1774
1775    /// Preset conforming to WCAG 2.4.11 / 2.4.13 High Contrast requirements (dual-tone contrasting double ring).
1776    pub const fn high_contrast() -> Self {
1777        Self {
1778            thickness: 3.0,
1779            offset: 2.0,
1780            corner_radius: 4.0,
1781            color: Color::rgb(255, 255, 255),           // Pure White
1782            secondary_color: Some(Color::rgb(0, 0, 0)), // Pure Black
1783            style: FocusRingStyle::DoubleRing,
1784        }
1785    }
1786
1787    /// Sets the stroke thickness in pixels.
1788    pub fn with_thickness(mut self, thickness: f32) -> Self {
1789        self.thickness = thickness;
1790        self
1791    }
1792
1793    /// Sets the offset gap from the widget boundary.
1794    pub fn with_offset(mut self, offset: f32) -> Self {
1795        self.offset = offset;
1796        self
1797    }
1798
1799    /// Sets the corner rounding radius.
1800    pub fn with_corner_radius(mut self, corner_radius: f32) -> Self {
1801        self.corner_radius = corner_radius;
1802        self
1803    }
1804
1805    /// Sets the primary stroke color.
1806    pub fn with_color(mut self, color: Color) -> Self {
1807        self.color = color;
1808        self
1809    }
1810
1811    /// Sets an optional secondary contrasting color.
1812    pub fn with_secondary_color(mut self, secondary: Color) -> Self {
1813        self.secondary_color = Some(secondary);
1814        self
1815    }
1816
1817    /// Sets the visual style pattern.
1818    pub fn with_style(mut self, style: FocusRingStyle) -> Self {
1819        self.style = style;
1820        self
1821    }
1822
1823    /// Computes the outer bounding rectangle enclosing the entire focus ring.
1824    pub fn compute_outer_bounds(&self, widget_bounds: FocusRect) -> FocusRect {
1825        let expansion = (self.offset + self.thickness).ceil() as i32;
1826        FocusRect::new(
1827            widget_bounds.x - expansion,
1828            widget_bounds.y - expansion,
1829            widget_bounds.width + (2 * expansion),
1830            widget_bounds.height + (2 * expansion),
1831        )
1832    }
1833
1834    /// Computes the inner edge rectangle enclosed by the focus ring.
1835    pub fn compute_inner_bounds(&self, widget_bounds: FocusRect) -> FocusRect {
1836        let offset_px = self.offset.round() as i32;
1837        FocusRect::new(
1838            widget_bounds.x - offset_px,
1839            widget_bounds.y - offset_px,
1840            widget_bounds.width + (2 * offset_px),
1841            widget_bounds.height + (2 * offset_px),
1842        )
1843    }
1844
1845    /// Computes the midline stroke rectangle used for rendering lines/borders.
1846    pub fn compute_ring_rect(&self, widget_bounds: FocusRect) -> FocusRect {
1847        let half_thickness = self.thickness / 2.0;
1848        let dist = (self.offset + half_thickness).round() as i32;
1849        FocusRect::new(
1850            widget_bounds.x - dist,
1851            widget_bounds.y - dist,
1852            widget_bounds.width + (2 * dist),
1853            widget_bounds.height + (2 * dist),
1854        )
1855    }
1856
1857    /// Calculates the WCAG 2.1 relative luminance of an sRGB color ($0.0 \le L \le 1.0$).
1858    pub fn relative_luminance(color: Color) -> f64 {
1859        fn linearize(channel: u8) -> f64 {
1860            let v = channel as f64 / 255.0;
1861            if v <= 0.04045 {
1862                v / 12.92
1863            } else {
1864                ((v + 0.055) / 1.055).powf(2.4)
1865            }
1866        }
1867        0.2126 * linearize(color.r) + 0.7152 * linearize(color.g) + 0.0722 * linearize(color.b)
1868    }
1869
1870    /// Computes the WCAG 2.1 contrast ratio between two colors ($1.0 \le \text{ratio} \le 21.0$).
1871    pub fn contrast_ratio(c1: Color, c2: Color) -> f64 {
1872        let l1 = Self::relative_luminance(c1);
1873        let l2 = Self::relative_luminance(c2);
1874        let (lighter, darker) = if l1 > l2 { (l1, l2) } else { (l2, l1) };
1875        (lighter + 0.05) / (darker + 0.05)
1876    }
1877
1878    /// Returns `true` if the focus ring color achieves at least a 3.0:1 contrast ratio
1879    /// against the provided background color (WCAG 2.1 Success Criterion 1.4.11 / 2.4.11).
1880    pub fn meets_wcag_contrast(&self, background: Color) -> bool {
1881        Self::contrast_ratio(self.color, background) >= 3.0
1882    }
1883}
1884
1885// ---------------------------------------------------------------------------
1886// 5. Unit Tests
1887// ---------------------------------------------------------------------------
1888
1889#[cfg(test)]
1890mod tests {
1891    use super::*;
1892
1893    #[test]
1894    fn default_focusable_covers_every_widget_kind() {
1895        let expected = [
1896            (WidgetKind::Window, false),
1897            (WidgetKind::Container, false),
1898            (WidgetKind::Label, false),
1899            (WidgetKind::Button, true),
1900            #[cfg(feature = "widgets-choice")]
1901            (WidgetKind::RadioButton, true),
1902            #[cfg(feature = "widgets-range")]
1903            (WidgetKind::Slider, true),
1904            #[cfg(feature = "widgets-range")]
1905            (WidgetKind::SpinBox, true),
1906            #[cfg(feature = "widgets-containers")]
1907            (WidgetKind::Separator, false),
1908            #[cfg(feature = "widgets-containers")]
1909            (WidgetKind::GroupBox, false),
1910            #[cfg(feature = "widgets-containers")]
1911            (WidgetKind::Tabs, true),
1912            #[cfg(feature = "widgets-media")]
1913            (WidgetKind::Image, false),
1914            #[cfg(feature = "widgets-pickers")]
1915            (WidgetKind::DatePicker, true),
1916            #[cfg(feature = "widgets-text")]
1917            (WidgetKind::LinkLabel, true),
1918            #[cfg(feature = "widgets-data")]
1919            (WidgetKind::ListView, true),
1920            #[cfg(feature = "widgets-data")]
1921            (WidgetKind::TreeView, true),
1922            #[cfg(feature = "widgets-containers")]
1923            (WidgetKind::SplitPane, false),
1924            #[cfg(feature = "widgets-pickers")]
1925            (WidgetKind::FileChooserDialog, true),
1926            #[cfg(feature = "widgets-containers")]
1927            (WidgetKind::AlertDialog, true),
1928            #[cfg(feature = "widgets-text")]
1929            (WidgetKind::TextInput, true),
1930            #[cfg(feature = "widgets-text")]
1931            (WidgetKind::TextArea, true),
1932            #[cfg(feature = "widgets-canvas")]
1933            (WidgetKind::VulkanCanvas, false),
1934            #[cfg(feature = "widgets-choice")]
1935            (WidgetKind::Checkbox, true),
1936            #[cfg(feature = "widgets-choice")]
1937            (WidgetKind::ComboBox, true),
1938            #[cfg(feature = "widgets-range")]
1939            (WidgetKind::ProgressBar, false),
1940            #[cfg(feature = "widgets-data")]
1941            (WidgetKind::DataList, true),
1942            #[cfg(feature = "widgets-data")]
1943            (WidgetKind::DataGrid, true),
1944            #[cfg(feature = "widgets-canvas")]
1945            (WidgetKind::Canvas, true),
1946            #[cfg(feature = "widgets-pickers")]
1947            (WidgetKind::ColorDialog, true),
1948            #[cfg(feature = "widgets-pickers")]
1949            (WidgetKind::FontDialog, true),
1950            (WidgetKind::Toolbar, false),
1951            #[cfg(feature = "widgets-pickers")]
1952            (WidgetKind::Calendar, true),
1953            #[cfg(feature = "widgets-choice")]
1954            (WidgetKind::MultiSelect, true),
1955        ];
1956
1957        // Canary: the table must stay in lockstep with the abstractable set.
1958        assert_eq!(expected.len(), abstractable_widget_types().len());
1959        for (kind, focusable) in expected {
1960            assert_eq!(default_focusable(kind), focusable, "default for {kind:?}");
1961        }
1962    }
1963
1964    #[test]
1965    fn explicit_override_wins_over_the_per_kind_default() {
1966        let mut label = WidgetSpec::new(WidgetId(1), WidgetKind::Label);
1967        assert!(!is_focusable(&label));
1968        label.focusable = Some(true);
1969        assert!(is_focusable(&label));
1970
1971        let mut button = WidgetSpec::new(WidgetId(2), WidgetKind::Button);
1972        assert!(is_focusable(&button));
1973        button.focusable = Some(false);
1974        assert!(!is_focusable(&button));
1975    }
1976
1977    #[test]
1978    fn focus_direction_properties_and_invariants() {
1979        assert!(FocusDirection::Up.is_directional());
1980        assert!(FocusDirection::Down.is_directional());
1981        assert!(FocusDirection::Left.is_directional());
1982        assert!(FocusDirection::Right.is_directional());
1983        assert!(!FocusDirection::TabNext.is_directional());
1984        assert!(!FocusDirection::TabPrev.is_directional());
1985
1986        assert!(FocusDirection::TabNext.is_tab());
1987        assert!(FocusDirection::TabPrev.is_tab());
1988        assert!(!FocusDirection::Up.is_tab());
1989
1990        assert_eq!(FocusDirection::Up.opposite(), FocusDirection::Down);
1991        assert_eq!(FocusDirection::Down.opposite(), FocusDirection::Up);
1992        assert_eq!(FocusDirection::Left.opposite(), FocusDirection::Right);
1993        assert_eq!(FocusDirection::Right.opposite(), FocusDirection::Left);
1994        assert_eq!(FocusDirection::TabNext.opposite(), FocusDirection::TabPrev);
1995        assert_eq!(FocusDirection::TabPrev.opposite(), FocusDirection::TabNext);
1996
1997        assert_eq!(FocusDirection::Up.unit_vector(), Some((0, -1)));
1998        assert_eq!(FocusDirection::Down.unit_vector(), Some((0, 1)));
1999        assert_eq!(FocusDirection::Left.unit_vector(), Some((-1, 0)));
2000        assert_eq!(FocusDirection::Right.unit_vector(), Some((1, 0)));
2001        assert_eq!(FocusDirection::TabNext.unit_vector(), None);
2002    }
2003
2004    #[test]
2005    fn focus_rect_geometry_and_queries() {
2006        let r = FocusRect::new(10, 20, 100, 50);
2007        assert_eq!(r.left(), 10);
2008        assert_eq!(r.top(), 20);
2009        assert_eq!(r.right(), 110);
2010        assert_eq!(r.bottom(), 70);
2011        assert_eq!(r.center_x(), 60.0);
2012        assert_eq!(r.center_y(), 45.0);
2013        assert_eq!(r.center(), (60.0, 45.0));
2014        assert!(!r.is_empty());
2015
2016        assert!(r.contains_point(10, 20));
2017        assert!(r.contains_point(109, 69));
2018        assert!(!r.contains_point(110, 70));
2019        assert!(!r.contains_point(9, 20));
2020
2021        let intersecting = FocusRect::new(50, 40, 80, 60);
2022        assert!(r.intersects(&intersecting));
2023        assert!(intersecting.intersects(&r));
2024
2025        let disjoint = FocusRect::new(200, 200, 30, 30);
2026        assert!(!r.intersects(&disjoint));
2027
2028        let empty = FocusRect::new(0, 0, 0, 0);
2029        assert!(empty.is_empty());
2030    }
2031
2032    #[test]
2033    fn directional_2d_horizontal_row_navigation() {
2034        // Layout: [Btn1 (10..60)] -- [Btn2 (80..130)] -- [Btn3 (150..200)] all at y=20..50
2035        let b1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 20, 50, 30));
2036        let b2 = FocusCandidate::new(WidgetId(2), FocusRect::new(80, 20, 50, 30));
2037        let b3 = FocusCandidate::new(WidgetId(3), FocusRect::new(150, 20, 50, 30));
2038        let candidates = [b1.clone(), b2.clone(), b3.clone()];
2039
2040        // Moving Right: b1 -> b2 -> b3
2041        let next_from_b1 = find_next_focus_2d(&b1.rect, &candidates, FocusDirection::Right, false);
2042        assert_eq!(next_from_b1.map(|c| c.id), Some(WidgetId(2)));
2043
2044        let next_from_b2 = find_next_focus_2d(&b2.rect, &candidates, FocusDirection::Right, false);
2045        assert_eq!(next_from_b2.map(|c| c.id), Some(WidgetId(3)));
2046
2047        let next_from_b3_no_wrap =
2048            find_next_focus_2d(&b3.rect, &candidates, FocusDirection::Right, false);
2049        assert_eq!(next_from_b3_no_wrap, None);
2050
2051        // Moving Right with wrap-around: b3 wraps back to b1
2052        let next_from_b3_wrap =
2053            find_next_focus_2d(&b3.rect, &candidates, FocusDirection::Right, true);
2054        assert_eq!(next_from_b3_wrap.map(|c| c.id), Some(WidgetId(1)));
2055
2056        // Moving Left: b3 -> b2 -> b1
2057        let prev_from_b3 = find_next_focus_2d(&b3.rect, &candidates, FocusDirection::Left, false);
2058        assert_eq!(prev_from_b3.map(|c| c.id), Some(WidgetId(2)));
2059
2060        let prev_from_b2 = find_next_focus_2d(&b2.rect, &candidates, FocusDirection::Left, false);
2061        assert_eq!(prev_from_b2.map(|c| c.id), Some(WidgetId(1)));
2062
2063        // Moving Left with wrap-around: b1 wraps to b3
2064        let prev_from_b1_wrap =
2065            find_next_focus_2d(&b1.rect, &candidates, FocusDirection::Left, true);
2066        assert_eq!(prev_from_b1_wrap.map(|c| c.id), Some(WidgetId(3)));
2067    }
2068
2069    #[test]
2070    fn directional_2d_vertical_column_navigation() {
2071        // Layout: [Row1 (y=10..40)], [Row2 (y=60..90)], [Row3 (y=110..140)] all at x=10..100
2072        let r1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 90, 30));
2073        let r2 = FocusCandidate::new(WidgetId(2), FocusRect::new(10, 60, 90, 30));
2074        let r3 = FocusCandidate::new(WidgetId(3), FocusRect::new(10, 110, 90, 30));
2075        let candidates = [r1.clone(), r2.clone(), r3.clone()];
2076
2077        // Moving Down: r1 -> r2 -> r3
2078        let next_down_1 = find_next_focus_2d(&r1.rect, &candidates, FocusDirection::Down, false);
2079        assert_eq!(next_down_1.map(|c| c.id), Some(WidgetId(2)));
2080
2081        let next_down_2 = find_next_focus_2d(&r2.rect, &candidates, FocusDirection::Down, false);
2082        assert_eq!(next_down_2.map(|c| c.id), Some(WidgetId(3)));
2083
2084        // Wrap around downwards: r3 wraps to r1
2085        let next_down_3_wrap =
2086            find_next_focus_2d(&r3.rect, &candidates, FocusDirection::Down, true);
2087        assert_eq!(next_down_3_wrap.map(|c| c.id), Some(WidgetId(1)));
2088
2089        // Moving Up: r3 -> r2 -> r1
2090        let next_up_3 = find_next_focus_2d(&r3.rect, &candidates, FocusDirection::Up, false);
2091        assert_eq!(next_up_3.map(|c| c.id), Some(WidgetId(2)));
2092
2093        // Wrap around upwards: r1 wraps to r3
2094        let next_up_1_wrap = find_next_focus_2d(&r1.rect, &candidates, FocusDirection::Up, true);
2095        assert_eq!(next_up_1_wrap.map(|c| c.id), Some(WidgetId(3)));
2096    }
2097
2098    #[test]
2099    fn directional_2d_grid_navigation() {
2100        // 2x2 Grid:
2101        // [A (10, 10, 40, 40)]  [B (70, 10, 40, 40)]
2102        // [C (10, 70, 40, 40)]  [D (70, 70, 40, 40)]
2103        let a = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 40, 40));
2104        let b = FocusCandidate::new(WidgetId(2), FocusRect::new(70, 10, 40, 40));
2105        let c = FocusCandidate::new(WidgetId(3), FocusRect::new(10, 70, 40, 40));
2106        let d = FocusCandidate::new(WidgetId(4), FocusRect::new(70, 70, 40, 40));
2107        let grid = [a.clone(), b.clone(), c.clone(), d.clone()];
2108
2109        // From A: Right -> B, Down -> C
2110        assert_eq!(
2111            find_next_focus_2d(&a.rect, &grid, FocusDirection::Right, false).map(|x| x.id),
2112            Some(WidgetId(2))
2113        );
2114        assert_eq!(
2115            find_next_focus_2d(&a.rect, &grid, FocusDirection::Down, false).map(|x| x.id),
2116            Some(WidgetId(3))
2117        );
2118
2119        // From B: Left -> A, Down -> D
2120        assert_eq!(
2121            find_next_focus_2d(&b.rect, &grid, FocusDirection::Left, false).map(|x| x.id),
2122            Some(WidgetId(1))
2123        );
2124        assert_eq!(
2125            find_next_focus_2d(&b.rect, &grid, FocusDirection::Down, false).map(|x| x.id),
2126            Some(WidgetId(4))
2127        );
2128
2129        // From C: Up -> A, Right -> D
2130        assert_eq!(
2131            find_next_focus_2d(&c.rect, &grid, FocusDirection::Up, false).map(|x| x.id),
2132            Some(WidgetId(1))
2133        );
2134        assert_eq!(
2135            find_next_focus_2d(&c.rect, &grid, FocusDirection::Right, false).map(|x| x.id),
2136            Some(WidgetId(4))
2137        );
2138
2139        // From D: Up -> B, Left -> C
2140        assert_eq!(
2141            find_next_focus_2d(&d.rect, &grid, FocusDirection::Up, false).map(|x| x.id),
2142            Some(WidgetId(2))
2143        );
2144        assert_eq!(
2145            find_next_focus_2d(&d.rect, &grid, FocusDirection::Left, false).map(|x| x.id),
2146            Some(WidgetId(3))
2147        );
2148    }
2149
2150    #[test]
2151    fn directional_beam_projection_prefers_in_beam_over_diagonal() {
2152        // Source: S at (10, 10, 50, 30)
2153        // Candidate 1 (In beam, farther): (120, 10, 50, 30) - shares Y interval [10, 40]
2154        // Candidate 2 (Off beam / diagonal, closer Euclidean distance): (70, 70, 50, 30)
2155        let s = FocusRect::new(10, 10, 50, 30);
2156        let in_beam = FocusCandidate::new(WidgetId(1), FocusRect::new(120, 10, 50, 30));
2157        let off_beam = FocusCandidate::new(WidgetId(2), FocusRect::new(70, 70, 50, 30));
2158        let candidates = [off_beam.clone(), in_beam.clone()];
2159
2160        let target = find_next_focus_2d(&s, &candidates, FocusDirection::Right, false);
2161        assert_eq!(
2162            target.map(|c| c.id),
2163            Some(WidgetId(1)),
2164            "In-beam projection must win over diagonal target"
2165        );
2166    }
2167
2168    #[test]
2169    fn directional_navigation_skips_unfocusable_candidates() {
2170        let b1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 50, 30));
2171        let b2_disabled =
2172            FocusCandidate::new(WidgetId(2), FocusRect::new(80, 10, 50, 30)).with_focusable(false);
2173        let b3 = FocusCandidate::new(WidgetId(3), FocusRect::new(150, 10, 50, 30));
2174        let candidates = [b1.clone(), b2_disabled, b3.clone()];
2175
2176        let next = find_next_focus_2d(&b1.rect, &candidates, FocusDirection::Right, false);
2177        assert_eq!(
2178            next.map(|c| c.id),
2179            Some(WidgetId(3)),
2180            "Must jump over disabled/unfocusable candidate"
2181        );
2182    }
2183
2184    #[test]
2185    fn tab_navigation_sequence_and_wrap_around() {
2186        let c1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 40, 20));
2187        let c2 = FocusCandidate::new(WidgetId(2), FocusRect::new(60, 10, 40, 20));
2188        let c3 = FocusCandidate::new(WidgetId(3), FocusRect::new(10, 40, 40, 20));
2189        let candidates = [c1.clone(), c2.clone(), c3.clone()];
2190
2191        // Natural reading order: c1 -> c2 -> c3
2192        let t1 = find_next_focus_tab(
2193            Some(&WidgetId(1)),
2194            &candidates,
2195            FocusDirection::TabNext,
2196            true,
2197        );
2198        assert_eq!(t1.map(|c| c.id), Some(WidgetId(2)));
2199
2200        let t2 = find_next_focus_tab(
2201            Some(&WidgetId(2)),
2202            &candidates,
2203            FocusDirection::TabNext,
2204            true,
2205        );
2206        assert_eq!(t2.map(|c| c.id), Some(WidgetId(3)));
2207
2208        // Wrap around to first
2209        let t3 = find_next_focus_tab(
2210            Some(&WidgetId(3)),
2211            &candidates,
2212            FocusDirection::TabNext,
2213            true,
2214        );
2215        assert_eq!(t3.map(|c| c.id), Some(WidgetId(1)));
2216
2217        // Backward tab: c1 wraps to c3
2218        let prev = find_next_focus_tab(
2219            Some(&WidgetId(1)),
2220            &candidates,
2221            FocusDirection::TabPrev,
2222            true,
2223        );
2224        assert_eq!(prev.map(|c| c.id), Some(WidgetId(3)));
2225    }
2226
2227    #[test]
2228    fn tab_navigation_explicit_tab_indices_take_priority() {
2229        let c1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 40, 20)).with_tab_index(2);
2230        let c2 = FocusCandidate::new(WidgetId(2), FocusRect::new(60, 10, 40, 20)).with_tab_index(1);
2231        let candidates = [c1.clone(), c2.clone()];
2232
2233        // Explicit tab index 1 (c2) navigates before tab index 2 (c1)
2234        let first = find_next_focus_tab(None, &candidates, FocusDirection::TabNext, true);
2235        assert_eq!(first.map(|c| c.id), Some(WidgetId(2)));
2236
2237        let second = find_next_focus_tab(
2238            Some(&WidgetId(2)),
2239            &candidates,
2240            FocusDirection::TabNext,
2241            true,
2242        );
2243        assert_eq!(second.map(|c| c.id), Some(WidgetId(1)));
2244    }
2245
2246    #[test]
2247    fn focus_ring_metrics_presets_and_bounds() {
2248        let win = FocusRingMetrics::win32();
2249        assert_eq!(win.thickness, 2.0);
2250        assert_eq!(win.offset, 1.0);
2251        assert_eq!(win.style, FocusRingStyle::Solid);
2252
2253        let classic = FocusRingMetrics::win32_classic();
2254        assert_eq!(classic.style, FocusRingStyle::Dotted);
2255        assert_eq!(classic.thickness, 1.0);
2256
2257        let gtk = FocusRingMetrics::gtk();
2258        assert_eq!(gtk.thickness, 2.0);
2259        assert_eq!(gtk.offset, 2.0);
2260
2261        let cocoa = FocusRingMetrics::cocoa();
2262        assert_eq!(cocoa.thickness, 3.0);
2263        assert_eq!(cocoa.offset, 1.0);
2264
2265        let hc = FocusRingMetrics::high_contrast();
2266        assert_eq!(hc.style, FocusRingStyle::DoubleRing);
2267        assert!(hc.secondary_color.is_some());
2268
2269        // Bounds calculations
2270        let widget = FocusRect::new(20, 30, 100, 40);
2271        let outer = gtk.compute_outer_bounds(widget);
2272        // gtk: offset = 2.0, thickness = 2.0 -> expansion = 4
2273        assert_eq!(outer, FocusRect::new(16, 26, 108, 48));
2274
2275        let inner = gtk.compute_inner_bounds(widget);
2276        // offset = 2.0 -> inner expansion = 2
2277        assert_eq!(inner, FocusRect::new(18, 28, 104, 44));
2278
2279        let stroke = gtk.compute_ring_rect(widget);
2280        // dist = round(2.0 + 1.0) = 3
2281        assert_eq!(stroke, FocusRect::new(17, 27, 106, 46));
2282    }
2283
2284    #[test]
2285    fn focus_ring_wcag_luminance_and_contrast() {
2286        let white = Color::rgb(255, 255, 255);
2287        let black = Color::rgb(0, 0, 0);
2288
2289        let lum_white = FocusRingMetrics::relative_luminance(white);
2290        let lum_black = FocusRingMetrics::relative_luminance(black);
2291        assert!((lum_white - 1.0).abs() < 1e-4);
2292        assert!(lum_black.abs() < 1e-4);
2293
2294        // Maximum contrast ratio 21:1
2295        let ratio_bw = FocusRingMetrics::contrast_ratio(white, black);
2296        assert!((ratio_bw - 21.0).abs() < 0.1);
2297
2298        // Identical colors have contrast 1:1
2299        let ratio_same = FocusRingMetrics::contrast_ratio(white, white);
2300        assert!((ratio_same - 1.0).abs() < 1e-4);
2301
2302        // High contrast preset meets WCAG AA on black and white backgrounds
2303        let hc = FocusRingMetrics::high_contrast();
2304        assert!(hc.meets_wcag_contrast(black));
2305
2306        let win = FocusRingMetrics::win32();
2307        assert!(win.meets_wcag_contrast(white));
2308    }
2309
2310    #[test]
2311    fn aspect_ratio_calculation_and_distance_weighting() {
2312        let square = FocusRect::new(0, 0, 50, 50);
2313        let wide = FocusRect::new(0, 0, 200, 50);
2314        let tall = FocusRect::new(0, 0, 50, 200);
2315
2316        assert!((square.aspect_ratio() - 1.0).abs() < 1e-6);
2317        assert!((wide.aspect_ratio() - 4.0).abs() < 1e-6);
2318        assert!((tall.aspect_ratio() - 0.25).abs() < 1e-6);
2319
2320        // Aspect ratio with zero or negative height falls back to 1.0
2321        let zero_h = FocusRect::new(0, 0, 100, 0);
2322        assert!((zero_h.aspect_ratio() - 1.0).abs() < 1e-6);
2323
2324        // Scenario: Source control at (0, 0, 50, 50)
2325        // Two candidates to the right:
2326        // Candidate 1 (narrow tall button): at (100, 60, 20, 50), off-beam, AR = 0.4
2327        // Candidate 2 (wide card): at (100, 70, 200, 40), off-beam, AR = 5.0
2328        let source = FocusRect::new(0, 0, 50, 50);
2329        let tall_cand = FocusCandidate::new(WidgetId(1), FocusRect::new(100, 60, 20, 50));
2330        let wide_cand = FocusCandidate::new(WidgetId(2), FocusRect::new(100, 70, 200, 40));
2331        let candidates = [tall_cand.clone(), wide_cand.clone()];
2332
2333        // With standard options (aspect_ratio_weight = 0.0), tall candidate has slightly lower orthogonal gap (55 vs 60)
2334        let unweighted = find_next_focus_2d_options(
2335            &source,
2336            &candidates,
2337            FocusDirection::Right,
2338            false,
2339            &ProjectionOptions::standard(),
2340        );
2341        assert_eq!(unweighted.map(|c| c.id), Some(WidgetId(1)));
2342
2343        // With aspect-ratio weighting (aspect_ratio_weight = 1.0), wide candidate's orthogonal penalty
2344        // is divided by 5.0, making it win over tall candidate!
2345        let weighted = find_next_focus_2d_options(
2346            &source,
2347            &candidates,
2348            FocusDirection::Right,
2349            false,
2350            &ProjectionOptions::with_aspect_ratio_weighting(1.0),
2351        );
2352        assert_eq!(weighted.map(|c| c.id), Some(WidgetId(2)));
2353    }
2354
2355    #[test]
2356    fn grid_multi_column_navigation_and_wrap_modes() {
2357        // 3 columns x 3 rows grid:
2358        // [1, 2, 3]
2359        // [4, 5, 6]
2360        // [7, 8, 9]
2361        let mut candidates = Vec::new();
2362        for id in 1..=9 {
2363            let row = (id - 1) / 3;
2364            let col = (id - 1) % 3;
2365            candidates.push(FocusCandidate::new(
2366                WidgetId(id),
2367                FocusRect::new(col as i32 * 60, row as i32 * 40, 50, 30),
2368            ));
2369        }
2370
2371        // Test GridWrapMode::None (default)
2372        let grid_none = FocusGrid::from_candidates(3, candidates.clone());
2373        assert_eq!(grid_none.columns, 3);
2374        assert_eq!(grid_none.rows, 3);
2375
2376        // Within boundaries
2377        assert_eq!(
2378            grid_none
2379                .navigate_step(&WidgetId(1), FocusDirection::Right, 1)
2380                .map(|c| c.id),
2381            Some(WidgetId(2))
2382        );
2383        assert_eq!(
2384            grid_none
2385                .navigate_step(&WidgetId(1), FocusDirection::Down, 1)
2386                .map(|c| c.id),
2387            Some(WidgetId(4))
2388        );
2389
2390        // Clamping at boundaries (None mode)
2391        assert_eq!(
2392            grid_none.navigate_step(&WidgetId(3), FocusDirection::Right, 1),
2393            None
2394        );
2395        assert_eq!(
2396            grid_none.navigate_step(&WidgetId(1), FocusDirection::Left, 1),
2397            None
2398        );
2399        assert_eq!(
2400            grid_none.navigate_step(&WidgetId(7), FocusDirection::Down, 1),
2401            None
2402        );
2403        assert_eq!(
2404            grid_none.navigate_step(&WidgetId(2), FocusDirection::Up, 1),
2405            None
2406        );
2407
2408        // Test GridWrapMode::Axis (toroidal within row/column)
2409        let grid_axis = grid_none.clone().with_wrap_mode(GridWrapMode::Axis);
2410        assert_eq!(
2411            grid_axis
2412                .navigate_step(&WidgetId(3), FocusDirection::Right, 1)
2413                .map(|c| c.id),
2414            Some(WidgetId(1)),
2415            "Row wraps back to column 0 in Axis mode"
2416        );
2417        assert_eq!(
2418            grid_axis
2419                .navigate_step(&WidgetId(1), FocusDirection::Left, 1)
2420                .map(|c| c.id),
2421            Some(WidgetId(3)),
2422            "Row wraps back to column 2 in Axis mode"
2423        );
2424        assert_eq!(
2425            grid_axis
2426                .navigate_step(&WidgetId(8), FocusDirection::Down, 1)
2427                .map(|c| c.id),
2428            Some(WidgetId(2)),
2429            "Column wraps back to row 0 in Axis mode"
2430        );
2431        assert_eq!(
2432            grid_axis
2433                .navigate_step(&WidgetId(2), FocusDirection::Up, 1)
2434                .map(|c| c.id),
2435            Some(WidgetId(8)),
2436            "Column wraps back to bottom row in Axis mode"
2437        );
2438
2439        // Test GridWrapMode::Flow (continuous reading order)
2440        let grid_flow = grid_none.clone().with_wrap_mode(GridWrapMode::Flow);
2441        assert_eq!(
2442            grid_flow
2443                .navigate_step(&WidgetId(3), FocusDirection::Right, 1)
2444                .map(|c| c.id),
2445            Some(WidgetId(4)),
2446            "End of row wraps to beginning of next row in Flow mode"
2447        );
2448        assert_eq!(
2449            grid_flow
2450                .navigate_step(&WidgetId(4), FocusDirection::Left, 1)
2451                .map(|c| c.id),
2452            Some(WidgetId(3)),
2453            "Start of row wraps to end of previous row in Flow mode"
2454        );
2455        assert_eq!(
2456            grid_flow
2457                .navigate_step(&WidgetId(9), FocusDirection::Right, 1)
2458                .map(|c| c.id),
2459            Some(WidgetId(1)),
2460            "End of grid wraps to first item in Flow mode"
2461        );
2462        assert_eq!(
2463            grid_flow
2464                .navigate_step(&WidgetId(1), FocusDirection::Left, 1)
2465                .map(|c| c.id),
2466            Some(WidgetId(9)),
2467            "Start of grid wraps to last item in Flow mode"
2468        );
2469    }
2470
2471    #[test]
2472    fn grid_navigation_acceleration() {
2473        let mut accel = GridAccelerator::new(2, 2, 6);
2474        assert_eq!(accel.current_step(), 1);
2475
2476        // First press Right
2477        assert_eq!(accel.record_step(FocusDirection::Right), 1);
2478        // Second press Right (hits threshold 2)
2479        assert_eq!(accel.record_step(FocusDirection::Right), 1);
2480        // Third press Right (accelerates: 1 + 1*2 = 3)
2481        assert_eq!(accel.record_step(FocusDirection::Right), 3);
2482        // Fourth press Right (accelerates: 1 + 2*2 = 5)
2483        assert_eq!(accel.record_step(FocusDirection::Right), 5);
2484        // Fifth press Right (caps at max_step 6)
2485        assert_eq!(accel.record_step(FocusDirection::Right), 6);
2486
2487        // Direction change to Down resets consecutive count
2488        assert_eq!(accel.record_step(FocusDirection::Down), 1);
2489
2490        // Accelerated grid navigation across a 6x6 grid
2491        let mut candidates = Vec::new();
2492        for id in 1..=36 {
2493            let row = (id - 1) / 6;
2494            let col = (id - 1) % 6;
2495            candidates.push(FocusCandidate::new(
2496                WidgetId(id),
2497                FocusRect::new(col as i32 * 50, row as i32 * 50, 40, 40),
2498            ));
2499        }
2500
2501        let mut grid = FocusGrid::from_candidates(6, candidates)
2502            .with_accelerator(GridAccelerator::new(1, 2, 4));
2503
2504        // Start at Widget 1 (col 0, row 0)
2505        // Step 1: step = 1 -> moves to Widget 2 (col 1, row 0)
2506        let n1 = grid.navigate_accelerated(&WidgetId(1), FocusDirection::Right);
2507        assert_eq!(n1.map(|c| c.id), Some(WidgetId(2)));
2508
2509        // Step 2: consecutive = 2 > threshold 1 -> step = 1 + 1*2 = 3 -> moves from Widget 2 by 3 to Widget 5 (col 4, row 0)!
2510        let n2 = grid.navigate_accelerated(&WidgetId(2), FocusDirection::Right);
2511        assert_eq!(n2.map(|c| c.id), Some(WidgetId(5)));
2512    }
2513
2514    #[test]
2515    fn grid_skips_unfocusable_and_empty_cells() {
2516        // 3x3 grid:
2517        // [1 (enabled), 2 (disabled), 3 (empty/None)]
2518        // [4 (enabled), 5 (enabled),  6 (enabled)]
2519        let mut grid = FocusGrid::new(3, 3);
2520        grid.set_cell(
2521            0,
2522            0,
2523            Some(FocusCandidate::new(
2524                WidgetId(1),
2525                FocusRect::new(0, 0, 40, 30),
2526            )),
2527        );
2528        grid.set_cell(
2529            1,
2530            0,
2531            Some(
2532                FocusCandidate::new(WidgetId(2), FocusRect::new(50, 0, 40, 30))
2533                    .with_focusable(false),
2534            ),
2535        );
2536        grid.set_cell(2, 0, None); // empty cell
2537
2538        grid.set_cell(
2539            0,
2540            1,
2541            Some(FocusCandidate::new(
2542                WidgetId(4),
2543                FocusRect::new(0, 40, 40, 30),
2544            )),
2545        );
2546        grid.set_cell(
2547            1,
2548            1,
2549            Some(FocusCandidate::new(
2550                WidgetId(5),
2551                FocusRect::new(50, 40, 40, 30),
2552            )),
2553        );
2554
2555        // In None mode, moving Right from 1 cannot land on 2 (disabled) or 3 (empty), returns None
2556        assert_eq!(
2557            grid.navigate_step(&WidgetId(1), FocusDirection::Right, 1),
2558            None
2559        );
2560
2561        // In Flow mode, moving Right from 1 skips disabled 2 and empty 3, wrapping to row 1 col 0 (Widget 4)!
2562        let grid_flow = grid.clone().with_wrap_mode(GridWrapMode::Flow);
2563        assert_eq!(
2564            grid_flow
2565                .navigate_step(&WidgetId(1), FocusDirection::Right, 1)
2566                .map(|c| c.id),
2567            Some(WidgetId(4))
2568        );
2569    }
2570
2571    #[test]
2572    fn directional_focus_trap_containment_and_policies() {
2573        // Layout:
2574        // Dialog trap contains controls [1, 2, 3]
2575        // Outside the dialog is control 4
2576        let c1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 40, 20));
2577        let c2 = FocusCandidate::new(WidgetId(2), FocusRect::new(60, 10, 40, 20));
2578        let c3 = FocusCandidate::new(WidgetId(3), FocusRect::new(110, 10, 40, 20));
2579        let c4 = FocusCandidate::new(WidgetId(4), FocusRect::new(200, 10, 40, 20)); // outside trap
2580        let candidates = [c1.clone(), c2.clone(), c3.clone(), c4.clone()];
2581
2582        // 1. Wrap policy (default): moving Right from c3 wraps to c1 within trap, ignoring c4
2583        let trap_wrap = FocusTrap::new(vec![WidgetId(1), WidgetId(2), WidgetId(3)])
2584            .with_boundary_policy(FocusTrapBoundaryPolicy::Wrap);
2585
2586        let out1 = trap_wrap.navigate(&WidgetId(2), &c2.rect, &candidates, FocusDirection::Right);
2587        assert_eq!(out1, FocusTrapOutcome::Moved(&c3));
2588
2589        let out2 = trap_wrap.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
2590        assert_eq!(out2, FocusTrapOutcome::Wrapped(&c1));
2591
2592        let out_tab_prev =
2593            trap_wrap.navigate(&WidgetId(1), &c1.rect, &candidates, FocusDirection::TabPrev);
2594        assert_eq!(out_tab_prev, FocusTrapOutcome::Wrapped(&c3));
2595
2596        // 2. Clamp policy: moving Right from c3 clamps at c3
2597        let trap_clamp = trap_wrap
2598            .clone()
2599            .with_boundary_policy(FocusTrapBoundaryPolicy::Clamp);
2600        let out_clamp =
2601            trap_clamp.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
2602        assert_eq!(out_clamp, FocusTrapOutcome::Clamped(&c3));
2603
2604        // 3. Stop policy: moving Right from c3 returns Stopped
2605        let trap_stop = trap_wrap
2606            .clone()
2607            .with_boundary_policy(FocusTrapBoundaryPolicy::Stop);
2608        let out_stop =
2609            trap_stop.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
2610        assert_eq!(out_stop, FocusTrapOutcome::Stopped);
2611
2612        // 4. Directional Exit: allow escaping Right
2613        let trap_exit = trap_wrap.clone().with_exit_direction(FocusDirection::Right);
2614        let out_exit =
2615            trap_exit.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
2616        assert_eq!(out_exit, FocusTrapOutcome::Exited(&c4));
2617
2618        // 5. Inactive trap allows unconstrained navigation
2619        let mut trap_inactive = trap_wrap.clone();
2620        trap_inactive.deactivate();
2621        let out_inactive =
2622            trap_inactive.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
2623        assert_eq!(out_inactive, FocusTrapOutcome::Moved(&c4));
2624    }
2625}