cranpose_ui/modifier/
focus.rs1use std::cell::Cell;
8use std::hash::{Hash, Hasher};
9use std::rc::Rc;
10
11use cranpose_foundation::{
12 impl_focus_node, DelegatableNode, FocusNode, FocusState, ModifierNode, ModifierNodeContext,
13 ModifierNodeElement, NodeCapabilities, NodeState,
14};
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub enum FocusDirection {
19 Enter,
21 Exit,
23 Next,
25 Previous,
27 Up,
29 Down,
31 Left,
33 Right,
35}
36
37pub struct FocusTargetNode {
42 state: NodeState,
43 focus_state: Cell<FocusState>,
44 on_focus_changed: Option<Rc<dyn Fn(FocusState)>>,
45}
46
47impl FocusTargetNode {
48 pub fn new() -> Self {
49 Self {
50 state: NodeState::new(),
51 focus_state: Cell::new(FocusState::Inactive),
52 on_focus_changed: None,
53 }
54 }
55
56 pub fn with_callback<F>(callback: F) -> Self
57 where
58 F: Fn(FocusState) + 'static,
59 {
60 Self {
61 state: NodeState::new(),
62 focus_state: Cell::new(FocusState::Inactive),
63 on_focus_changed: Some(Rc::new(callback)),
64 }
65 }
66
67 pub fn set_focus_state(&self, state: FocusState) {
69 let old_state = self.focus_state.get();
70 if old_state != state {
71 self.focus_state.set(state);
72 if let Some(callback) = &self.on_focus_changed {
73 callback(state);
74 }
75 }
76 }
77
78 pub fn clear_focus(&self) {
80 self.set_focus_state(FocusState::Inactive);
81 }
82}
83
84impl Default for FocusTargetNode {
85 fn default() -> Self {
86 Self::new()
87 }
88}
89
90impl DelegatableNode for FocusTargetNode {
91 fn node_state(&self) -> &NodeState {
92 &self.state
93 }
94}
95
96impl ModifierNode for FocusTargetNode {
97 fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
98 self.state.set_attached(true);
99 }
100
101 fn on_detach(&mut self) {
102 self.state.set_attached(false);
103 self.clear_focus();
104 }
105
106 impl_focus_node!();
108}
109
110impl FocusNode for FocusTargetNode {
111 fn focus_state(&self) -> FocusState {
112 self.focus_state.get()
113 }
114
115 fn on_focus_changed(&mut self, _context: &mut dyn ModifierNodeContext, state: FocusState) {
116 self.set_focus_state(state);
117 }
118}
119
120#[derive(Clone)]
124pub struct FocusTargetElement {
125 on_focus_changed: Option<Rc<dyn Fn(FocusState)>>,
126}
127
128impl FocusTargetElement {
129 pub fn new() -> Self {
130 Self {
131 on_focus_changed: None,
132 }
133 }
134
135 pub fn with_callback<F>(callback: F) -> Self
136 where
137 F: Fn(FocusState) + 'static,
138 {
139 Self {
140 on_focus_changed: Some(Rc::new(callback)),
141 }
142 }
143}
144
145impl Default for FocusTargetElement {
146 fn default() -> Self {
147 Self::new()
148 }
149}
150
151impl std::fmt::Debug for FocusTargetElement {
152 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 f.debug_struct("FocusTargetElement")
154 .field("has_callback", &self.on_focus_changed.is_some())
155 .finish()
156 }
157}
158
159impl PartialEq for FocusTargetElement {
160 fn eq(&self, other: &Self) -> bool {
161 self.on_focus_changed.is_some() == other.on_focus_changed.is_some()
164 }
165}
166
167impl Hash for FocusTargetElement {
168 fn hash<H: Hasher>(&self, state: &mut H) {
169 "focus_target".hash(state);
171 self.on_focus_changed.is_some().hash(state);
172 }
173}
174
175impl ModifierNodeElement for FocusTargetElement {
176 type Node = FocusTargetNode;
177
178 fn create(&self) -> Self::Node {
179 if let Some(callback) = &self.on_focus_changed {
180 FocusTargetNode::with_callback({
181 let callback = callback.clone();
182 move |state| callback(state)
183 })
184 } else {
185 FocusTargetNode::new()
186 }
187 }
188
189 fn update(&self, node: &mut Self::Node) {
190 node.on_focus_changed = self.on_focus_changed.clone();
191 }
192
193 fn inspector_name(&self) -> &'static str {
194 "focusTarget"
195 }
196
197 fn capabilities(&self) -> NodeCapabilities {
198 NodeCapabilities::FOCUS
199 }
200
201 fn always_update(&self) -> bool {
202 true
204 }
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210 use cranpose_foundation::{BasicModifierNodeContext, ModifierNodeChain};
211
212 #[test]
213 fn focus_target_node_lifecycle() {
214 let mut node = FocusTargetNode::new();
215 let mut context = BasicModifierNodeContext::new();
216
217 assert_eq!(node.focus_state(), FocusState::Inactive);
218 assert!(!node.node_state().is_attached());
219
220 node.on_attach(&mut context);
221 assert!(node.node_state().is_attached());
222
223 node.set_focus_state(FocusState::Active);
224 assert_eq!(node.focus_state(), FocusState::Active);
225 assert!(node.focus_state().is_focused());
226
227 node.on_detach();
228 assert!(!node.node_state().is_attached());
229 assert_eq!(node.focus_state(), FocusState::Inactive);
230 }
231
232 #[test]
233 fn focus_target_callback_invoked() {
234 use std::cell::RefCell;
235 let states = Rc::new(RefCell::new(Vec::new()));
236 let states_clone = states.clone();
237
238 let node = FocusTargetNode::with_callback(move |state| {
239 states_clone.borrow_mut().push(state);
240 });
241
242 node.set_focus_state(FocusState::Active);
243 node.set_focus_state(FocusState::ActiveParent);
244 node.set_focus_state(FocusState::Inactive);
245
246 let recorded = states.borrow();
247 assert_eq!(recorded.len(), 3);
248 assert_eq!(recorded[0], FocusState::Active);
249 assert_eq!(recorded[1], FocusState::ActiveParent);
250 assert_eq!(recorded[2], FocusState::Inactive);
251 }
252
253 #[test]
254 fn focus_element_creates_node() {
255 let element = FocusTargetElement::new();
256 let node = element.create();
257 assert_eq!(node.focus_state(), FocusState::Inactive);
258 }
259
260 #[test]
261 fn focus_chain_integration() {
262 let element = FocusTargetElement::new();
263 let dyn_element = cranpose_foundation::modifier_element(element);
264
265 let mut chain = ModifierNodeChain::new();
266 let mut context = BasicModifierNodeContext::new();
267
268 chain.update(vec![dyn_element], &mut context);
269
270 assert_eq!(chain.len(), 1);
271 assert!(chain.has_capability(NodeCapabilities::FOCUS));
272 }
273
274 #[test]
275 fn focus_state_predicates() {
276 assert!(FocusState::Active.is_focused());
277 assert!(FocusState::Captured.is_focused());
278 assert!(!FocusState::Inactive.is_focused());
279 assert!(!FocusState::ActiveParent.is_focused());
280
281 assert!(FocusState::Active.has_focus());
282 assert!(FocusState::ActiveParent.has_focus());
283 assert!(FocusState::Captured.has_focus());
284 assert!(!FocusState::Inactive.has_focus());
285
286 assert!(FocusState::Captured.is_captured());
287 assert!(!FocusState::Active.is_captured());
288 }
289}