Skip to main content

ftui_widgets/focus/
manager.rs

1#![forbid(unsafe_code)]
2
3//! Focus manager coordinating focus traversal, history, and traps.
4//!
5//! The manager tracks the current focus, maintains a navigation history,
6//! and enforces focus traps for modal dialogs. It also provides a
7//! configurable [`FocusIndicator`] for styling the focused widget.
8
9use ahash::AHashMap;
10
11use super::indicator::FocusIndicator;
12use super::spatial;
13use super::{FocusGraph, FocusId, NavDirection};
14
15/// Focus change events emitted by the manager.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum FocusEvent {
18    FocusGained { id: FocusId },
19    FocusLost { id: FocusId },
20    FocusMoved { from: FocusId, to: FocusId },
21}
22
23/// Group of focusable widgets for tab traversal.
24#[derive(Debug, Clone)]
25pub struct FocusGroup {
26    pub id: u32,
27    pub members: Vec<FocusId>,
28    pub wrap: bool,
29}
30
31impl FocusGroup {
32    #[must_use]
33    pub fn new(id: u32, members: Vec<FocusId>) -> Self {
34        Self {
35            id,
36            members,
37            wrap: true,
38        }
39    }
40
41    #[must_use]
42    pub fn with_wrap(mut self, wrap: bool) -> Self {
43        self.wrap = wrap;
44        self
45    }
46
47    fn contains(&self, id: FocusId) -> bool {
48        self.members.contains(&id)
49    }
50}
51
52/// Active focus trap (e.g., modal).
53#[derive(Debug, Clone, Copy)]
54pub struct FocusTrap {
55    pub group_id: u32,
56    pub return_focus: Option<FocusId>,
57}
58
59/// Focus changes [`FocusManager::focus_back`] can step back through.
60///
61/// Every recorded change adds an entry, so a long session tabbing between
62/// widgets grew the history without bound. Each graph repair also filters
63/// all of it. The oldest entry is dropped at the cap.
64const MAX_FOCUS_HISTORY: usize = 64;
65
66/// Central focus coordinator.
67///
68/// Tracks focus state, navigation history, focus traps (for modals),
69/// and focus indicator styling. Emits [`FocusEvent`]s on focus changes.
70#[derive(Debug)]
71pub struct FocusManager {
72    graph: FocusGraph,
73    current: Option<FocusId>,
74    host_focused: bool,
75    pending_focus_on_host_gain: Option<FocusId>,
76    history: Vec<FocusId>,
77    trap_stack: Vec<FocusTrap>,
78    groups: AHashMap<u32, FocusGroup>,
79    last_event: Option<FocusEvent>,
80    indicator: FocusIndicator,
81    /// Running count of focus changes for metrics.
82    focus_change_count: u64,
83}
84
85impl Default for FocusManager {
86    fn default() -> Self {
87        Self {
88            graph: FocusGraph::default(),
89            current: None,
90            host_focused: true,
91            pending_focus_on_host_gain: None,
92            history: Vec::new(),
93            trap_stack: Vec::new(),
94            groups: AHashMap::new(),
95            last_event: None,
96            indicator: FocusIndicator::default(),
97            focus_change_count: 0,
98        }
99    }
100}
101
102impl FocusManager {
103    /// Create a new focus manager.
104    #[must_use]
105    pub fn new() -> Self {
106        Self::default()
107    }
108
109    /// Access the underlying focus graph.
110    #[must_use]
111    pub fn graph(&self) -> &FocusGraph {
112        &self.graph
113    }
114
115    /// Mutably access the underlying focus graph.
116    pub fn graph_mut(&mut self) -> &mut FocusGraph {
117        &mut self.graph
118    }
119
120    /// Get currently focused widget.
121    #[inline]
122    #[must_use]
123    pub fn current(&self) -> Option<FocusId> {
124        self.current
125    }
126
127    #[must_use]
128    pub(crate) fn host_focused(&self) -> bool {
129        self.host_focused
130    }
131
132    pub(crate) fn set_host_focused(&mut self, focused: bool) {
133        self.host_focused = focused;
134        if focused {
135            self.pending_focus_on_host_gain = None;
136        }
137    }
138
139    /// Check if a widget is focused.
140    #[must_use]
141    pub fn is_focused(&self, id: FocusId) -> bool {
142        self.current == Some(id)
143    }
144
145    /// Set focus to widget, returns previous focus.
146    pub fn focus(&mut self, id: FocusId) -> Option<FocusId> {
147        if !self.can_focus(id) || !self.allowed_by_trap(id) {
148            return None;
149        }
150        let prev = self.active_focus_target();
151        if prev == Some(id) {
152            return prev;
153        }
154        self.set_focus(id);
155        prev
156    }
157
158    /// Remove focus from current widget.
159    pub fn blur(&mut self) -> Option<FocusId> {
160        let prev = self.current.take();
161        if let Some(id) = prev {
162            #[cfg(feature = "tracing")]
163            tracing::debug!(from_widget = id, trigger = "blur", "focus.change");
164            self.last_event = Some(FocusEvent::FocusLost { id });
165            self.focus_change_count += 1;
166        }
167        prev
168    }
169
170    /// Apply host/window focus state to the widget focus graph.
171    ///
172    /// Deterministic policy:
173    /// - `focused = false` clears current focus.
174    /// - `focused = true` restores the last valid logical focus target when
175    ///   possible, otherwise falls back to the first allowed node (respecting
176    ///   active traps).
177    ///
178    /// Returns `true` when focus state changed.
179    pub fn apply_host_focus(&mut self, focused: bool) -> bool {
180        if !focused {
181            if let Some(current) = self.current {
182                self.pending_focus_on_host_gain = Some(current);
183            }
184            self.host_focused = false;
185            return self.blur().is_some();
186        }
187
188        self.host_focused = true;
189        let had_current = self.current.is_some();
190        if let Some(current) = self.current
191            && self.can_focus(current)
192            && self.allowed_by_trap(current)
193        {
194            self.pending_focus_on_host_gain = None;
195            return false;
196        }
197
198        let pending_focus = self.pending_focus_on_host_gain.take();
199        if let Some(id) = pending_focus
200            && self.can_focus(id)
201            && self.allowed_by_trap(id)
202        {
203            return self.set_focus_without_history(id);
204        }
205
206        if let Some(group_id) = self.active_trap_group()
207            && self.focus_first_in_group_without_history(group_id)
208        {
209            return true;
210        }
211
212        if self.focus_first_without_history() {
213            return true;
214        }
215
216        if had_current {
217            return self.blur().is_some();
218        }
219
220        false
221    }
222
223    /// Move focus in direction.
224    pub fn navigate(&mut self, dir: NavDirection) -> bool {
225        match dir {
226            NavDirection::Next => self.focus_next(),
227            NavDirection::Prev => self.focus_prev(),
228            _ => {
229                let Some(current) = self.active_focus_target() else {
230                    return false;
231                };
232                // Explicit edges take precedence; fall back to spatial navigation.
233                let target = self
234                    .graph
235                    .navigate(current, dir)
236                    .or_else(|| spatial::spatial_navigate(&self.graph, current, dir));
237                let Some(target) = target else {
238                    return false;
239                };
240                if !self.allowed_by_trap(target) {
241                    return false;
242                }
243                self.set_focus(target)
244            }
245        }
246    }
247
248    /// Move to next in tab order.
249    pub fn focus_next(&mut self) -> bool {
250        self.move_in_tab_order(true)
251    }
252
253    /// Move to previous in tab order.
254    pub fn focus_prev(&mut self) -> bool {
255        self.move_in_tab_order(false)
256    }
257
258    /// Focus first focusable widget.
259    pub fn focus_first(&mut self) -> bool {
260        let order = self.active_tab_order();
261        let Some(first) = order.first().copied() else {
262            return false;
263        };
264        self.set_focus(first)
265    }
266
267    /// Focus last focusable widget.
268    pub fn focus_last(&mut self) -> bool {
269        let order = self.active_tab_order();
270        let Some(last) = order.last().copied() else {
271            return false;
272        };
273        self.set_focus(last)
274    }
275
276    /// Go back to previous focus.
277    pub fn focus_back(&mut self) -> bool {
278        let active_focus = self.active_focus_target();
279        while let Some(id) = self.history.pop() {
280            if active_focus == Some(id) {
281                continue;
282            }
283            if self.can_focus(id) && self.allowed_by_trap(id) {
284                if !self.host_focused {
285                    return self.set_pending_focus_target(id);
286                }
287                // Set focus directly without pushing current to history
288                // (going back shouldn't create a forward entry).
289                let prev = self.current;
290                self.current = Some(id);
291                self.last_event = Some(match prev {
292                    Some(from) => FocusEvent::FocusMoved { from, to: id },
293                    None => FocusEvent::FocusGained { id },
294                });
295                self.focus_change_count += 1;
296                return true;
297            }
298        }
299        false
300    }
301
302    /// Clear focus history.
303    pub fn clear_history(&mut self) {
304        self.history.clear();
305    }
306
307    /// Push focus trap (for modals).
308    ///
309    /// If the group doesn't exist or has no focusable members, the trap is
310    /// **not** pushed and the method returns `false`. This prevents a deadlock
311    /// where `allowed_by_trap` would deny focus to every widget because the
312    /// group is empty/missing.
313    pub fn push_trap(&mut self, group_id: u32) -> bool {
314        let return_focus = if self.host_focused {
315            self.current
316        } else {
317            self.current.or(self.deferred_focus_target())
318        };
319        if !self.push_trap_with_return_focus(group_id, return_focus) {
320            #[cfg(feature = "tracing")]
321            tracing::warn!(group_id, "focus.trap_push rejected: group missing or empty");
322            return false;
323        }
324
325        if self.host_focused && !self.is_current_focusable_in_group(group_id) {
326            self.focus_first_in_group_without_history(group_id);
327        } else if !self.host_focused {
328            self.pending_focus_on_host_gain = self.group_primary_focus_target(group_id);
329        }
330        true
331    }
332
333    /// Pop focus trap, restore previous focus.
334    pub fn pop_trap(&mut self) -> bool {
335        let Some(trap) = self.trap_stack.pop() else {
336            return false;
337        };
338        let had_current = self.current.is_some();
339        #[cfg(feature = "tracing")]
340        tracing::debug!(
341            group_id = trap.group_id,
342            return_focus = ?trap.return_focus,
343            "focus.trap_pop"
344        );
345
346        if !self.host_focused {
347            self.pending_focus_on_host_gain = trap
348                .return_focus
349                .filter(|id| self.can_focus(*id) && self.allowed_by_trap(*id))
350                .or_else(|| {
351                    self.active_trap_group()
352                        .and_then(|group_id| self.group_primary_focus_target(group_id))
353                });
354            return if had_current {
355                self.blur().is_some()
356            } else {
357                false
358            };
359        }
360
361        if let Some(id) = trap.return_focus
362            && self.can_focus(id)
363            && self.allowed_by_trap(id)
364        {
365            return self.set_focus_without_history(id);
366        }
367
368        if let Some(active) = self.active_trap_group() {
369            return self.focus_first_in_group_without_history(active);
370        }
371
372        if trap.return_focus.is_none() {
373            return if had_current {
374                self.blur().is_some()
375            } else {
376                false
377            };
378        }
379
380        if self.focus_first_without_history() {
381            return true;
382        }
383
384        if had_current && self.current.is_some_and(|id| !self.can_focus(id)) {
385            return self.blur().is_some();
386        }
387
388        false
389    }
390
391    /// Check if focus is currently trapped.
392    #[must_use]
393    pub fn is_trapped(&self) -> bool {
394        self.active_trap_group().is_some()
395    }
396
397    /// Remove all active focus traps without changing focus groups.
398    pub fn clear_traps(&mut self) {
399        self.trap_stack.clear();
400    }
401
402    /// Create focus group.
403    pub fn create_group(&mut self, id: u32, members: Vec<FocusId>) {
404        let members = self.filter_focusable(members);
405        self.groups.insert(id, FocusGroup::new(id, members));
406        self.repair_focus_after_group_change();
407    }
408
409    pub(crate) fn create_group_preserving_members(&mut self, id: u32, members: Vec<FocusId>) {
410        let members = self.dedup_members(members);
411        self.groups.insert(id, FocusGroup::new(id, members));
412        self.repair_focus_after_group_change();
413    }
414
415    /// Add widget to group.
416    pub fn add_to_group(&mut self, group_id: u32, widget_id: FocusId) {
417        if !self.can_focus(widget_id) {
418            return;
419        }
420        let group = self
421            .groups
422            .entry(group_id)
423            .or_insert_with(|| FocusGroup::new(group_id, Vec::new()));
424        if !group.contains(widget_id) {
425            group.members.push(widget_id);
426        }
427        self.repair_focus_after_group_change();
428    }
429
430    /// Remove widget from group.
431    pub fn remove_from_group(&mut self, group_id: u32, widget_id: FocusId) {
432        let Some(group) = self.groups.get_mut(&group_id) else {
433            return;
434        };
435        group.members.retain(|id| *id != widget_id);
436        self.repair_focus_after_group_change();
437    }
438
439    /// Remove an entire focus group.
440    pub fn remove_group(&mut self, group_id: u32) {
441        if self.groups.remove(&group_id).is_none() {
442            return;
443        }
444        self.trap_stack.retain(|trap| trap.group_id != group_id);
445        self.repair_focus_after_group_change();
446    }
447
448    /// Get the last focus event.
449    #[must_use]
450    pub fn focus_event(&self) -> Option<&FocusEvent> {
451        self.last_event.as_ref()
452    }
453
454    /// Take and clear the last focus event.
455    #[must_use]
456    pub fn take_focus_event(&mut self) -> Option<FocusEvent> {
457        self.last_event.take()
458    }
459
460    /// Get the focus indicator configuration.
461    #[inline]
462    #[must_use]
463    pub fn indicator(&self) -> &FocusIndicator {
464        &self.indicator
465    }
466
467    /// Set the focus indicator configuration.
468    pub fn set_indicator(&mut self, indicator: FocusIndicator) {
469        self.indicator = indicator;
470    }
471
472    /// Total number of focus changes since creation (for metrics).
473    #[inline]
474    #[must_use]
475    pub fn focus_change_count(&self) -> u64 {
476        self.focus_change_count
477    }
478
479    #[cfg(test)]
480    #[must_use]
481    pub(crate) fn group_count(&self) -> usize {
482        self.groups.len()
483    }
484
485    #[must_use]
486    pub(crate) fn has_group(&self, group_id: u32) -> bool {
487        self.groups.contains_key(&group_id)
488    }
489
490    #[must_use]
491    pub(crate) fn group_members(&self, group_id: u32) -> Vec<FocusId> {
492        self.groups
493            .get(&group_id)
494            .map(|group| group.members.clone())
495            .unwrap_or_default()
496    }
497
498    #[cfg(test)]
499    #[must_use]
500    pub(crate) fn base_trap_return_focus(&self) -> Option<Option<FocusId>> {
501        self.trap_stack.first().map(|trap| trap.return_focus)
502    }
503
504    #[must_use]
505    pub(crate) fn deferred_focus_target(&self) -> Option<FocusId> {
506        if let Some(id) = self.active_focus_target() {
507            return Some(id);
508        }
509
510        self.active_trap_group()
511            .and_then(|group_id| self.group_primary_focus_target(group_id))
512    }
513
514    #[must_use]
515    pub(crate) fn logical_focus_target(&self) -> Option<FocusId> {
516        self.active_focus_target()
517    }
518
519    pub(crate) fn focus_without_history(&mut self, id: FocusId) -> bool {
520        self.set_focus_without_history(id)
521    }
522
523    pub(crate) fn focus_first_without_history_for_restore(&mut self) -> bool {
524        self.focus_first_without_history()
525    }
526
527    pub(crate) fn replace_deferred_focus_target(&mut self, target: Option<FocusId>) {
528        self.current = None;
529        self.pending_focus_on_host_gain =
530            target.filter(|id| self.can_focus(*id) && self.allowed_by_trap(*id));
531    }
532
533    pub(crate) fn remove_group_without_repair(&mut self, group_id: u32) -> bool {
534        if self.groups.remove(&group_id).is_none() {
535            return false;
536        }
537        self.trap_stack.retain(|trap| trap.group_id != group_id);
538        true
539    }
540
541    pub(crate) fn push_trap_with_return_focus(
542        &mut self,
543        group_id: u32,
544        return_focus: Option<FocusId>,
545    ) -> bool {
546        if !self.group_has_focusable_member(group_id) {
547            return false;
548        }
549
550        #[cfg(feature = "tracing")]
551        tracing::debug!(
552            group_id,
553            return_focus = ?return_focus,
554            "focus.trap_push"
555        );
556        self.trap_stack.push(FocusTrap {
557            group_id,
558            return_focus,
559        });
560        true
561    }
562
563    pub(crate) fn repair_focus_after_excluding_ids(&mut self, excluded: &[FocusId]) {
564        self.history.retain(|id| !excluded.contains(id));
565
566        if !self.host_focused {
567            if self.current.is_some_and(|id| excluded.contains(&id)) {
568                let _ = self.blur();
569            }
570            return;
571        }
572
573        if self.is_trapped() || !self.current.is_some_and(|id| excluded.contains(&id)) {
574            return;
575        }
576
577        for id in self.graph.tab_order() {
578            if excluded.contains(&id) {
579                continue;
580            }
581            if self.set_focus_without_history(id) {
582                return;
583            }
584        }
585
586        let _ = self.blur();
587    }
588
589    pub(crate) fn clear_deferred_focus_if_excluded(&mut self, excluded: &[FocusId]) {
590        if self
591            .pending_focus_on_host_gain
592            .is_some_and(|id| excluded.contains(&id))
593        {
594            self.pending_focus_on_host_gain = None;
595        }
596    }
597
598    pub(crate) fn restore_focus_after_invalid_current(&mut self) {
599        if !self.host_focused {
600            return;
601        }
602
603        if let Some(group_id) = self.active_trap_group()
604            && self.focus_first_in_group_without_history(group_id)
605        {
606            return;
607        }
608
609        let _ = self.focus_first_without_history();
610    }
611
612    fn set_focus(&mut self, id: FocusId) -> bool {
613        self.set_focus_target(id, true)
614    }
615
616    fn set_focus_without_history(&mut self, id: FocusId) -> bool {
617        self.set_focus_target(id, false)
618    }
619
620    fn set_focus_target(&mut self, id: FocusId, record_history: bool) -> bool {
621        if !self.host_focused {
622            return self.set_pending_focus_target(id);
623        }
624        self.set_focus_internal(id, record_history)
625    }
626
627    fn set_focus_internal(&mut self, id: FocusId, record_history: bool) -> bool {
628        if !self.can_focus(id) || !self.allowed_by_trap(id) {
629            return false;
630        }
631        if self.current == Some(id) {
632            return false;
633        }
634
635        let prev = self.current;
636        if let Some(prev_id) = prev {
637            if record_history && Some(prev_id) != self.history.last().copied() {
638                if self.history.len() >= MAX_FOCUS_HISTORY {
639                    self.history.remove(0);
640                }
641                self.history.push(prev_id);
642            }
643            let event = FocusEvent::FocusMoved {
644                from: prev_id,
645                to: id,
646            };
647            #[cfg(feature = "tracing")]
648            tracing::debug!(
649                from_widget = prev_id,
650                to_widget = id,
651                trigger = "navigate",
652                "focus.change"
653            );
654            self.last_event = Some(event);
655        } else {
656            #[cfg(feature = "tracing")]
657            tracing::debug!(to_widget = id, trigger = "initial", "focus.change");
658            self.last_event = Some(FocusEvent::FocusGained { id });
659        }
660
661        self.current = Some(id);
662        self.focus_change_count += 1;
663        true
664    }
665
666    fn can_focus(&self, id: FocusId) -> bool {
667        self.graph.get(id).map(|n| n.is_focusable).unwrap_or(false)
668    }
669
670    fn active_focus_target(&self) -> Option<FocusId> {
671        if let Some(current) = self.current
672            && self.can_focus(current)
673            && self.allowed_by_trap(current)
674        {
675            return Some(current);
676        }
677
678        if self.host_focused {
679            return None;
680        }
681
682        self.pending_focus_on_host_gain
683            .filter(|id| self.can_focus(*id) && self.allowed_by_trap(*id))
684    }
685
686    fn set_pending_focus_target(&mut self, id: FocusId) -> bool {
687        if !self.can_focus(id) || !self.allowed_by_trap(id) {
688            return false;
689        }
690
691        let prev = self.active_focus_target();
692        self.current = None;
693        if prev == Some(id) {
694            return false;
695        }
696
697        self.pending_focus_on_host_gain = Some(id);
698        true
699    }
700
701    fn active_trap_group(&self) -> Option<u32> {
702        self.trap_stack
703            .iter()
704            .rev()
705            .find(|trap| self.group_has_focusable_member(trap.group_id))
706            .map(|trap| trap.group_id)
707    }
708
709    fn allowed_by_trap(&self, id: FocusId) -> bool {
710        let Some(group_id) = self.active_trap_group() else {
711            return true;
712        };
713        self.groups
714            .get(&group_id)
715            .map(|g| g.contains(id))
716            .unwrap_or(false)
717    }
718
719    fn group_has_focusable_member(&self, group_id: u32) -> bool {
720        self.groups
721            .get(&group_id)
722            .is_some_and(|group| group.members.iter().any(|id| self.can_focus(*id)))
723    }
724
725    fn repair_focus_after_group_change(&mut self) {
726        if !self.host_focused {
727            if self.current.is_some() {
728                let _ = self.blur();
729            }
730            return;
731        }
732
733        match self.active_trap_group() {
734            Some(group_id) => {
735                let current_allowed = self
736                    .current
737                    .is_some_and(|id| self.can_focus(id) && self.allowed_by_trap(id));
738                if !current_allowed {
739                    let _ = self.focus_first_in_group_without_history(group_id);
740                }
741            }
742            None => {
743                if self.current.is_some_and(|id| !self.can_focus(id))
744                    && !self.focus_first_without_history()
745                {
746                    let _ = self.blur();
747                }
748            }
749        }
750    }
751
752    fn is_current_focusable_in_group(&self, group_id: u32) -> bool {
753        let Some(current) = self.current else {
754            return false;
755        };
756        self.can_focus(current)
757            && self
758                .groups
759                .get(&group_id)
760                .map(|g| g.contains(current))
761                .unwrap_or(false)
762    }
763
764    fn active_tab_order(&self) -> Vec<FocusId> {
765        if let Some(group_id) = self.active_trap_group() {
766            return self.group_tab_order(group_id);
767        }
768        self.graph.tab_order()
769    }
770
771    fn group_tab_order(&self, group_id: u32) -> Vec<FocusId> {
772        let Some(group) = self.groups.get(&group_id) else {
773            return Vec::new();
774        };
775        let order = self.graph.tab_order();
776        order.into_iter().filter(|id| group.contains(*id)).collect()
777    }
778
779    pub(crate) fn group_primary_focus_target(&self, group_id: u32) -> Option<FocusId> {
780        self.group_tab_order(group_id).first().copied().or_else(|| {
781            self.groups
782                .get(&group_id)
783                .and_then(|group| group.members.iter().copied().find(|id| self.can_focus(*id)))
784        })
785    }
786
787    fn focus_first_in_group_without_history(&mut self, group_id: u32) -> bool {
788        let Some(first) = self.group_primary_focus_target(group_id) else {
789            return false;
790        };
791        self.set_focus_without_history(first)
792    }
793
794    fn focus_first_without_history(&mut self) -> bool {
795        let order = self.active_tab_order();
796        let Some(first) = order.first().copied() else {
797            return false;
798        };
799        self.set_focus_without_history(first)
800    }
801
802    fn move_in_tab_order(&mut self, forward: bool) -> bool {
803        let order = self.active_tab_order();
804        if order.is_empty() {
805            return false;
806        }
807        let first = order[0];
808        let last = order[order.len() - 1];
809        let fallback = if forward { first } else { last };
810
811        let wrap = self
812            .active_trap_group()
813            .and_then(|id| self.groups.get(&id).map(|g| g.wrap))
814            .unwrap_or(true);
815
816        let next = match self.active_focus_target() {
817            None => fallback,
818            Some(current) => {
819                let pos = order.iter().position(|id| *id == current);
820                match pos {
821                    None => fallback,
822                    Some(idx) if forward => {
823                        if idx + 1 < order.len() {
824                            order[idx + 1]
825                        } else if wrap {
826                            order[0]
827                        } else {
828                            return false;
829                        }
830                    }
831                    Some(idx) => {
832                        if idx > 0 {
833                            order[idx - 1]
834                        } else if wrap {
835                            last
836                        } else {
837                            return false;
838                        }
839                    }
840                }
841            }
842        };
843
844        self.set_focus(next)
845    }
846
847    fn dedup_members(&self, ids: Vec<FocusId>) -> Vec<FocusId> {
848        let mut out = Vec::new();
849        for id in ids {
850            if !out.contains(&id) {
851                out.push(id);
852            }
853        }
854        out
855    }
856
857    fn filter_focusable(&self, ids: Vec<FocusId>) -> Vec<FocusId> {
858        self.dedup_members(ids)
859            .into_iter()
860            .filter(|id| self.can_focus(*id))
861            .collect()
862    }
863}
864
865// =========================================================================
866// Tests
867// =========================================================================
868
869#[cfg(test)]
870mod tests {
871    use super::*;
872    use crate::focus::FocusNode;
873    use ftui_core::geometry::Rect;
874
875    fn node(id: FocusId, tab: i32) -> FocusNode {
876        FocusNode::new(id, Rect::new(0, 0, 1, 1)).with_tab_index(tab)
877    }
878
879    #[test]
880    fn focus_basic() {
881        let mut fm = FocusManager::new();
882        fm.graph_mut().insert(node(1, 0));
883        fm.graph_mut().insert(node(2, 1));
884
885        assert!(fm.focus(1).is_none());
886        assert_eq!(fm.current(), Some(1));
887
888        assert_eq!(fm.focus(2), Some(1));
889        assert_eq!(fm.current(), Some(2));
890
891        assert_eq!(fm.blur(), Some(2));
892        assert_eq!(fm.current(), None);
893    }
894
895    #[test]
896    fn focus_history_back() {
897        let mut fm = FocusManager::new();
898        fm.graph_mut().insert(node(1, 0));
899        fm.graph_mut().insert(node(2, 1));
900        fm.graph_mut().insert(node(3, 2));
901
902        fm.focus(1);
903        fm.focus(2);
904        fm.focus(3);
905
906        assert!(fm.focus_back());
907        assert_eq!(fm.current(), Some(2));
908
909        assert!(fm.focus_back());
910        assert_eq!(fm.current(), Some(1));
911    }
912
913    #[test]
914    fn focus_history_is_bounded_and_keeps_the_newest_entries() {
915        let mut fm = FocusManager::new();
916        fm.graph_mut().insert(node(1, 0));
917        fm.graph_mut().insert(node(2, 1));
918        fm.graph_mut().insert(node(3, 2));
919
920        for _ in 0..10_000 {
921            fm.focus(1);
922            fm.focus(2);
923        }
924        assert_eq!(fm.history.len(), MAX_FOCUS_HISTORY);
925
926        fm.focus(3);
927        assert!(fm.focus_back());
928        assert_eq!(fm.current(), Some(2));
929    }
930
931    #[test]
932    fn focus_back_skips_current_id_in_history() {
933        let mut fm = FocusManager::new();
934        fm.graph_mut().insert(node(1, 0));
935        fm.graph_mut().insert(node(2, 1));
936
937        fm.focus(1);
938        fm.focus(2);
939        assert_eq!(fm.current(), Some(2));
940
941        assert_eq!(fm.blur(), Some(2));
942        assert_eq!(fm.current(), None);
943
944        fm.focus(1);
945        assert_eq!(fm.current(), Some(1));
946        let _ = fm.take_focus_event();
947        let before = fm.focus_change_count();
948
949        assert!(!fm.focus_back());
950        assert_eq!(fm.current(), Some(1));
951        assert!(fm.take_focus_event().is_none());
952        assert_eq!(fm.focus_change_count(), before);
953    }
954
955    #[test]
956    fn focus_next_prev() {
957        let mut fm = FocusManager::new();
958        fm.graph_mut().insert(node(1, 0));
959        fm.graph_mut().insert(node(2, 1));
960        fm.graph_mut().insert(node(3, 2));
961
962        assert!(fm.focus_next());
963        assert_eq!(fm.current(), Some(1));
964
965        assert!(fm.focus_next());
966        assert_eq!(fm.current(), Some(2));
967
968        assert!(fm.focus_prev());
969        assert_eq!(fm.current(), Some(1));
970    }
971
972    #[test]
973    fn apply_host_focus_loss_blurs_current() {
974        let mut fm = FocusManager::new();
975        fm.graph_mut().insert(node(1, 0));
976        fm.focus(1);
977        let _ = fm.take_focus_event();
978
979        assert!(fm.apply_host_focus(false));
980        assert_eq!(fm.current(), None);
981        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
982    }
983
984    #[test]
985    fn apply_host_focus_gain_focuses_first_when_unfocused() {
986        let mut fm = FocusManager::new();
987        fm.graph_mut().insert(node(10, 1));
988        fm.graph_mut().insert(node(5, 0));
989
990        assert!(fm.apply_host_focus(true));
991        assert_eq!(fm.current(), Some(5));
992        assert_eq!(
993            fm.take_focus_event(),
994            Some(FocusEvent::FocusGained { id: 5 })
995        );
996    }
997
998    #[test]
999    fn apply_host_focus_gain_preserves_valid_current() {
1000        let mut fm = FocusManager::new();
1001        fm.graph_mut().insert(node(1, 0));
1002        fm.graph_mut().insert(node(2, 1));
1003        fm.focus(2);
1004        let _ = fm.take_focus_event();
1005
1006        assert!(!fm.apply_host_focus(true));
1007        assert_eq!(fm.current(), Some(2));
1008        assert!(fm.take_focus_event().is_none());
1009    }
1010
1011    #[test]
1012    fn apply_host_focus_gain_clears_invalid_current_when_restore_fails() {
1013        let mut fm = FocusManager::new();
1014        fm.graph_mut().insert(node(1, 0));
1015        fm.focus(1);
1016        let _ = fm.take_focus_event();
1017        let _ = fm.graph_mut().remove(1);
1018
1019        assert!(fm.apply_host_focus(true));
1020        assert_eq!(fm.current(), None);
1021        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1022    }
1023
1024    #[test]
1025    fn apply_host_focus_gain_respects_trap_order() {
1026        let mut fm = FocusManager::new();
1027        fm.graph_mut().insert(node(1, 0));
1028        fm.graph_mut().insert(node(2, 1));
1029        fm.graph_mut().insert(node(3, 2));
1030        fm.create_group(42, vec![2, 3]);
1031        fm.push_trap(42);
1032        let _ = fm.take_focus_event();
1033        fm.blur();
1034        let _ = fm.take_focus_event();
1035
1036        assert!(fm.apply_host_focus(true));
1037        assert_eq!(fm.current(), Some(2));
1038    }
1039
1040    #[test]
1041    fn apply_host_focus_gain_restores_previously_selected_trapped_focus() {
1042        let mut fm = FocusManager::new();
1043        fm.graph_mut().insert(node(1, 0));
1044        fm.graph_mut().insert(node(2, 1));
1045        fm.graph_mut().insert(node(3, 2));
1046        fm.create_group(42, vec![2, 3]);
1047        assert!(fm.push_trap(42));
1048        assert_eq!(fm.current(), Some(2));
1049        assert_eq!(fm.focus(3), Some(2));
1050        let _ = fm.take_focus_event();
1051
1052        assert!(fm.apply_host_focus(false));
1053        assert_eq!(fm.current(), None);
1054        let _ = fm.take_focus_event();
1055
1056        assert!(fm.apply_host_focus(true));
1057        assert_eq!(fm.current(), Some(3));
1058        assert_eq!(
1059            fm.take_focus_event(),
1060            Some(FocusEvent::FocusGained { id: 3 })
1061        );
1062    }
1063
1064    #[test]
1065    fn push_trap_while_host_blurred_without_prior_focus_restores_none_on_pop() {
1066        let mut fm = FocusManager::new();
1067        fm.graph_mut().insert(node(1, 0));
1068        fm.graph_mut().insert(node(2, 1));
1069        assert!(!fm.apply_host_focus(false));
1070
1071        fm.create_group(42, vec![2]);
1072        assert!(fm.push_trap(42));
1073        assert!(fm.apply_host_focus(true));
1074        assert_eq!(fm.current(), Some(2));
1075
1076        assert!(fm.pop_trap());
1077        assert_eq!(fm.current(), None);
1078        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 2 }));
1079    }
1080
1081    #[test]
1082    fn push_trap_does_not_autofocus_while_host_blurred() {
1083        let mut fm = FocusManager::new();
1084        fm.graph_mut().insert(node(1, 0));
1085        fm.graph_mut().insert(node(2, 1));
1086        fm.focus(1);
1087        assert!(fm.apply_host_focus(false));
1088
1089        fm.create_group(42, vec![2]);
1090        assert!(fm.push_trap(42));
1091        assert_eq!(fm.current(), None);
1092
1093        assert!(fm.apply_host_focus(true));
1094        assert_eq!(fm.current(), Some(2));
1095    }
1096
1097    #[test]
1098    fn focus_while_host_blurred_updates_deferred_target_without_restoring_current() {
1099        let mut fm = FocusManager::new();
1100        fm.graph_mut().insert(node(1, 0));
1101        fm.graph_mut().insert(node(2, 1));
1102        fm.graph_mut().insert(node(3, 2));
1103        fm.focus(1);
1104        let _ = fm.take_focus_event();
1105
1106        assert!(fm.apply_host_focus(false));
1107        assert_eq!(fm.current(), None);
1108        assert_eq!(fm.focus(3), Some(1));
1109        assert_eq!(fm.current(), None);
1110        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1111
1112        assert!(fm.apply_host_focus(true));
1113        assert_eq!(fm.current(), Some(3));
1114        assert_eq!(
1115            fm.take_focus_event(),
1116            Some(FocusEvent::FocusGained { id: 3 })
1117        );
1118    }
1119
1120    #[test]
1121    fn focus_next_while_host_blurred_advances_deferred_target() {
1122        let mut fm = FocusManager::new();
1123        fm.graph_mut().insert(node(1, 0));
1124        fm.graph_mut().insert(node(2, 1));
1125        fm.graph_mut().insert(node(3, 2));
1126        fm.focus(1);
1127        assert_eq!(fm.focus(2), Some(1));
1128        let _ = fm.take_focus_event();
1129
1130        assert!(fm.apply_host_focus(false));
1131        assert_eq!(fm.current(), None);
1132        assert!(fm.focus_next());
1133        assert_eq!(fm.current(), None);
1134        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 2 }));
1135
1136        assert!(fm.apply_host_focus(true));
1137        assert_eq!(fm.current(), Some(3));
1138        assert_eq!(
1139            fm.take_focus_event(),
1140            Some(FocusEvent::FocusGained { id: 3 })
1141        );
1142    }
1143
1144    #[test]
1145    fn focus_trap_push_pop() {
1146        let mut fm = FocusManager::new();
1147        fm.graph_mut().insert(node(1, 0));
1148        fm.graph_mut().insert(node(2, 1));
1149        fm.graph_mut().insert(node(3, 2));
1150
1151        fm.focus(3);
1152        fm.create_group(7, vec![1, 2]);
1153
1154        fm.push_trap(7);
1155        assert!(fm.is_trapped());
1156        assert_eq!(fm.current(), Some(1));
1157
1158        fm.pop_trap();
1159        assert!(!fm.is_trapped());
1160        assert_eq!(fm.current(), Some(3));
1161    }
1162
1163    #[test]
1164    fn focus_group_wrap_respected() {
1165        let mut fm = FocusManager::new();
1166        fm.graph_mut().insert(node(1, 0));
1167        fm.graph_mut().insert(node(2, 1));
1168        fm.create_group(9, vec![1, 2]);
1169        fm.groups.get_mut(&9).unwrap().wrap = false;
1170
1171        fm.push_trap(9);
1172        fm.focus(2);
1173        assert!(!fm.focus_next());
1174        assert_eq!(fm.current(), Some(2));
1175    }
1176
1177    #[test]
1178    fn focus_event_generation() {
1179        let mut fm = FocusManager::new();
1180        fm.graph_mut().insert(node(1, 0));
1181        fm.graph_mut().insert(node(2, 1));
1182
1183        fm.focus(1);
1184        assert_eq!(
1185            fm.take_focus_event(),
1186            Some(FocusEvent::FocusGained { id: 1 })
1187        );
1188
1189        fm.focus(2);
1190        assert_eq!(
1191            fm.take_focus_event(),
1192            Some(FocusEvent::FocusMoved { from: 1, to: 2 })
1193        );
1194
1195        fm.blur();
1196        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 2 }));
1197    }
1198
1199    #[test]
1200    fn trap_prevents_focus_outside_group() {
1201        let mut fm = FocusManager::new();
1202        fm.graph_mut().insert(node(1, 0));
1203        fm.graph_mut().insert(node(2, 1));
1204        fm.graph_mut().insert(node(3, 2));
1205        fm.create_group(5, vec![1, 2]);
1206
1207        fm.push_trap(5);
1208        assert_eq!(fm.current(), Some(1));
1209
1210        // Attempt to focus outside trap should fail.
1211        assert!(fm.focus(3).is_none());
1212        assert_ne!(fm.current(), Some(3));
1213    }
1214
1215    // --- Spatial navigation integration ---
1216
1217    fn spatial_node(id: FocusId, x: u16, y: u16, w: u16, h: u16, tab: i32) -> FocusNode {
1218        FocusNode::new(id, Rect::new(x, y, w, h)).with_tab_index(tab)
1219    }
1220
1221    #[test]
1222    fn navigate_spatial_fallback() {
1223        let mut fm = FocusManager::new();
1224        // Two nodes side by side — no explicit edges.
1225        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1226        fm.graph_mut().insert(spatial_node(2, 20, 0, 10, 3, 1));
1227
1228        fm.focus(1);
1229        assert!(fm.navigate(NavDirection::Right));
1230        assert_eq!(fm.current(), Some(2));
1231
1232        assert!(fm.navigate(NavDirection::Left));
1233        assert_eq!(fm.current(), Some(1));
1234    }
1235
1236    #[test]
1237    fn navigate_explicit_edge_overrides_spatial() {
1238        let mut fm = FocusManager::new();
1239        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1240        fm.graph_mut().insert(spatial_node(2, 20, 0, 10, 3, 1)); // spatially right
1241        fm.graph_mut().insert(spatial_node(3, 40, 0, 10, 3, 2)); // further right
1242
1243        // Explicit edge overrides spatial: Right from 1 goes to 3, not 2.
1244        fm.graph_mut().connect(1, NavDirection::Right, 3);
1245
1246        fm.focus(1);
1247        assert!(fm.navigate(NavDirection::Right));
1248        assert_eq!(fm.current(), Some(3));
1249    }
1250
1251    #[test]
1252    fn navigate_spatial_respects_trap() {
1253        let mut fm = FocusManager::new();
1254        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1255        fm.graph_mut().insert(spatial_node(2, 20, 0, 10, 3, 1));
1256        fm.graph_mut().insert(spatial_node(3, 40, 0, 10, 3, 2));
1257
1258        // Trap to group containing only 1 and 2.
1259        fm.create_group(1, vec![1, 2]);
1260        fm.focus(2);
1261        fm.push_trap(1);
1262
1263        // Spatial would find 3 to the right of 2, but trap blocks it.
1264        assert!(!fm.navigate(NavDirection::Right));
1265        assert_eq!(fm.current(), Some(2));
1266    }
1267
1268    #[test]
1269    fn navigate_spatial_grid_round_trip() {
1270        let mut fm = FocusManager::new();
1271        // 2x2 grid.
1272        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1273        fm.graph_mut().insert(spatial_node(2, 20, 0, 10, 3, 1));
1274        fm.graph_mut().insert(spatial_node(3, 0, 6, 10, 3, 2));
1275        fm.graph_mut().insert(spatial_node(4, 20, 6, 10, 3, 3));
1276
1277        fm.focus(1);
1278
1279        // Navigate around the grid: right, down, left, up — back to start.
1280        assert!(fm.navigate(NavDirection::Right));
1281        assert_eq!(fm.current(), Some(2));
1282
1283        assert!(fm.navigate(NavDirection::Down));
1284        assert_eq!(fm.current(), Some(4));
1285
1286        assert!(fm.navigate(NavDirection::Left));
1287        assert_eq!(fm.current(), Some(3));
1288
1289        assert!(fm.navigate(NavDirection::Up));
1290        assert_eq!(fm.current(), Some(1));
1291    }
1292
1293    #[test]
1294    fn navigate_spatial_no_candidate() {
1295        let mut fm = FocusManager::new();
1296        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1297        fm.focus(1);
1298
1299        // No other nodes, spatial should return false.
1300        assert!(!fm.navigate(NavDirection::Right));
1301        assert!(!fm.navigate(NavDirection::Up));
1302        assert_eq!(fm.current(), Some(1));
1303    }
1304
1305    // --- FocusManager construction ---
1306
1307    #[test]
1308    fn new_manager_has_no_focus() {
1309        let fm = FocusManager::new();
1310        assert_eq!(fm.current(), None);
1311        assert!(!fm.is_trapped());
1312    }
1313
1314    #[test]
1315    fn default_and_new_are_equivalent() {
1316        let a = FocusManager::new();
1317        let b = FocusManager::default();
1318        assert_eq!(a.current(), b.current());
1319        assert_eq!(a.is_trapped(), b.is_trapped());
1320        assert_eq!(a.host_focused(), b.host_focused());
1321    }
1322
1323    // --- is_focused ---
1324
1325    #[test]
1326    fn is_focused_returns_true_for_current() {
1327        let mut fm = FocusManager::new();
1328        fm.graph_mut().insert(node(1, 0));
1329        fm.focus(1);
1330        assert!(fm.is_focused(1));
1331        assert!(!fm.is_focused(2));
1332    }
1333
1334    #[test]
1335    fn is_focused_returns_false_when_no_focus() {
1336        let fm = FocusManager::new();
1337        assert!(!fm.is_focused(1));
1338    }
1339
1340    // --- focus edge cases ---
1341
1342    #[test]
1343    fn focus_non_existent_node_returns_none() {
1344        let mut fm = FocusManager::new();
1345        assert!(fm.focus(999).is_none());
1346        assert_eq!(fm.current(), None);
1347    }
1348
1349    #[test]
1350    fn focus_already_focused_returns_same_id() {
1351        let mut fm = FocusManager::new();
1352        fm.graph_mut().insert(node(1, 0));
1353        fm.focus(1);
1354        // Focusing same node returns current (early exit)
1355        assert_eq!(fm.focus(1), Some(1));
1356        assert_eq!(fm.current(), Some(1));
1357    }
1358
1359    // --- blur ---
1360
1361    #[test]
1362    fn blur_when_no_focus_returns_none() {
1363        let mut fm = FocusManager::new();
1364        assert_eq!(fm.blur(), None);
1365    }
1366
1367    #[test]
1368    fn blur_generates_focus_lost_event() {
1369        let mut fm = FocusManager::new();
1370        fm.graph_mut().insert(node(1, 0));
1371        fm.focus(1);
1372        let _ = fm.take_focus_event(); // clear
1373        fm.blur();
1374        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1375    }
1376
1377    // --- focus_first / focus_last ---
1378
1379    #[test]
1380    fn focus_first_selects_lowest_tab_index() {
1381        let mut fm = FocusManager::new();
1382        fm.graph_mut().insert(node(3, 2));
1383        fm.graph_mut().insert(node(1, 0));
1384        fm.graph_mut().insert(node(2, 1));
1385
1386        assert!(fm.focus_first());
1387        assert_eq!(fm.current(), Some(1));
1388    }
1389
1390    #[test]
1391    fn focus_last_selects_highest_tab_index() {
1392        let mut fm = FocusManager::new();
1393        fm.graph_mut().insert(node(1, 0));
1394        fm.graph_mut().insert(node(2, 1));
1395        fm.graph_mut().insert(node(3, 2));
1396
1397        assert!(fm.focus_last());
1398        assert_eq!(fm.current(), Some(3));
1399    }
1400
1401    #[test]
1402    fn focus_first_on_empty_graph_returns_false() {
1403        let mut fm = FocusManager::new();
1404        assert!(!fm.focus_first());
1405    }
1406
1407    #[test]
1408    fn focus_last_on_empty_graph_returns_false() {
1409        let mut fm = FocusManager::new();
1410        assert!(!fm.focus_last());
1411    }
1412
1413    // --- Tab wrapping ---
1414
1415    #[test]
1416    fn focus_next_wraps_at_end() {
1417        let mut fm = FocusManager::new();
1418        fm.graph_mut().insert(node(1, 0));
1419        fm.graph_mut().insert(node(2, 1));
1420
1421        fm.focus(2);
1422        assert!(fm.focus_next()); // wraps
1423        assert_eq!(fm.current(), Some(1));
1424    }
1425
1426    #[test]
1427    fn focus_prev_wraps_at_start() {
1428        let mut fm = FocusManager::new();
1429        fm.graph_mut().insert(node(1, 0));
1430        fm.graph_mut().insert(node(2, 1));
1431
1432        fm.focus(1);
1433        assert!(fm.focus_prev()); // wraps
1434        assert_eq!(fm.current(), Some(2));
1435    }
1436
1437    #[test]
1438    fn focus_next_with_no_current_selects_first() {
1439        let mut fm = FocusManager::new();
1440        fm.graph_mut().insert(node(1, 0));
1441        fm.graph_mut().insert(node(2, 1));
1442
1443        assert!(fm.focus_next());
1444        assert_eq!(fm.current(), Some(1));
1445    }
1446
1447    #[test]
1448    fn focus_prev_with_no_current_selects_last() {
1449        let mut fm = FocusManager::new();
1450        fm.graph_mut().insert(node(1, 0));
1451        fm.graph_mut().insert(node(2, 1));
1452
1453        assert!(fm.focus_prev());
1454        assert_eq!(fm.current(), Some(2));
1455    }
1456
1457    #[test]
1458    fn focus_prev_with_stale_current_selects_last() {
1459        let mut fm = FocusManager::new();
1460        fm.graph_mut().insert(node(1, 0));
1461        fm.graph_mut().insert(node(2, 1));
1462        fm.graph_mut().insert(node(3, 2));
1463
1464        fm.focus(2);
1465        let _ = fm.graph_mut().remove(2);
1466
1467        assert!(fm.focus_prev());
1468        assert_eq!(fm.current(), Some(3));
1469    }
1470
1471    #[test]
1472    fn focus_next_on_empty_returns_false() {
1473        let mut fm = FocusManager::new();
1474        assert!(!fm.focus_next());
1475    }
1476
1477    // --- History ---
1478
1479    #[test]
1480    fn focus_back_on_empty_history_returns_false() {
1481        let mut fm = FocusManager::new();
1482        fm.graph_mut().insert(node(1, 0));
1483        fm.focus(1);
1484        assert!(!fm.focus_back());
1485    }
1486
1487    #[test]
1488    fn clear_history_prevents_back() {
1489        let mut fm = FocusManager::new();
1490        fm.graph_mut().insert(node(1, 0));
1491        fm.graph_mut().insert(node(2, 1));
1492
1493        fm.focus(1);
1494        fm.focus(2);
1495        fm.clear_history();
1496        assert!(!fm.focus_back());
1497        assert_eq!(fm.current(), Some(2));
1498    }
1499
1500    #[test]
1501    fn focus_back_skips_removed_nodes() {
1502        let mut fm = FocusManager::new();
1503        fm.graph_mut().insert(node(1, 0));
1504        fm.graph_mut().insert(node(2, 1));
1505        fm.graph_mut().insert(node(3, 2));
1506
1507        fm.focus(1);
1508        fm.focus(2);
1509        fm.focus(3);
1510
1511        // Remove node 2 from graph
1512        let _ = fm.graph_mut().remove(2);
1513
1514        // focus_back should skip 2 and go to 1
1515        assert!(fm.focus_back());
1516        assert_eq!(fm.current(), Some(1));
1517    }
1518
1519    // --- Groups ---
1520
1521    #[test]
1522    fn create_group_filters_non_focusable() {
1523        let mut fm = FocusManager::new();
1524        fm.graph_mut().insert(node(1, 0));
1525        // Node 999 doesn't exist in the graph
1526        fm.create_group(1, vec![1, 999]);
1527
1528        let group = fm.groups.get(&1).unwrap();
1529        assert_eq!(group.members.len(), 1);
1530        assert!(group.contains(1));
1531    }
1532
1533    #[test]
1534    fn add_to_group_creates_group_if_needed() {
1535        let mut fm = FocusManager::new();
1536        fm.graph_mut().insert(node(1, 0));
1537        fm.add_to_group(42, 1);
1538        assert!(fm.groups.contains_key(&42));
1539        assert!(fm.groups.get(&42).unwrap().contains(1));
1540    }
1541
1542    #[test]
1543    fn add_to_group_skips_unfocusable() {
1544        let mut fm = FocusManager::new();
1545        fm.add_to_group(1, 999); // 999 not in graph
1546        // Group may or may not exist, but if it does, 999 is not in it
1547        if let Some(group) = fm.groups.get(&1) {
1548            assert!(!group.contains(999));
1549        }
1550    }
1551
1552    #[test]
1553    fn add_to_group_no_duplicates() {
1554        let mut fm = FocusManager::new();
1555        fm.graph_mut().insert(node(1, 0));
1556        fm.add_to_group(1, 1);
1557        fm.add_to_group(1, 1);
1558        assert_eq!(fm.groups.get(&1).unwrap().members.len(), 1);
1559    }
1560
1561    #[test]
1562    fn remove_from_group() {
1563        let mut fm = FocusManager::new();
1564        fm.graph_mut().insert(node(1, 0));
1565        fm.graph_mut().insert(node(2, 1));
1566        fm.create_group(1, vec![1, 2]);
1567        fm.remove_from_group(1, 1);
1568        assert!(!fm.groups.get(&1).unwrap().contains(1));
1569        assert!(fm.groups.get(&1).unwrap().contains(2));
1570    }
1571
1572    #[test]
1573    fn removing_focused_member_from_active_trap_refocuses_remaining_member() {
1574        let mut fm = FocusManager::new();
1575        fm.graph_mut().insert(node(1, 0));
1576        fm.graph_mut().insert(node(2, 1));
1577        fm.graph_mut().insert(node(3, 2));
1578        fm.create_group(1, vec![1, 2]);
1579
1580        fm.focus(2);
1581        assert!(fm.push_trap(1));
1582        assert_eq!(fm.current(), Some(2));
1583
1584        fm.remove_from_group(1, 2);
1585        assert_eq!(fm.current(), Some(1));
1586        assert!(fm.is_trapped());
1587        assert!(fm.focus(3).is_none());
1588        assert_eq!(fm.current(), Some(1));
1589    }
1590
1591    #[test]
1592    fn removing_last_member_from_active_trap_allows_focus_escape() {
1593        let mut fm = FocusManager::new();
1594        fm.graph_mut().insert(node(1, 0));
1595        fm.graph_mut().insert(node(2, 1));
1596        fm.create_group(1, vec![1]);
1597
1598        fm.focus(1);
1599        assert!(fm.push_trap(1));
1600        assert!(fm.is_trapped());
1601
1602        fm.remove_from_group(1, 1);
1603        assert!(!fm.is_trapped());
1604        assert_eq!(fm.current(), Some(1));
1605        assert_eq!(fm.focus(2), Some(1));
1606        assert_eq!(fm.current(), Some(2));
1607    }
1608
1609    #[test]
1610    fn removing_active_inner_trap_member_falls_back_to_outer_trap() {
1611        let mut fm = FocusManager::new();
1612        fm.graph_mut().insert(node(1, 0));
1613        fm.graph_mut().insert(node(2, 1));
1614        fm.graph_mut().insert(node(3, 2));
1615        fm.create_group(10, vec![1, 2]);
1616        fm.create_group(20, vec![3]);
1617
1618        fm.focus(1);
1619        assert!(fm.push_trap(10));
1620        assert!(fm.push_trap(20));
1621        assert_eq!(fm.current(), Some(3));
1622
1623        fm.remove_from_group(20, 3);
1624        assert!(fm.is_trapped());
1625        assert_eq!(fm.current(), Some(1));
1626        assert!(fm.focus(3).is_none());
1627        assert_eq!(fm.focus(2), Some(1));
1628        assert_eq!(fm.current(), Some(2));
1629    }
1630
1631    #[test]
1632    fn adding_member_to_invalidated_trap_restores_confinement() {
1633        let mut fm = FocusManager::new();
1634        fm.graph_mut().insert(node(1, 0));
1635        fm.graph_mut().insert(node(2, 1));
1636        fm.create_group(1, vec![1]);
1637
1638        fm.focus(1);
1639        assert!(fm.push_trap(1));
1640
1641        fm.remove_from_group(1, 1);
1642        assert!(!fm.is_trapped());
1643
1644        fm.add_to_group(1, 2);
1645        assert!(fm.is_trapped());
1646        assert_eq!(fm.current(), Some(2));
1647        assert!(fm.focus(1).is_none());
1648    }
1649
1650    #[test]
1651    fn remove_from_nonexistent_group_is_noop() {
1652        let mut fm = FocusManager::new();
1653        fm.remove_from_group(999, 1); // should not panic
1654    }
1655
1656    #[test]
1657    fn remove_group_deletes_group() {
1658        let mut fm = FocusManager::new();
1659        fm.graph_mut().insert(node(1, 0));
1660        fm.create_group(42, vec![1]);
1661
1662        fm.remove_group(42);
1663        assert!(!fm.groups.contains_key(&42));
1664    }
1665
1666    #[test]
1667    fn remove_group_from_active_inner_trap_falls_back_to_outer_trap() {
1668        let mut fm = FocusManager::new();
1669        fm.graph_mut().insert(node(1, 0));
1670        fm.graph_mut().insert(node(2, 1));
1671        fm.graph_mut().insert(node(3, 2));
1672        fm.create_group(10, vec![1, 2]);
1673        fm.create_group(20, vec![3]);
1674
1675        fm.focus(1);
1676        assert!(fm.push_trap(10));
1677        assert!(fm.push_trap(20));
1678        assert_eq!(fm.current(), Some(3));
1679
1680        fm.remove_group(20);
1681        assert!(fm.is_trapped());
1682        assert_eq!(fm.current(), Some(1));
1683        assert!(fm.focus(3).is_none());
1684    }
1685
1686    #[test]
1687    fn remove_group_clears_stale_trap_entries() {
1688        let mut fm = FocusManager::new();
1689        fm.graph_mut().insert(node(1, 0));
1690        fm.create_group(10, vec![1]);
1691
1692        fm.focus(1);
1693        assert!(fm.push_trap(10));
1694        assert!(fm.is_trapped());
1695
1696        fm.remove_group(10);
1697        assert!(!fm.is_trapped());
1698        assert!(!fm.pop_trap());
1699    }
1700
1701    #[test]
1702    fn remove_group_blurs_invalid_current_when_no_fallback_exists() {
1703        let mut fm = FocusManager::new();
1704        fm.graph_mut().insert(node(1, 0));
1705        fm.create_group(10, vec![1]);
1706        fm.focus(1);
1707
1708        let _ = fm.graph_mut().remove(1);
1709        fm.remove_group(10);
1710
1711        assert_eq!(fm.current(), None);
1712        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1713    }
1714
1715    // --- FocusGroup ---
1716
1717    #[test]
1718    fn focus_group_with_wrap() {
1719        let group = FocusGroup::new(1, vec![1, 2]).with_wrap(false);
1720        assert!(!group.wrap);
1721    }
1722
1723    #[test]
1724    fn focus_group_default_wraps() {
1725        let group = FocusGroup::new(1, vec![]);
1726        assert!(group.wrap);
1727    }
1728
1729    // --- Trap stack ---
1730
1731    #[test]
1732    fn nested_traps() {
1733        let mut fm = FocusManager::new();
1734        fm.graph_mut().insert(node(1, 0));
1735        fm.graph_mut().insert(node(2, 1));
1736        fm.graph_mut().insert(node(3, 2));
1737        fm.graph_mut().insert(node(4, 3));
1738
1739        fm.create_group(10, vec![1, 2]);
1740        fm.create_group(20, vec![3, 4]);
1741
1742        fm.focus(1);
1743        fm.push_trap(10);
1744        assert!(fm.is_trapped());
1745
1746        fm.push_trap(20);
1747        // Should be in inner trap, focused on first of group 20
1748        assert_eq!(fm.current(), Some(3));
1749
1750        // Pop inner trap
1751        fm.pop_trap();
1752        // Should still be trapped (in group 10)
1753        assert!(fm.is_trapped());
1754
1755        // Pop outer trap
1756        fm.pop_trap();
1757        assert!(!fm.is_trapped());
1758    }
1759
1760    #[test]
1761    fn trap_push_pop_does_not_pollute_focus_history() {
1762        let mut fm = FocusManager::new();
1763        fm.graph_mut().insert(node(1, 0));
1764        fm.graph_mut().insert(node(2, 1));
1765        fm.graph_mut().insert(node(3, 2));
1766        fm.create_group(10, vec![2]);
1767
1768        fm.focus(1);
1769        fm.focus(3);
1770        assert_eq!(fm.current(), Some(3));
1771
1772        assert!(fm.push_trap(10));
1773        assert_eq!(fm.current(), Some(2));
1774
1775        assert!(fm.pop_trap());
1776        assert_eq!(fm.current(), Some(3));
1777
1778        assert!(fm.focus_back());
1779        assert_eq!(fm.current(), Some(1));
1780        assert!(!fm.focus_back());
1781    }
1782
1783    #[test]
1784    fn pop_trap_restores_none_when_modal_opened_without_focus() {
1785        let mut fm = FocusManager::new();
1786        fm.graph_mut().insert(node(1, 0));
1787        fm.create_group(10, vec![1]);
1788
1789        assert!(fm.push_trap(10));
1790        assert_eq!(fm.current(), Some(1));
1791
1792        assert!(fm.pop_trap());
1793        assert_eq!(fm.current(), None);
1794        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1795    }
1796
1797    #[test]
1798    fn pop_trap_on_empty_returns_false() {
1799        let mut fm = FocusManager::new();
1800        assert!(!fm.pop_trap());
1801    }
1802
1803    #[test]
1804    fn push_trap_rejects_missing_group() {
1805        let mut fm = FocusManager::new();
1806        fm.graph_mut().insert(node(1, 0));
1807        fm.focus(1);
1808
1809        // Group 999 doesn't exist — push_trap must refuse.
1810        assert!(!fm.push_trap(999));
1811        assert!(!fm.is_trapped());
1812        // Focus should remain unchanged (no deadlock).
1813        assert_eq!(fm.current(), Some(1));
1814    }
1815
1816    #[test]
1817    fn push_trap_rejects_empty_group() {
1818        let mut fm = FocusManager::new();
1819        fm.graph_mut().insert(node(1, 0));
1820        fm.focus(1);
1821
1822        // Create group with no members.
1823        fm.create_group(42, vec![]);
1824        assert!(!fm.push_trap(42));
1825        assert!(!fm.is_trapped());
1826        // Focus should remain unchanged (no deadlock).
1827        assert_eq!(fm.current(), Some(1));
1828    }
1829
1830    #[test]
1831    fn push_trap_autofocuses_negative_tabindex_member_when_group_has_no_tabbable_nodes() {
1832        let mut fm = FocusManager::new();
1833        fm.graph_mut().insert(node(1, 0));
1834        fm.graph_mut().insert(node(2, -1));
1835        fm.focus(1);
1836
1837        fm.create_group(42, vec![2]);
1838        assert!(fm.push_trap(42));
1839        assert!(fm.is_trapped());
1840        assert_eq!(fm.current(), Some(2));
1841    }
1842
1843    #[test]
1844    fn push_trap_blurred_restores_negative_tabindex_member_on_focus_gain() {
1845        let mut fm = FocusManager::new();
1846        fm.graph_mut().insert(node(1, 0));
1847        fm.graph_mut().insert(node(2, -1));
1848        fm.focus(1);
1849        assert!(fm.apply_host_focus(false));
1850
1851        fm.create_group(42, vec![2]);
1852        assert!(fm.push_trap(42));
1853        assert_eq!(fm.current(), None);
1854
1855        assert!(fm.apply_host_focus(true));
1856        assert_eq!(fm.current(), Some(2));
1857    }
1858
1859    #[test]
1860    fn push_trap_retargets_when_current_group_member_becomes_unfocusable() {
1861        let mut fm = FocusManager::new();
1862        fm.graph_mut().insert(node(1, 0));
1863        fm.graph_mut().insert(node(2, 1));
1864        fm.focus(1);
1865        fm.create_group(10, vec![1, 2]);
1866
1867        fm.graph_mut().insert(node(1, 0).with_focusable(false));
1868
1869        assert!(fm.push_trap(10));
1870        assert_eq!(fm.current(), Some(2));
1871    }
1872
1873    // --- Focus events ---
1874
1875    #[test]
1876    fn take_focus_event_clears_it() {
1877        let mut fm = FocusManager::new();
1878        fm.graph_mut().insert(node(1, 0));
1879        fm.focus(1);
1880
1881        assert!(fm.take_focus_event().is_some());
1882        assert!(fm.take_focus_event().is_none());
1883    }
1884
1885    #[test]
1886    fn focus_event_accessor() {
1887        let mut fm = FocusManager::new();
1888        fm.graph_mut().insert(node(1, 0));
1889        fm.focus(1);
1890
1891        assert_eq!(fm.focus_event(), Some(&FocusEvent::FocusGained { id: 1 }));
1892    }
1893
1894    // --- Navigate with no current ---
1895
1896    #[test]
1897    fn navigate_direction_with_no_current_returns_false() {
1898        let mut fm = FocusManager::new();
1899        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1900        assert!(!fm.navigate(NavDirection::Right));
1901    }
1902
1903    // --- graph accessors ---
1904
1905    #[test]
1906    fn graph_accessor_returns_reference() {
1907        let mut fm = FocusManager::new();
1908        fm.graph_mut().insert(node(1, 0));
1909        assert!(fm.graph().get(1).is_some());
1910    }
1911
1912    // --- Focus indicator ---
1913
1914    #[test]
1915    fn default_indicator_is_reverse() {
1916        let fm = FocusManager::new();
1917        assert!(fm.indicator().is_visible());
1918        assert_eq!(
1919            fm.indicator().kind(),
1920            crate::focus::FocusIndicatorKind::StyleOverlay
1921        );
1922    }
1923
1924    #[test]
1925    fn set_indicator() {
1926        let mut fm = FocusManager::new();
1927        fm.set_indicator(crate::focus::FocusIndicator::underline());
1928        assert_eq!(
1929            fm.indicator().kind(),
1930            crate::focus::FocusIndicatorKind::Underline
1931        );
1932    }
1933
1934    // --- Focus change count ---
1935
1936    #[test]
1937    fn focus_change_count_increments() {
1938        let mut fm = FocusManager::new();
1939        fm.graph_mut().insert(node(1, 0));
1940        fm.graph_mut().insert(node(2, 1));
1941
1942        assert_eq!(fm.focus_change_count(), 0);
1943
1944        fm.focus(1);
1945        assert_eq!(fm.focus_change_count(), 1);
1946
1947        fm.focus(2);
1948        assert_eq!(fm.focus_change_count(), 2);
1949
1950        fm.blur();
1951        assert_eq!(fm.focus_change_count(), 3);
1952    }
1953
1954    #[test]
1955    fn focus_change_count_zero_on_no_op() {
1956        let mut fm = FocusManager::new();
1957        fm.graph_mut().insert(node(1, 0));
1958        fm.focus(1);
1959        assert_eq!(fm.focus_change_count(), 1);
1960
1961        // Focusing the same widget is a no-op
1962        fm.focus(1);
1963        assert_eq!(fm.focus_change_count(), 1);
1964    }
1965
1966    #[test]
1967    fn focus_back_increments_focus_change_count() {
1968        let mut fm = FocusManager::new();
1969        fm.graph_mut().insert(node(1, 0));
1970        fm.graph_mut().insert(node(2, 1));
1971
1972        fm.focus(1);
1973        fm.focus(2);
1974        assert_eq!(fm.focus_change_count(), 2);
1975
1976        assert!(fm.focus_back());
1977        assert_eq!(fm.current(), Some(1));
1978        assert_eq!(fm.focus_change_count(), 3);
1979    }
1980}