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    /// Synchronize this manager's authoritative focus state into `frame`'s
480    /// accessibility tree builder.
481    ///
482    /// Call once during `view()` (either before or after widgets render).
483    /// When [`ftui_render::frame::Frame::finish_a11y`] runs, the built
484    /// [`ftui_a11y::tree::A11yTree`] uses `self.current()` (when the host
485    /// window is focused) as the single focus truth source, delegating to an
486    /// active focused descendant when `self.current()` names a composite
487    /// container (`List`, `Tree`, `Form`, `Dialog`) and clearing stale
488    /// `focused` flags on all other nodes.
489    pub fn sync_to_frame(&self, frame: &mut ftui_render::frame::Frame<'_>) {
490        let target = if self.host_focused {
491            self.current
492        } else {
493            None
494        };
495        frame.set_a11y_focused(target);
496    }
497
498    /// Apply this manager's authoritative focus state directly to an
499    /// [`ftui_a11y::tree::A11yTreeBuilder`] and reading-order slice.
500    pub fn apply_to_a11y(&self, builder: &mut ftui_a11y::tree::A11yTreeBuilder, order: &[u64]) {
501        let resolved_target = if self.host_focused {
502            self.current.filter(|id| builder.node(*id).is_some())
503        } else {
504            None
505        };
506        let active_focus = resolved_target.map(|target| {
507            let is_in_target_subtree =
508                |builder: &ftui_a11y::tree::A11yTreeBuilder, mut id: u64| -> bool {
509                    let mut steps = 0usize;
510                    loop {
511                        if id == target {
512                            return true;
513                        }
514                        let Some(parent) = builder.node(id).and_then(|n| n.parent) else {
515                            return false;
516                        };
517                        id = parent;
518                        steps += 1;
519                        if steps > 256 {
520                            return false;
521                        }
522                    }
523                };
524            order
525                .iter()
526                .copied()
527                .find(|&id| {
528                    builder.node(id).is_some_and(|n| n.state.focused)
529                        && is_in_target_subtree(builder, id)
530                })
531                .or_else(|| {
532                    order.iter().copied().find(|&id| {
533                        id != target
534                            && builder.node(id).is_some_and(|n| n.state.selected)
535                            && is_in_target_subtree(builder, id)
536                    })
537                })
538                .unwrap_or(target)
539        });
540        for &id in order {
541            if let Some(node) = builder.node_mut(id) {
542                node.state.focused = Some(id) == active_focus;
543            }
544        }
545        builder.set_focused(active_focus);
546    }
547
548    #[cfg(test)]
549    #[must_use]
550    pub(crate) fn group_count(&self) -> usize {
551        self.groups.len()
552    }
553
554    #[must_use]
555    pub(crate) fn has_group(&self, group_id: u32) -> bool {
556        self.groups.contains_key(&group_id)
557    }
558
559    #[must_use]
560    pub(crate) fn group_members(&self, group_id: u32) -> Vec<FocusId> {
561        self.groups
562            .get(&group_id)
563            .map(|group| group.members.clone())
564            .unwrap_or_default()
565    }
566
567    #[cfg(test)]
568    #[must_use]
569    pub(crate) fn base_trap_return_focus(&self) -> Option<Option<FocusId>> {
570        self.trap_stack.first().map(|trap| trap.return_focus)
571    }
572
573    #[must_use]
574    pub(crate) fn deferred_focus_target(&self) -> Option<FocusId> {
575        if let Some(id) = self.active_focus_target() {
576            return Some(id);
577        }
578
579        self.active_trap_group()
580            .and_then(|group_id| self.group_primary_focus_target(group_id))
581    }
582
583    #[must_use]
584    pub(crate) fn logical_focus_target(&self) -> Option<FocusId> {
585        self.active_focus_target()
586    }
587
588    pub(crate) fn focus_without_history(&mut self, id: FocusId) -> bool {
589        self.set_focus_without_history(id)
590    }
591
592    pub(crate) fn focus_first_without_history_for_restore(&mut self) -> bool {
593        self.focus_first_without_history()
594    }
595
596    pub(crate) fn replace_deferred_focus_target(&mut self, target: Option<FocusId>) {
597        self.current = None;
598        self.pending_focus_on_host_gain =
599            target.filter(|id| self.can_focus(*id) && self.allowed_by_trap(*id));
600    }
601
602    pub(crate) fn remove_group_without_repair(&mut self, group_id: u32) -> bool {
603        if self.groups.remove(&group_id).is_none() {
604            return false;
605        }
606        self.trap_stack.retain(|trap| trap.group_id != group_id);
607        true
608    }
609
610    pub(crate) fn push_trap_with_return_focus(
611        &mut self,
612        group_id: u32,
613        return_focus: Option<FocusId>,
614    ) -> bool {
615        if !self.group_has_focusable_member(group_id) {
616            return false;
617        }
618
619        #[cfg(feature = "tracing")]
620        tracing::debug!(
621            group_id,
622            return_focus = ?return_focus,
623            "focus.trap_push"
624        );
625        self.trap_stack.push(FocusTrap {
626            group_id,
627            return_focus,
628        });
629        true
630    }
631
632    pub(crate) fn repair_focus_after_excluding_ids(&mut self, excluded: &[FocusId]) {
633        self.history.retain(|id| !excluded.contains(id));
634
635        if !self.host_focused {
636            if self.current.is_some_and(|id| excluded.contains(&id)) {
637                let _ = self.blur();
638            }
639            return;
640        }
641
642        if self.is_trapped() || !self.current.is_some_and(|id| excluded.contains(&id)) {
643            return;
644        }
645
646        for id in self.graph.tab_order() {
647            if excluded.contains(&id) {
648                continue;
649            }
650            if self.set_focus_without_history(id) {
651                return;
652            }
653        }
654
655        let _ = self.blur();
656    }
657
658    pub(crate) fn clear_deferred_focus_if_excluded(&mut self, excluded: &[FocusId]) {
659        if self
660            .pending_focus_on_host_gain
661            .is_some_and(|id| excluded.contains(&id))
662        {
663            self.pending_focus_on_host_gain = None;
664        }
665    }
666
667    pub(crate) fn restore_focus_after_invalid_current(&mut self) {
668        if !self.host_focused {
669            return;
670        }
671
672        if let Some(group_id) = self.active_trap_group()
673            && self.focus_first_in_group_without_history(group_id)
674        {
675            return;
676        }
677
678        let _ = self.focus_first_without_history();
679    }
680
681    fn set_focus(&mut self, id: FocusId) -> bool {
682        self.set_focus_target(id, true)
683    }
684
685    fn set_focus_without_history(&mut self, id: FocusId) -> bool {
686        self.set_focus_target(id, false)
687    }
688
689    fn set_focus_target(&mut self, id: FocusId, record_history: bool) -> bool {
690        if !self.host_focused {
691            return self.set_pending_focus_target(id);
692        }
693        self.set_focus_internal(id, record_history)
694    }
695
696    fn set_focus_internal(&mut self, id: FocusId, record_history: bool) -> bool {
697        if !self.can_focus(id) || !self.allowed_by_trap(id) {
698            return false;
699        }
700        if self.current == Some(id) {
701            return false;
702        }
703
704        let prev = self.current;
705        if let Some(prev_id) = prev {
706            if record_history && Some(prev_id) != self.history.last().copied() {
707                if self.history.len() >= MAX_FOCUS_HISTORY {
708                    self.history.remove(0);
709                }
710                self.history.push(prev_id);
711            }
712            let event = FocusEvent::FocusMoved {
713                from: prev_id,
714                to: id,
715            };
716            #[cfg(feature = "tracing")]
717            tracing::debug!(
718                from_widget = prev_id,
719                to_widget = id,
720                trigger = "navigate",
721                "focus.change"
722            );
723            self.last_event = Some(event);
724        } else {
725            #[cfg(feature = "tracing")]
726            tracing::debug!(to_widget = id, trigger = "initial", "focus.change");
727            self.last_event = Some(FocusEvent::FocusGained { id });
728        }
729
730        self.current = Some(id);
731        self.focus_change_count += 1;
732        true
733    }
734
735    fn can_focus(&self, id: FocusId) -> bool {
736        self.graph.get(id).map(|n| n.is_focusable).unwrap_or(false)
737    }
738
739    fn active_focus_target(&self) -> Option<FocusId> {
740        if let Some(current) = self.current
741            && self.can_focus(current)
742            && self.allowed_by_trap(current)
743        {
744            return Some(current);
745        }
746
747        if self.host_focused {
748            return None;
749        }
750
751        self.pending_focus_on_host_gain
752            .filter(|id| self.can_focus(*id) && self.allowed_by_trap(*id))
753    }
754
755    fn set_pending_focus_target(&mut self, id: FocusId) -> bool {
756        if !self.can_focus(id) || !self.allowed_by_trap(id) {
757            return false;
758        }
759
760        let prev = self.active_focus_target();
761        self.current = None;
762        if prev == Some(id) {
763            return false;
764        }
765
766        self.pending_focus_on_host_gain = Some(id);
767        true
768    }
769
770    fn active_trap_group(&self) -> Option<u32> {
771        self.trap_stack
772            .iter()
773            .rev()
774            .find(|trap| self.group_has_focusable_member(trap.group_id))
775            .map(|trap| trap.group_id)
776    }
777
778    fn allowed_by_trap(&self, id: FocusId) -> bool {
779        let Some(group_id) = self.active_trap_group() else {
780            return true;
781        };
782        self.groups
783            .get(&group_id)
784            .map(|g| g.contains(id))
785            .unwrap_or(false)
786    }
787
788    fn group_has_focusable_member(&self, group_id: u32) -> bool {
789        self.groups
790            .get(&group_id)
791            .is_some_and(|group| group.members.iter().any(|id| self.can_focus(*id)))
792    }
793
794    fn repair_focus_after_group_change(&mut self) {
795        if !self.host_focused {
796            if self.current.is_some() {
797                let _ = self.blur();
798            }
799            return;
800        }
801
802        match self.active_trap_group() {
803            Some(group_id) => {
804                let current_allowed = self
805                    .current
806                    .is_some_and(|id| self.can_focus(id) && self.allowed_by_trap(id));
807                if !current_allowed {
808                    let _ = self.focus_first_in_group_without_history(group_id);
809                }
810            }
811            None => {
812                if self.current.is_some_and(|id| !self.can_focus(id))
813                    && !self.focus_first_without_history()
814                {
815                    let _ = self.blur();
816                }
817            }
818        }
819    }
820
821    fn is_current_focusable_in_group(&self, group_id: u32) -> bool {
822        let Some(current) = self.current else {
823            return false;
824        };
825        self.can_focus(current)
826            && self
827                .groups
828                .get(&group_id)
829                .map(|g| g.contains(current))
830                .unwrap_or(false)
831    }
832
833    fn active_tab_order(&self) -> Vec<FocusId> {
834        if let Some(group_id) = self.active_trap_group() {
835            return self.group_tab_order(group_id);
836        }
837        self.graph.tab_order()
838    }
839
840    fn group_tab_order(&self, group_id: u32) -> Vec<FocusId> {
841        let Some(group) = self.groups.get(&group_id) else {
842            return Vec::new();
843        };
844        let order = self.graph.tab_order();
845        order.into_iter().filter(|id| group.contains(*id)).collect()
846    }
847
848    pub(crate) fn group_primary_focus_target(&self, group_id: u32) -> Option<FocusId> {
849        self.group_tab_order(group_id).first().copied().or_else(|| {
850            self.groups
851                .get(&group_id)
852                .and_then(|group| group.members.iter().copied().find(|id| self.can_focus(*id)))
853        })
854    }
855
856    fn focus_first_in_group_without_history(&mut self, group_id: u32) -> bool {
857        let Some(first) = self.group_primary_focus_target(group_id) else {
858            return false;
859        };
860        self.set_focus_without_history(first)
861    }
862
863    fn focus_first_without_history(&mut self) -> bool {
864        let order = self.active_tab_order();
865        let Some(first) = order.first().copied() else {
866            return false;
867        };
868        self.set_focus_without_history(first)
869    }
870
871    fn move_in_tab_order(&mut self, forward: bool) -> bool {
872        let order = self.active_tab_order();
873        if order.is_empty() {
874            return false;
875        }
876        let first = order[0];
877        let last = order[order.len() - 1];
878        let fallback = if forward { first } else { last };
879
880        let wrap = self
881            .active_trap_group()
882            .and_then(|id| self.groups.get(&id).map(|g| g.wrap))
883            .unwrap_or(true);
884
885        let next = match self.active_focus_target() {
886            None => fallback,
887            Some(current) => {
888                let pos = order.iter().position(|id| *id == current);
889                match pos {
890                    None => fallback,
891                    Some(idx) if forward => {
892                        if idx + 1 < order.len() {
893                            order[idx + 1]
894                        } else if wrap {
895                            order[0]
896                        } else {
897                            return false;
898                        }
899                    }
900                    Some(idx) => {
901                        if idx > 0 {
902                            order[idx - 1]
903                        } else if wrap {
904                            last
905                        } else {
906                            return false;
907                        }
908                    }
909                }
910            }
911        };
912
913        self.set_focus(next)
914    }
915
916    fn dedup_members(&self, ids: Vec<FocusId>) -> Vec<FocusId> {
917        let mut out = Vec::new();
918        for id in ids {
919            if !out.contains(&id) {
920                out.push(id);
921            }
922        }
923        out
924    }
925
926    fn filter_focusable(&self, ids: Vec<FocusId>) -> Vec<FocusId> {
927        self.dedup_members(ids)
928            .into_iter()
929            .filter(|id| self.can_focus(*id))
930            .collect()
931    }
932}
933
934// =========================================================================
935// Tests
936// =========================================================================
937
938#[cfg(test)]
939mod tests {
940    use super::*;
941    use crate::focus::FocusNode;
942    use ftui_core::geometry::Rect;
943
944    fn node(id: FocusId, tab: i32) -> FocusNode {
945        FocusNode::new(id, Rect::new(0, 0, 1, 1)).with_tab_index(tab)
946    }
947
948    #[test]
949    fn focus_basic() {
950        let mut fm = FocusManager::new();
951        fm.graph_mut().insert(node(1, 0));
952        fm.graph_mut().insert(node(2, 1));
953
954        assert!(fm.focus(1).is_none());
955        assert_eq!(fm.current(), Some(1));
956
957        assert_eq!(fm.focus(2), Some(1));
958        assert_eq!(fm.current(), Some(2));
959
960        assert_eq!(fm.blur(), Some(2));
961        assert_eq!(fm.current(), None);
962    }
963
964    #[test]
965    fn focus_history_back() {
966        let mut fm = FocusManager::new();
967        fm.graph_mut().insert(node(1, 0));
968        fm.graph_mut().insert(node(2, 1));
969        fm.graph_mut().insert(node(3, 2));
970
971        fm.focus(1);
972        fm.focus(2);
973        fm.focus(3);
974
975        assert!(fm.focus_back());
976        assert_eq!(fm.current(), Some(2));
977
978        assert!(fm.focus_back());
979        assert_eq!(fm.current(), Some(1));
980    }
981
982    #[test]
983    fn focus_history_is_bounded_and_keeps_the_newest_entries() {
984        let mut fm = FocusManager::new();
985        fm.graph_mut().insert(node(1, 0));
986        fm.graph_mut().insert(node(2, 1));
987        fm.graph_mut().insert(node(3, 2));
988
989        for _ in 0..10_000 {
990            fm.focus(1);
991            fm.focus(2);
992        }
993        assert_eq!(fm.history.len(), MAX_FOCUS_HISTORY);
994
995        fm.focus(3);
996        assert!(fm.focus_back());
997        assert_eq!(fm.current(), Some(2));
998    }
999
1000    #[test]
1001    fn focus_back_skips_current_id_in_history() {
1002        let mut fm = FocusManager::new();
1003        fm.graph_mut().insert(node(1, 0));
1004        fm.graph_mut().insert(node(2, 1));
1005
1006        fm.focus(1);
1007        fm.focus(2);
1008        assert_eq!(fm.current(), Some(2));
1009
1010        assert_eq!(fm.blur(), Some(2));
1011        assert_eq!(fm.current(), None);
1012
1013        fm.focus(1);
1014        assert_eq!(fm.current(), Some(1));
1015        let _ = fm.take_focus_event();
1016        let before = fm.focus_change_count();
1017
1018        assert!(!fm.focus_back());
1019        assert_eq!(fm.current(), Some(1));
1020        assert!(fm.take_focus_event().is_none());
1021        assert_eq!(fm.focus_change_count(), before);
1022    }
1023
1024    #[test]
1025    fn focus_next_prev() {
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
1031        assert!(fm.focus_next());
1032        assert_eq!(fm.current(), Some(1));
1033
1034        assert!(fm.focus_next());
1035        assert_eq!(fm.current(), Some(2));
1036
1037        assert!(fm.focus_prev());
1038        assert_eq!(fm.current(), Some(1));
1039    }
1040
1041    #[test]
1042    fn apply_host_focus_loss_blurs_current() {
1043        let mut fm = FocusManager::new();
1044        fm.graph_mut().insert(node(1, 0));
1045        fm.focus(1);
1046        let _ = fm.take_focus_event();
1047
1048        assert!(fm.apply_host_focus(false));
1049        assert_eq!(fm.current(), None);
1050        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1051    }
1052
1053    #[test]
1054    fn apply_host_focus_gain_focuses_first_when_unfocused() {
1055        let mut fm = FocusManager::new();
1056        fm.graph_mut().insert(node(10, 1));
1057        fm.graph_mut().insert(node(5, 0));
1058
1059        assert!(fm.apply_host_focus(true));
1060        assert_eq!(fm.current(), Some(5));
1061        assert_eq!(
1062            fm.take_focus_event(),
1063            Some(FocusEvent::FocusGained { id: 5 })
1064        );
1065    }
1066
1067    #[test]
1068    fn apply_host_focus_gain_preserves_valid_current() {
1069        let mut fm = FocusManager::new();
1070        fm.graph_mut().insert(node(1, 0));
1071        fm.graph_mut().insert(node(2, 1));
1072        fm.focus(2);
1073        let _ = fm.take_focus_event();
1074
1075        assert!(!fm.apply_host_focus(true));
1076        assert_eq!(fm.current(), Some(2));
1077        assert!(fm.take_focus_event().is_none());
1078    }
1079
1080    #[test]
1081    fn apply_host_focus_gain_clears_invalid_current_when_restore_fails() {
1082        let mut fm = FocusManager::new();
1083        fm.graph_mut().insert(node(1, 0));
1084        fm.focus(1);
1085        let _ = fm.take_focus_event();
1086        let _ = fm.graph_mut().remove(1);
1087
1088        assert!(fm.apply_host_focus(true));
1089        assert_eq!(fm.current(), None);
1090        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1091    }
1092
1093    #[test]
1094    fn apply_host_focus_gain_respects_trap_order() {
1095        let mut fm = FocusManager::new();
1096        fm.graph_mut().insert(node(1, 0));
1097        fm.graph_mut().insert(node(2, 1));
1098        fm.graph_mut().insert(node(3, 2));
1099        fm.create_group(42, vec![2, 3]);
1100        fm.push_trap(42);
1101        let _ = fm.take_focus_event();
1102        fm.blur();
1103        let _ = fm.take_focus_event();
1104
1105        assert!(fm.apply_host_focus(true));
1106        assert_eq!(fm.current(), Some(2));
1107    }
1108
1109    #[test]
1110    fn apply_host_focus_gain_restores_previously_selected_trapped_focus() {
1111        let mut fm = FocusManager::new();
1112        fm.graph_mut().insert(node(1, 0));
1113        fm.graph_mut().insert(node(2, 1));
1114        fm.graph_mut().insert(node(3, 2));
1115        fm.create_group(42, vec![2, 3]);
1116        assert!(fm.push_trap(42));
1117        assert_eq!(fm.current(), Some(2));
1118        assert_eq!(fm.focus(3), Some(2));
1119        let _ = fm.take_focus_event();
1120
1121        assert!(fm.apply_host_focus(false));
1122        assert_eq!(fm.current(), None);
1123        let _ = fm.take_focus_event();
1124
1125        assert!(fm.apply_host_focus(true));
1126        assert_eq!(fm.current(), Some(3));
1127        assert_eq!(
1128            fm.take_focus_event(),
1129            Some(FocusEvent::FocusGained { id: 3 })
1130        );
1131    }
1132
1133    #[test]
1134    fn push_trap_while_host_blurred_without_prior_focus_restores_none_on_pop() {
1135        let mut fm = FocusManager::new();
1136        fm.graph_mut().insert(node(1, 0));
1137        fm.graph_mut().insert(node(2, 1));
1138        assert!(!fm.apply_host_focus(false));
1139
1140        fm.create_group(42, vec![2]);
1141        assert!(fm.push_trap(42));
1142        assert!(fm.apply_host_focus(true));
1143        assert_eq!(fm.current(), Some(2));
1144
1145        assert!(fm.pop_trap());
1146        assert_eq!(fm.current(), None);
1147        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 2 }));
1148    }
1149
1150    #[test]
1151    fn push_trap_does_not_autofocus_while_host_blurred() {
1152        let mut fm = FocusManager::new();
1153        fm.graph_mut().insert(node(1, 0));
1154        fm.graph_mut().insert(node(2, 1));
1155        fm.focus(1);
1156        assert!(fm.apply_host_focus(false));
1157
1158        fm.create_group(42, vec![2]);
1159        assert!(fm.push_trap(42));
1160        assert_eq!(fm.current(), None);
1161
1162        assert!(fm.apply_host_focus(true));
1163        assert_eq!(fm.current(), Some(2));
1164    }
1165
1166    #[test]
1167    fn focus_while_host_blurred_updates_deferred_target_without_restoring_current() {
1168        let mut fm = FocusManager::new();
1169        fm.graph_mut().insert(node(1, 0));
1170        fm.graph_mut().insert(node(2, 1));
1171        fm.graph_mut().insert(node(3, 2));
1172        fm.focus(1);
1173        let _ = fm.take_focus_event();
1174
1175        assert!(fm.apply_host_focus(false));
1176        assert_eq!(fm.current(), None);
1177        assert_eq!(fm.focus(3), Some(1));
1178        assert_eq!(fm.current(), None);
1179        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1180
1181        assert!(fm.apply_host_focus(true));
1182        assert_eq!(fm.current(), Some(3));
1183        assert_eq!(
1184            fm.take_focus_event(),
1185            Some(FocusEvent::FocusGained { id: 3 })
1186        );
1187    }
1188
1189    #[test]
1190    fn focus_next_while_host_blurred_advances_deferred_target() {
1191        let mut fm = FocusManager::new();
1192        fm.graph_mut().insert(node(1, 0));
1193        fm.graph_mut().insert(node(2, 1));
1194        fm.graph_mut().insert(node(3, 2));
1195        fm.focus(1);
1196        assert_eq!(fm.focus(2), Some(1));
1197        let _ = fm.take_focus_event();
1198
1199        assert!(fm.apply_host_focus(false));
1200        assert_eq!(fm.current(), None);
1201        assert!(fm.focus_next());
1202        assert_eq!(fm.current(), None);
1203        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 2 }));
1204
1205        assert!(fm.apply_host_focus(true));
1206        assert_eq!(fm.current(), Some(3));
1207        assert_eq!(
1208            fm.take_focus_event(),
1209            Some(FocusEvent::FocusGained { id: 3 })
1210        );
1211    }
1212
1213    #[test]
1214    fn focus_trap_push_pop() {
1215        let mut fm = FocusManager::new();
1216        fm.graph_mut().insert(node(1, 0));
1217        fm.graph_mut().insert(node(2, 1));
1218        fm.graph_mut().insert(node(3, 2));
1219
1220        fm.focus(3);
1221        fm.create_group(7, vec![1, 2]);
1222
1223        fm.push_trap(7);
1224        assert!(fm.is_trapped());
1225        assert_eq!(fm.current(), Some(1));
1226
1227        fm.pop_trap();
1228        assert!(!fm.is_trapped());
1229        assert_eq!(fm.current(), Some(3));
1230    }
1231
1232    #[test]
1233    fn focus_group_wrap_respected() {
1234        let mut fm = FocusManager::new();
1235        fm.graph_mut().insert(node(1, 0));
1236        fm.graph_mut().insert(node(2, 1));
1237        fm.create_group(9, vec![1, 2]);
1238        fm.groups.get_mut(&9).unwrap().wrap = false;
1239
1240        fm.push_trap(9);
1241        fm.focus(2);
1242        assert!(!fm.focus_next());
1243        assert_eq!(fm.current(), Some(2));
1244    }
1245
1246    #[test]
1247    fn focus_event_generation() {
1248        let mut fm = FocusManager::new();
1249        fm.graph_mut().insert(node(1, 0));
1250        fm.graph_mut().insert(node(2, 1));
1251
1252        fm.focus(1);
1253        assert_eq!(
1254            fm.take_focus_event(),
1255            Some(FocusEvent::FocusGained { id: 1 })
1256        );
1257
1258        fm.focus(2);
1259        assert_eq!(
1260            fm.take_focus_event(),
1261            Some(FocusEvent::FocusMoved { from: 1, to: 2 })
1262        );
1263
1264        fm.blur();
1265        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 2 }));
1266    }
1267
1268    #[test]
1269    fn trap_prevents_focus_outside_group() {
1270        let mut fm = FocusManager::new();
1271        fm.graph_mut().insert(node(1, 0));
1272        fm.graph_mut().insert(node(2, 1));
1273        fm.graph_mut().insert(node(3, 2));
1274        fm.create_group(5, vec![1, 2]);
1275
1276        fm.push_trap(5);
1277        assert_eq!(fm.current(), Some(1));
1278
1279        // Attempt to focus outside trap should fail.
1280        assert!(fm.focus(3).is_none());
1281        assert_ne!(fm.current(), Some(3));
1282    }
1283
1284    // --- Spatial navigation integration ---
1285
1286    fn spatial_node(id: FocusId, x: u16, y: u16, w: u16, h: u16, tab: i32) -> FocusNode {
1287        FocusNode::new(id, Rect::new(x, y, w, h)).with_tab_index(tab)
1288    }
1289
1290    #[test]
1291    fn navigate_spatial_fallback() {
1292        let mut fm = FocusManager::new();
1293        // Two nodes side by side — no explicit edges.
1294        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1295        fm.graph_mut().insert(spatial_node(2, 20, 0, 10, 3, 1));
1296
1297        fm.focus(1);
1298        assert!(fm.navigate(NavDirection::Right));
1299        assert_eq!(fm.current(), Some(2));
1300
1301        assert!(fm.navigate(NavDirection::Left));
1302        assert_eq!(fm.current(), Some(1));
1303    }
1304
1305    #[test]
1306    fn navigate_explicit_edge_overrides_spatial() {
1307        let mut fm = FocusManager::new();
1308        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1309        fm.graph_mut().insert(spatial_node(2, 20, 0, 10, 3, 1)); // spatially right
1310        fm.graph_mut().insert(spatial_node(3, 40, 0, 10, 3, 2)); // further right
1311
1312        // Explicit edge overrides spatial: Right from 1 goes to 3, not 2.
1313        fm.graph_mut().connect(1, NavDirection::Right, 3);
1314
1315        fm.focus(1);
1316        assert!(fm.navigate(NavDirection::Right));
1317        assert_eq!(fm.current(), Some(3));
1318    }
1319
1320    #[test]
1321    fn navigate_spatial_respects_trap() {
1322        let mut fm = FocusManager::new();
1323        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1324        fm.graph_mut().insert(spatial_node(2, 20, 0, 10, 3, 1));
1325        fm.graph_mut().insert(spatial_node(3, 40, 0, 10, 3, 2));
1326
1327        // Trap to group containing only 1 and 2.
1328        fm.create_group(1, vec![1, 2]);
1329        fm.focus(2);
1330        fm.push_trap(1);
1331
1332        // Spatial would find 3 to the right of 2, but trap blocks it.
1333        assert!(!fm.navigate(NavDirection::Right));
1334        assert_eq!(fm.current(), Some(2));
1335    }
1336
1337    #[test]
1338    fn navigate_spatial_grid_round_trip() {
1339        let mut fm = FocusManager::new();
1340        // 2x2 grid.
1341        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1342        fm.graph_mut().insert(spatial_node(2, 20, 0, 10, 3, 1));
1343        fm.graph_mut().insert(spatial_node(3, 0, 6, 10, 3, 2));
1344        fm.graph_mut().insert(spatial_node(4, 20, 6, 10, 3, 3));
1345
1346        fm.focus(1);
1347
1348        // Navigate around the grid: right, down, left, up — back to start.
1349        assert!(fm.navigate(NavDirection::Right));
1350        assert_eq!(fm.current(), Some(2));
1351
1352        assert!(fm.navigate(NavDirection::Down));
1353        assert_eq!(fm.current(), Some(4));
1354
1355        assert!(fm.navigate(NavDirection::Left));
1356        assert_eq!(fm.current(), Some(3));
1357
1358        assert!(fm.navigate(NavDirection::Up));
1359        assert_eq!(fm.current(), Some(1));
1360    }
1361
1362    #[test]
1363    fn navigate_spatial_no_candidate() {
1364        let mut fm = FocusManager::new();
1365        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1366        fm.focus(1);
1367
1368        // No other nodes, spatial should return false.
1369        assert!(!fm.navigate(NavDirection::Right));
1370        assert!(!fm.navigate(NavDirection::Up));
1371        assert_eq!(fm.current(), Some(1));
1372    }
1373
1374    // --- FocusManager construction ---
1375
1376    #[test]
1377    fn new_manager_has_no_focus() {
1378        let fm = FocusManager::new();
1379        assert_eq!(fm.current(), None);
1380        assert!(!fm.is_trapped());
1381    }
1382
1383    #[test]
1384    fn default_and_new_are_equivalent() {
1385        let a = FocusManager::new();
1386        let b = FocusManager::default();
1387        assert_eq!(a.current(), b.current());
1388        assert_eq!(a.is_trapped(), b.is_trapped());
1389        assert_eq!(a.host_focused(), b.host_focused());
1390    }
1391
1392    // --- is_focused ---
1393
1394    #[test]
1395    fn is_focused_returns_true_for_current() {
1396        let mut fm = FocusManager::new();
1397        fm.graph_mut().insert(node(1, 0));
1398        fm.focus(1);
1399        assert!(fm.is_focused(1));
1400        assert!(!fm.is_focused(2));
1401    }
1402
1403    #[test]
1404    fn is_focused_returns_false_when_no_focus() {
1405        let fm = FocusManager::new();
1406        assert!(!fm.is_focused(1));
1407    }
1408
1409    // --- focus edge cases ---
1410
1411    #[test]
1412    fn focus_non_existent_node_returns_none() {
1413        let mut fm = FocusManager::new();
1414        assert!(fm.focus(999).is_none());
1415        assert_eq!(fm.current(), None);
1416    }
1417
1418    #[test]
1419    fn focus_already_focused_returns_same_id() {
1420        let mut fm = FocusManager::new();
1421        fm.graph_mut().insert(node(1, 0));
1422        fm.focus(1);
1423        // Focusing same node returns current (early exit)
1424        assert_eq!(fm.focus(1), Some(1));
1425        assert_eq!(fm.current(), Some(1));
1426    }
1427
1428    // --- blur ---
1429
1430    #[test]
1431    fn blur_when_no_focus_returns_none() {
1432        let mut fm = FocusManager::new();
1433        assert_eq!(fm.blur(), None);
1434    }
1435
1436    #[test]
1437    fn blur_generates_focus_lost_event() {
1438        let mut fm = FocusManager::new();
1439        fm.graph_mut().insert(node(1, 0));
1440        fm.focus(1);
1441        let _ = fm.take_focus_event(); // clear
1442        fm.blur();
1443        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1444    }
1445
1446    // --- focus_first / focus_last ---
1447
1448    #[test]
1449    fn focus_first_selects_lowest_tab_index() {
1450        let mut fm = FocusManager::new();
1451        fm.graph_mut().insert(node(3, 2));
1452        fm.graph_mut().insert(node(1, 0));
1453        fm.graph_mut().insert(node(2, 1));
1454
1455        assert!(fm.focus_first());
1456        assert_eq!(fm.current(), Some(1));
1457    }
1458
1459    #[test]
1460    fn focus_last_selects_highest_tab_index() {
1461        let mut fm = FocusManager::new();
1462        fm.graph_mut().insert(node(1, 0));
1463        fm.graph_mut().insert(node(2, 1));
1464        fm.graph_mut().insert(node(3, 2));
1465
1466        assert!(fm.focus_last());
1467        assert_eq!(fm.current(), Some(3));
1468    }
1469
1470    #[test]
1471    fn focus_first_on_empty_graph_returns_false() {
1472        let mut fm = FocusManager::new();
1473        assert!(!fm.focus_first());
1474    }
1475
1476    #[test]
1477    fn focus_last_on_empty_graph_returns_false() {
1478        let mut fm = FocusManager::new();
1479        assert!(!fm.focus_last());
1480    }
1481
1482    // --- Tab wrapping ---
1483
1484    #[test]
1485    fn focus_next_wraps_at_end() {
1486        let mut fm = FocusManager::new();
1487        fm.graph_mut().insert(node(1, 0));
1488        fm.graph_mut().insert(node(2, 1));
1489
1490        fm.focus(2);
1491        assert!(fm.focus_next()); // wraps
1492        assert_eq!(fm.current(), Some(1));
1493    }
1494
1495    #[test]
1496    fn focus_prev_wraps_at_start() {
1497        let mut fm = FocusManager::new();
1498        fm.graph_mut().insert(node(1, 0));
1499        fm.graph_mut().insert(node(2, 1));
1500
1501        fm.focus(1);
1502        assert!(fm.focus_prev()); // wraps
1503        assert_eq!(fm.current(), Some(2));
1504    }
1505
1506    #[test]
1507    fn focus_next_with_no_current_selects_first() {
1508        let mut fm = FocusManager::new();
1509        fm.graph_mut().insert(node(1, 0));
1510        fm.graph_mut().insert(node(2, 1));
1511
1512        assert!(fm.focus_next());
1513        assert_eq!(fm.current(), Some(1));
1514    }
1515
1516    #[test]
1517    fn focus_prev_with_no_current_selects_last() {
1518        let mut fm = FocusManager::new();
1519        fm.graph_mut().insert(node(1, 0));
1520        fm.graph_mut().insert(node(2, 1));
1521
1522        assert!(fm.focus_prev());
1523        assert_eq!(fm.current(), Some(2));
1524    }
1525
1526    #[test]
1527    fn focus_prev_with_stale_current_selects_last() {
1528        let mut fm = FocusManager::new();
1529        fm.graph_mut().insert(node(1, 0));
1530        fm.graph_mut().insert(node(2, 1));
1531        fm.graph_mut().insert(node(3, 2));
1532
1533        fm.focus(2);
1534        let _ = fm.graph_mut().remove(2);
1535
1536        assert!(fm.focus_prev());
1537        assert_eq!(fm.current(), Some(3));
1538    }
1539
1540    #[test]
1541    fn focus_next_on_empty_returns_false() {
1542        let mut fm = FocusManager::new();
1543        assert!(!fm.focus_next());
1544    }
1545
1546    // --- History ---
1547
1548    #[test]
1549    fn focus_back_on_empty_history_returns_false() {
1550        let mut fm = FocusManager::new();
1551        fm.graph_mut().insert(node(1, 0));
1552        fm.focus(1);
1553        assert!(!fm.focus_back());
1554    }
1555
1556    #[test]
1557    fn clear_history_prevents_back() {
1558        let mut fm = FocusManager::new();
1559        fm.graph_mut().insert(node(1, 0));
1560        fm.graph_mut().insert(node(2, 1));
1561
1562        fm.focus(1);
1563        fm.focus(2);
1564        fm.clear_history();
1565        assert!(!fm.focus_back());
1566        assert_eq!(fm.current(), Some(2));
1567    }
1568
1569    #[test]
1570    fn focus_back_skips_removed_nodes() {
1571        let mut fm = FocusManager::new();
1572        fm.graph_mut().insert(node(1, 0));
1573        fm.graph_mut().insert(node(2, 1));
1574        fm.graph_mut().insert(node(3, 2));
1575
1576        fm.focus(1);
1577        fm.focus(2);
1578        fm.focus(3);
1579
1580        // Remove node 2 from graph
1581        let _ = fm.graph_mut().remove(2);
1582
1583        // focus_back should skip 2 and go to 1
1584        assert!(fm.focus_back());
1585        assert_eq!(fm.current(), Some(1));
1586    }
1587
1588    // --- Groups ---
1589
1590    #[test]
1591    fn create_group_filters_non_focusable() {
1592        let mut fm = FocusManager::new();
1593        fm.graph_mut().insert(node(1, 0));
1594        // Node 999 doesn't exist in the graph
1595        fm.create_group(1, vec![1, 999]);
1596
1597        let group = fm.groups.get(&1).unwrap();
1598        assert_eq!(group.members.len(), 1);
1599        assert!(group.contains(1));
1600    }
1601
1602    #[test]
1603    fn add_to_group_creates_group_if_needed() {
1604        let mut fm = FocusManager::new();
1605        fm.graph_mut().insert(node(1, 0));
1606        fm.add_to_group(42, 1);
1607        assert!(fm.groups.contains_key(&42));
1608        assert!(fm.groups.get(&42).unwrap().contains(1));
1609    }
1610
1611    #[test]
1612    fn add_to_group_skips_unfocusable() {
1613        let mut fm = FocusManager::new();
1614        fm.add_to_group(1, 999); // 999 not in graph
1615        // Group may or may not exist, but if it does, 999 is not in it
1616        if let Some(group) = fm.groups.get(&1) {
1617            assert!(!group.contains(999));
1618        }
1619    }
1620
1621    #[test]
1622    fn add_to_group_no_duplicates() {
1623        let mut fm = FocusManager::new();
1624        fm.graph_mut().insert(node(1, 0));
1625        fm.add_to_group(1, 1);
1626        fm.add_to_group(1, 1);
1627        assert_eq!(fm.groups.get(&1).unwrap().members.len(), 1);
1628    }
1629
1630    #[test]
1631    fn remove_from_group() {
1632        let mut fm = FocusManager::new();
1633        fm.graph_mut().insert(node(1, 0));
1634        fm.graph_mut().insert(node(2, 1));
1635        fm.create_group(1, vec![1, 2]);
1636        fm.remove_from_group(1, 1);
1637        assert!(!fm.groups.get(&1).unwrap().contains(1));
1638        assert!(fm.groups.get(&1).unwrap().contains(2));
1639    }
1640
1641    #[test]
1642    fn removing_focused_member_from_active_trap_refocuses_remaining_member() {
1643        let mut fm = FocusManager::new();
1644        fm.graph_mut().insert(node(1, 0));
1645        fm.graph_mut().insert(node(2, 1));
1646        fm.graph_mut().insert(node(3, 2));
1647        fm.create_group(1, vec![1, 2]);
1648
1649        fm.focus(2);
1650        assert!(fm.push_trap(1));
1651        assert_eq!(fm.current(), Some(2));
1652
1653        fm.remove_from_group(1, 2);
1654        assert_eq!(fm.current(), Some(1));
1655        assert!(fm.is_trapped());
1656        assert!(fm.focus(3).is_none());
1657        assert_eq!(fm.current(), Some(1));
1658    }
1659
1660    #[test]
1661    fn removing_last_member_from_active_trap_allows_focus_escape() {
1662        let mut fm = FocusManager::new();
1663        fm.graph_mut().insert(node(1, 0));
1664        fm.graph_mut().insert(node(2, 1));
1665        fm.create_group(1, vec![1]);
1666
1667        fm.focus(1);
1668        assert!(fm.push_trap(1));
1669        assert!(fm.is_trapped());
1670
1671        fm.remove_from_group(1, 1);
1672        assert!(!fm.is_trapped());
1673        assert_eq!(fm.current(), Some(1));
1674        assert_eq!(fm.focus(2), Some(1));
1675        assert_eq!(fm.current(), Some(2));
1676    }
1677
1678    #[test]
1679    fn removing_active_inner_trap_member_falls_back_to_outer_trap() {
1680        let mut fm = FocusManager::new();
1681        fm.graph_mut().insert(node(1, 0));
1682        fm.graph_mut().insert(node(2, 1));
1683        fm.graph_mut().insert(node(3, 2));
1684        fm.create_group(10, vec![1, 2]);
1685        fm.create_group(20, vec![3]);
1686
1687        fm.focus(1);
1688        assert!(fm.push_trap(10));
1689        assert!(fm.push_trap(20));
1690        assert_eq!(fm.current(), Some(3));
1691
1692        fm.remove_from_group(20, 3);
1693        assert!(fm.is_trapped());
1694        assert_eq!(fm.current(), Some(1));
1695        assert!(fm.focus(3).is_none());
1696        assert_eq!(fm.focus(2), Some(1));
1697        assert_eq!(fm.current(), Some(2));
1698    }
1699
1700    #[test]
1701    fn adding_member_to_invalidated_trap_restores_confinement() {
1702        let mut fm = FocusManager::new();
1703        fm.graph_mut().insert(node(1, 0));
1704        fm.graph_mut().insert(node(2, 1));
1705        fm.create_group(1, vec![1]);
1706
1707        fm.focus(1);
1708        assert!(fm.push_trap(1));
1709
1710        fm.remove_from_group(1, 1);
1711        assert!(!fm.is_trapped());
1712
1713        fm.add_to_group(1, 2);
1714        assert!(fm.is_trapped());
1715        assert_eq!(fm.current(), Some(2));
1716        assert!(fm.focus(1).is_none());
1717    }
1718
1719    #[test]
1720    fn remove_from_nonexistent_group_is_noop() {
1721        let mut fm = FocusManager::new();
1722        fm.remove_from_group(999, 1); // should not panic
1723    }
1724
1725    #[test]
1726    fn remove_group_deletes_group() {
1727        let mut fm = FocusManager::new();
1728        fm.graph_mut().insert(node(1, 0));
1729        fm.create_group(42, vec![1]);
1730
1731        fm.remove_group(42);
1732        assert!(!fm.groups.contains_key(&42));
1733    }
1734
1735    #[test]
1736    fn remove_group_from_active_inner_trap_falls_back_to_outer_trap() {
1737        let mut fm = FocusManager::new();
1738        fm.graph_mut().insert(node(1, 0));
1739        fm.graph_mut().insert(node(2, 1));
1740        fm.graph_mut().insert(node(3, 2));
1741        fm.create_group(10, vec![1, 2]);
1742        fm.create_group(20, vec![3]);
1743
1744        fm.focus(1);
1745        assert!(fm.push_trap(10));
1746        assert!(fm.push_trap(20));
1747        assert_eq!(fm.current(), Some(3));
1748
1749        fm.remove_group(20);
1750        assert!(fm.is_trapped());
1751        assert_eq!(fm.current(), Some(1));
1752        assert!(fm.focus(3).is_none());
1753    }
1754
1755    #[test]
1756    fn remove_group_clears_stale_trap_entries() {
1757        let mut fm = FocusManager::new();
1758        fm.graph_mut().insert(node(1, 0));
1759        fm.create_group(10, vec![1]);
1760
1761        fm.focus(1);
1762        assert!(fm.push_trap(10));
1763        assert!(fm.is_trapped());
1764
1765        fm.remove_group(10);
1766        assert!(!fm.is_trapped());
1767        assert!(!fm.pop_trap());
1768    }
1769
1770    #[test]
1771    fn remove_group_blurs_invalid_current_when_no_fallback_exists() {
1772        let mut fm = FocusManager::new();
1773        fm.graph_mut().insert(node(1, 0));
1774        fm.create_group(10, vec![1]);
1775        fm.focus(1);
1776
1777        let _ = fm.graph_mut().remove(1);
1778        fm.remove_group(10);
1779
1780        assert_eq!(fm.current(), None);
1781        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1782    }
1783
1784    // --- FocusGroup ---
1785
1786    #[test]
1787    fn focus_group_with_wrap() {
1788        let group = FocusGroup::new(1, vec![1, 2]).with_wrap(false);
1789        assert!(!group.wrap);
1790    }
1791
1792    #[test]
1793    fn focus_group_default_wraps() {
1794        let group = FocusGroup::new(1, vec![]);
1795        assert!(group.wrap);
1796    }
1797
1798    // --- Trap stack ---
1799
1800    #[test]
1801    fn nested_traps() {
1802        let mut fm = FocusManager::new();
1803        fm.graph_mut().insert(node(1, 0));
1804        fm.graph_mut().insert(node(2, 1));
1805        fm.graph_mut().insert(node(3, 2));
1806        fm.graph_mut().insert(node(4, 3));
1807
1808        fm.create_group(10, vec![1, 2]);
1809        fm.create_group(20, vec![3, 4]);
1810
1811        fm.focus(1);
1812        fm.push_trap(10);
1813        assert!(fm.is_trapped());
1814
1815        fm.push_trap(20);
1816        // Should be in inner trap, focused on first of group 20
1817        assert_eq!(fm.current(), Some(3));
1818
1819        // Pop inner trap
1820        fm.pop_trap();
1821        // Should still be trapped (in group 10)
1822        assert!(fm.is_trapped());
1823
1824        // Pop outer trap
1825        fm.pop_trap();
1826        assert!(!fm.is_trapped());
1827    }
1828
1829    #[test]
1830    fn trap_push_pop_does_not_pollute_focus_history() {
1831        let mut fm = FocusManager::new();
1832        fm.graph_mut().insert(node(1, 0));
1833        fm.graph_mut().insert(node(2, 1));
1834        fm.graph_mut().insert(node(3, 2));
1835        fm.create_group(10, vec![2]);
1836
1837        fm.focus(1);
1838        fm.focus(3);
1839        assert_eq!(fm.current(), Some(3));
1840
1841        assert!(fm.push_trap(10));
1842        assert_eq!(fm.current(), Some(2));
1843
1844        assert!(fm.pop_trap());
1845        assert_eq!(fm.current(), Some(3));
1846
1847        assert!(fm.focus_back());
1848        assert_eq!(fm.current(), Some(1));
1849        assert!(!fm.focus_back());
1850    }
1851
1852    #[test]
1853    fn pop_trap_restores_none_when_modal_opened_without_focus() {
1854        let mut fm = FocusManager::new();
1855        fm.graph_mut().insert(node(1, 0));
1856        fm.create_group(10, vec![1]);
1857
1858        assert!(fm.push_trap(10));
1859        assert_eq!(fm.current(), Some(1));
1860
1861        assert!(fm.pop_trap());
1862        assert_eq!(fm.current(), None);
1863        assert_eq!(fm.take_focus_event(), Some(FocusEvent::FocusLost { id: 1 }));
1864    }
1865
1866    #[test]
1867    fn pop_trap_on_empty_returns_false() {
1868        let mut fm = FocusManager::new();
1869        assert!(!fm.pop_trap());
1870    }
1871
1872    #[test]
1873    fn push_trap_rejects_missing_group() {
1874        let mut fm = FocusManager::new();
1875        fm.graph_mut().insert(node(1, 0));
1876        fm.focus(1);
1877
1878        // Group 999 doesn't exist — push_trap must refuse.
1879        assert!(!fm.push_trap(999));
1880        assert!(!fm.is_trapped());
1881        // Focus should remain unchanged (no deadlock).
1882        assert_eq!(fm.current(), Some(1));
1883    }
1884
1885    #[test]
1886    fn push_trap_rejects_empty_group() {
1887        let mut fm = FocusManager::new();
1888        fm.graph_mut().insert(node(1, 0));
1889        fm.focus(1);
1890
1891        // Create group with no members.
1892        fm.create_group(42, vec![]);
1893        assert!(!fm.push_trap(42));
1894        assert!(!fm.is_trapped());
1895        // Focus should remain unchanged (no deadlock).
1896        assert_eq!(fm.current(), Some(1));
1897    }
1898
1899    #[test]
1900    fn push_trap_autofocuses_negative_tabindex_member_when_group_has_no_tabbable_nodes() {
1901        let mut fm = FocusManager::new();
1902        fm.graph_mut().insert(node(1, 0));
1903        fm.graph_mut().insert(node(2, -1));
1904        fm.focus(1);
1905
1906        fm.create_group(42, vec![2]);
1907        assert!(fm.push_trap(42));
1908        assert!(fm.is_trapped());
1909        assert_eq!(fm.current(), Some(2));
1910    }
1911
1912    #[test]
1913    fn push_trap_blurred_restores_negative_tabindex_member_on_focus_gain() {
1914        let mut fm = FocusManager::new();
1915        fm.graph_mut().insert(node(1, 0));
1916        fm.graph_mut().insert(node(2, -1));
1917        fm.focus(1);
1918        assert!(fm.apply_host_focus(false));
1919
1920        fm.create_group(42, vec![2]);
1921        assert!(fm.push_trap(42));
1922        assert_eq!(fm.current(), None);
1923
1924        assert!(fm.apply_host_focus(true));
1925        assert_eq!(fm.current(), Some(2));
1926    }
1927
1928    #[test]
1929    fn push_trap_retargets_when_current_group_member_becomes_unfocusable() {
1930        let mut fm = FocusManager::new();
1931        fm.graph_mut().insert(node(1, 0));
1932        fm.graph_mut().insert(node(2, 1));
1933        fm.focus(1);
1934        fm.create_group(10, vec![1, 2]);
1935
1936        fm.graph_mut().insert(node(1, 0).with_focusable(false));
1937
1938        assert!(fm.push_trap(10));
1939        assert_eq!(fm.current(), Some(2));
1940    }
1941
1942    // --- Focus events ---
1943
1944    #[test]
1945    fn take_focus_event_clears_it() {
1946        let mut fm = FocusManager::new();
1947        fm.graph_mut().insert(node(1, 0));
1948        fm.focus(1);
1949
1950        assert!(fm.take_focus_event().is_some());
1951        assert!(fm.take_focus_event().is_none());
1952    }
1953
1954    #[test]
1955    fn focus_event_accessor() {
1956        let mut fm = FocusManager::new();
1957        fm.graph_mut().insert(node(1, 0));
1958        fm.focus(1);
1959
1960        assert_eq!(fm.focus_event(), Some(&FocusEvent::FocusGained { id: 1 }));
1961    }
1962
1963    // --- Navigate with no current ---
1964
1965    #[test]
1966    fn navigate_direction_with_no_current_returns_false() {
1967        let mut fm = FocusManager::new();
1968        fm.graph_mut().insert(spatial_node(1, 0, 0, 10, 3, 0));
1969        assert!(!fm.navigate(NavDirection::Right));
1970    }
1971
1972    // --- graph accessors ---
1973
1974    #[test]
1975    fn graph_accessor_returns_reference() {
1976        let mut fm = FocusManager::new();
1977        fm.graph_mut().insert(node(1, 0));
1978        assert!(fm.graph().get(1).is_some());
1979    }
1980
1981    // --- Focus indicator ---
1982
1983    #[test]
1984    fn default_indicator_is_reverse() {
1985        let fm = FocusManager::new();
1986        assert!(fm.indicator().is_visible());
1987        assert_eq!(
1988            fm.indicator().kind(),
1989            crate::focus::FocusIndicatorKind::StyleOverlay
1990        );
1991    }
1992
1993    #[test]
1994    fn set_indicator() {
1995        let mut fm = FocusManager::new();
1996        fm.set_indicator(crate::focus::FocusIndicator::underline());
1997        assert_eq!(
1998            fm.indicator().kind(),
1999            crate::focus::FocusIndicatorKind::Underline
2000        );
2001    }
2002
2003    // --- Focus change count ---
2004
2005    #[test]
2006    fn focus_change_count_increments() {
2007        let mut fm = FocusManager::new();
2008        fm.graph_mut().insert(node(1, 0));
2009        fm.graph_mut().insert(node(2, 1));
2010
2011        assert_eq!(fm.focus_change_count(), 0);
2012
2013        fm.focus(1);
2014        assert_eq!(fm.focus_change_count(), 1);
2015
2016        fm.focus(2);
2017        assert_eq!(fm.focus_change_count(), 2);
2018
2019        fm.blur();
2020        assert_eq!(fm.focus_change_count(), 3);
2021    }
2022
2023    #[test]
2024    fn focus_change_count_zero_on_no_op() {
2025        let mut fm = FocusManager::new();
2026        fm.graph_mut().insert(node(1, 0));
2027        fm.focus(1);
2028        assert_eq!(fm.focus_change_count(), 1);
2029
2030        // Focusing the same widget is a no-op
2031        fm.focus(1);
2032        assert_eq!(fm.focus_change_count(), 1);
2033    }
2034
2035    #[test]
2036    fn focus_back_increments_focus_change_count() {
2037        let mut fm = FocusManager::new();
2038        fm.graph_mut().insert(node(1, 0));
2039        fm.graph_mut().insert(node(2, 1));
2040
2041        fm.focus(1);
2042        fm.focus(2);
2043        assert_eq!(fm.focus_change_count(), 2);
2044
2045        assert!(fm.focus_back());
2046        assert_eq!(fm.current(), Some(1));
2047        assert_eq!(fm.focus_change_count(), 3);
2048    }
2049
2050    #[test]
2051    fn sync_to_frame_enforces_single_focus_truth_and_modal_trap_restoration() {
2052        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
2053        use ftui_a11y::tree::A11yTreeBuilder;
2054        use ftui_render::frame::Frame;
2055        use ftui_render::grapheme_pool::GraphemePool;
2056
2057        let mut fm = FocusManager::new();
2058        fm.graph_mut().insert(node(10, 0));
2059        fm.graph_mut().insert(node(20, 1));
2060        fm.graph_mut().insert(node(30, 2));
2061        fm.create_group(1, vec![30]);
2062        fm.focus(10);
2063
2064        let build_frame_tree = |fm: &FocusManager| {
2065            let mut pool = GraphemePool::new();
2066            let mut builder = A11yTreeBuilder::new();
2067            {
2068                let mut frame = Frame::new(40, 10, &mut pool);
2069                frame.set_a11y(&mut builder);
2070                fm.sync_to_frame(&mut frame);
2071                // Even if widget 20 claims local focus, FocusManager is authoritative.
2072                let stale_focused = A11yState {
2073                    focused: true,
2074                    ..Default::default()
2075                };
2076                frame.push_a11y(A11yNodeInfo::new(
2077                    10,
2078                    A11yRole::TextInput,
2079                    Rect::new(0, 0, 10, 1),
2080                ));
2081                frame.push_a11y(
2082                    A11yNodeInfo::new(20, A11yRole::TextInput, Rect::new(0, 1, 10, 1))
2083                        .with_state(stale_focused),
2084                );
2085                frame.push_a11y(A11yNodeInfo::new(
2086                    30,
2087                    A11yRole::Button,
2088                    Rect::new(0, 2, 10, 1),
2089                ));
2090                frame.finish_a11y();
2091            }
2092            builder.build()
2093        };
2094
2095        let tree1 = build_frame_tree(&fm);
2096        assert_eq!(tree1.focused().map(|n| n.id), Some(10));
2097        assert!(tree1.node(10).unwrap().state.focused);
2098        assert!(!tree1.node(20).unwrap().state.focused);
2099        assert!(!tree1.node(30).unwrap().state.focused);
2100
2101        // Push modal trap on group 1 (widget 30) -> accessibility focus moves to 30.
2102        assert!(fm.push_trap(1));
2103        let tree_trapped = build_frame_tree(&fm);
2104        assert_eq!(tree_trapped.focused().map(|n| n.id), Some(30));
2105        assert!(!tree_trapped.node(10).unwrap().state.focused);
2106        assert!(!tree_trapped.node(20).unwrap().state.focused);
2107        assert!(tree_trapped.node(30).unwrap().state.focused);
2108
2109        // Pop modal trap -> accessibility focus restores to 10.
2110        assert!(fm.pop_trap());
2111        let tree_restored = build_frame_tree(&fm);
2112        assert_eq!(tree_restored.focused().map(|n| n.id), Some(10));
2113        assert!(tree_restored.node(10).unwrap().state.focused);
2114        assert!(!tree_restored.node(30).unwrap().state.focused);
2115
2116        // Host window loses focus -> accessibility tree focus clears completely.
2117        assert!(fm.apply_host_focus(false));
2118        let tree_blurred = build_frame_tree(&fm);
2119        assert_eq!(tree_blurred.focused().map(|n| n.id), None);
2120        assert!(!tree_blurred.node(10).unwrap().state.focused);
2121        assert!(!tree_blurred.node(20).unwrap().state.focused);
2122        assert!(!tree_blurred.node(30).unwrap().state.focused);
2123    }
2124
2125    #[test]
2126    fn sync_to_frame_delegates_to_focused_descendant_of_composite_container() {
2127        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
2128        use ftui_a11y::tree::A11yTreeBuilder;
2129        use ftui_render::frame::Frame;
2130        use ftui_render::grapheme_pool::GraphemePool;
2131
2132        let mut fm = FocusManager::new();
2133        fm.graph_mut().insert(node(100, 0));
2134        fm.focus(100);
2135
2136        let mut pool = GraphemePool::new();
2137        let mut builder = A11yTreeBuilder::new();
2138        {
2139            let mut frame = Frame::new(40, 10, &mut pool);
2140            frame.set_a11y(&mut builder);
2141            fm.sync_to_frame(&mut frame);
2142            let focused_state = A11yState {
2143                focused: true,
2144                selected: true,
2145                ..Default::default()
2146            };
2147            frame.with_a11y_scope(
2148                A11yNodeInfo::new(100, A11yRole::List, Rect::new(0, 0, 20, 4)),
2149                |f| {
2150                    f.push_a11y(A11yNodeInfo::new(
2151                        101,
2152                        A11yRole::ListItem,
2153                        Rect::new(0, 0, 20, 1),
2154                    ));
2155                    f.push_a11y(
2156                        A11yNodeInfo::new(102, A11yRole::ListItem, Rect::new(0, 1, 20, 1))
2157                            .with_state(focused_state),
2158                    );
2159                },
2160            );
2161            frame.finish_a11y();
2162        }
2163        let tree = builder.build();
2164        assert_eq!(tree.focused().map(|n| n.id), Some(102));
2165        assert!(!tree.node(100).unwrap().state.focused);
2166        assert!(!tree.node(101).unwrap().state.focused);
2167        assert!(tree.node(102).unwrap().state.focused);
2168    }
2169}