sim_logic/ui/focus.rs
1//! Explicit keyboard focus without hidden input dispatch, layout, or widget storage.
2
3use std::{error::Error, fmt};
4
5/// One caller-accepted UI navigation action. Feed only fresh, uncancelled presses.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum FocusCommand {
8 /// Focus the next eligible target, wrapping at the end.
9 Next,
10 /// Focus the previous eligible target, wrapping at the start.
11 Previous,
12 /// Focus the first eligible target.
13 First,
14 /// Focus the last eligible target.
15 Last,
16 /// Report activation of the current eligible target; dispatch remains caller-owned.
17 Activate,
18 /// Clear focus, for example after input focus loss.
19 Clear,
20}
21
22/// A rejected focus operation; previous scope and focused identity are unchanged.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FocusError {
25 /// The supplied eligible order exceeds the configured maximum.
26 TargetLimitExceeded,
27 /// Repeated target IDs make navigation ambiguous.
28 DuplicateTarget,
29 /// An explicit focus request names an ineligible target.
30 IneligibleTarget,
31}
32impl fmt::Display for FocusError {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 write!(f, "invalid keyboard focus request: {self:?}")
35 }
36}
37impl Error for FocusError {}
38
39/// Explicit focus/activation output. No runtime input is consumed by the helper.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct FocusOutcome<T> {
42 /// Current eligible focus after this operation.
43 pub focused: Option<T>,
44 /// Target activated by this command, if any.
45 pub activated: Option<T>,
46}
47
48/// An allocation-free focus controller for one caller-selected modal scope.
49///
50/// The caller supplies a bounded, ordered slice of unique eligible target IDs on
51/// every operation. Disabled/hidden targets must be omitted. Changing scope or
52/// removing the current target clears focus before interpreting the command;
53/// activation never silently moves to another target. Use generation-qualified
54/// entity IDs, or clear/recreate the controller when a World is replaced.
55///
56/// This helper registers no systems and reads no keys. The application chooses
57/// Tab/Shift-Tab/arrow bindings and routes each accepted action exactly once.
58/// Equality is caller code. Validation costs O(n^2) comparisons, bounded by the
59/// configured target limit; navigation is O(n), storage is constant, no heap work.
60#[derive(Debug)]
61pub struct KeyboardFocus<T: Copy + Eq, S: Copy + Eq> {
62 focused: Option<T>,
63 scope: Option<S>,
64 max_targets: usize,
65}
66
67impl<T: Copy + Eq, S: Copy + Eq> KeyboardFocus<T, S> {
68 /// Creates an empty controller with an explicit eligible-target cap.
69 pub const fn new(max_targets: usize) -> Self {
70 Self {
71 focused: None,
72 scope: None,
73 max_targets,
74 }
75 }
76 /// Returns focused identity; call synchronize after changing eligibility.
77 pub const fn focused(&self) -> Option<T> {
78 self.focused
79 }
80 /// Returns the last explicitly supplied modal scope.
81 pub const fn scope(&self) -> Option<S> {
82 self.scope
83 }
84 /// Clears focus without changing the caller's active scope.
85 pub fn clear(&mut self) {
86 self.focused = None;
87 }
88
89 /// Reconciles scope and eligibility without choosing or activating a new target.
90 pub fn synchronize(&mut self, scope: S, eligible: &[T]) -> Result<(), FocusError> {
91 self.validate(eligible)?;
92 if self.scope != Some(scope)
93 || self
94 .focused
95 .is_some_and(|target| !eligible.contains(&target))
96 {
97 self.focused = None;
98 }
99 self.scope = Some(scope);
100 Ok(())
101 }
102
103 /// Sets an eligible focus explicitly, for example after pointer selection.
104 /// Invalid target/order/limits preserve both old scope and old focus.
105 pub fn set_focused(
106 &mut self,
107 scope: S,
108 eligible: &[T],
109 target: Option<T>,
110 ) -> Result<(), FocusError> {
111 self.validate(eligible)?;
112 if target.is_some_and(|target| !eligible.contains(&target)) {
113 return Err(FocusError::IneligibleTarget);
114 }
115 self.scope = Some(scope);
116 self.focused = target;
117 Ok(())
118 }
119
120 /// Applies one caller-approved command after reconciling the active modal scope.
121 /// Empty orders clear focus. Failed validation performs no mutation.
122 pub fn process(
123 &mut self,
124 scope: S,
125 eligible: &[T],
126 command: FocusCommand,
127 ) -> Result<FocusOutcome<T>, FocusError> {
128 self.synchronize(scope, eligible)?;
129 let index = self
130 .focused
131 .and_then(|target| eligible.iter().position(|item| *item == target));
132 let mut activated = None;
133 match command {
134 FocusCommand::Clear => self.focused = None,
135 FocusCommand::Activate => activated = self.focused,
136 FocusCommand::First => self.focused = eligible.first().copied(),
137 FocusCommand::Last => self.focused = eligible.last().copied(),
138 FocusCommand::Next if !eligible.is_empty() => {
139 self.focused = eligible
140 .get(index.map_or(0, |index| (index + 1) % eligible.len()))
141 .copied();
142 }
143 FocusCommand::Previous if !eligible.is_empty() => {
144 self.focused = eligible
145 .get(
146 index
147 .filter(|index| *index > 0)
148 .map_or(eligible.len() - 1, |index| index - 1),
149 )
150 .copied();
151 }
152 FocusCommand::Next | FocusCommand::Previous => {}
153 }
154 Ok(FocusOutcome {
155 focused: self.focused,
156 activated,
157 })
158 }
159
160 fn validate(&self, eligible: &[T]) -> Result<(), FocusError> {
161 if eligible.len() > self.max_targets {
162 return Err(FocusError::TargetLimitExceeded);
163 }
164 for (index, target) in eligible.iter().enumerate() {
165 if eligible[..index].contains(target) {
166 return Err(FocusError::DuplicateTarget);
167 }
168 }
169 Ok(())
170 }
171}