cranpose-ui 0.0.60

UI primitives for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Focus modifier nodes for Cranpose.
//!
//! This module implements focus management that mirrors Jetpack Compose's
//! focus system. Focus nodes participate in focus traversal, track focus state,
//! and integrate with the modifier chain lifecycle.

use std::cell::Cell;
use std::hash::{Hash, Hasher};
use std::rc::Rc;

use cranpose_foundation::{
    impl_focus_node, DelegatableNode, FocusNode, FocusState, ModifierNode, ModifierNodeContext,
    ModifierNodeElement, NodeCapabilities, NodeState,
};

/// Focus direction for navigation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FocusDirection {
    /// Enter focus from outside.
    Enter,
    /// Exit focus to outside.
    Exit,
    /// Move to next focusable.
    Next,
    /// Move to previous focusable.
    Previous,
    /// Move up (2D navigation).
    Up,
    /// Move down (2D navigation).
    Down,
    /// Move left (2D navigation).
    Left,
    /// Move right (2D navigation).
    Right,
}

/// A focus target node that can receive focus.
///
/// This is the core building block for focusable components. Each focus target
/// tracks its own focus state and participates in the focus traversal system.
pub struct FocusTargetNode {
    state: NodeState,
    focus_state: Cell<FocusState>,
    on_focus_changed: Option<Rc<dyn Fn(FocusState)>>,
}

impl FocusTargetNode {
    pub fn new() -> Self {
        Self {
            state: NodeState::new(),
            focus_state: Cell::new(FocusState::Inactive),
            on_focus_changed: None,
        }
    }

    pub fn with_callback<F>(callback: F) -> Self
    where
        F: Fn(FocusState) + 'static,
    {
        Self {
            state: NodeState::new(),
            focus_state: Cell::new(FocusState::Inactive),
            on_focus_changed: Some(Rc::new(callback)),
        }
    }

    /// Sets the focus state for this node.
    pub fn set_focus_state(&self, state: FocusState) {
        let old_state = self.focus_state.get();
        if old_state != state {
            self.focus_state.set(state);
            if let Some(callback) = &self.on_focus_changed {
                callback(state);
            }
        }
    }

    /// Clears focus from this node.
    pub fn clear_focus(&self) {
        self.set_focus_state(FocusState::Inactive);
    }
}

impl Default for FocusTargetNode {
    fn default() -> Self {
        Self::new()
    }
}

impl DelegatableNode for FocusTargetNode {
    fn node_state(&self) -> &NodeState {
        &self.state
    }
}

impl ModifierNode for FocusTargetNode {
    fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
        self.state.set_attached(true);
    }

    fn on_detach(&mut self) {
        self.state.set_attached(false);
        self.clear_focus();
    }

    // Capability-driven implementation using helper macro
    impl_focus_node!();
}

impl FocusNode for FocusTargetNode {
    fn focus_state(&self) -> FocusState {
        self.focus_state.get()
    }

    fn on_focus_changed(&mut self, _context: &mut dyn ModifierNodeContext, state: FocusState) {
        self.set_focus_state(state);
    }
}

/// Modifier element for focus targets.
///
/// Creates a focusable modifier that can receive and track focus.
#[derive(Clone)]
pub struct FocusTargetElement {
    on_focus_changed: Option<Rc<dyn Fn(FocusState)>>,
}

impl FocusTargetElement {
    pub fn new() -> Self {
        Self {
            on_focus_changed: None,
        }
    }

    pub fn with_callback<F>(callback: F) -> Self
    where
        F: Fn(FocusState) + 'static,
    {
        Self {
            on_focus_changed: Some(Rc::new(callback)),
        }
    }
}

impl Default for FocusTargetElement {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for FocusTargetElement {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FocusTargetElement")
            .field("has_callback", &self.on_focus_changed.is_some())
            .finish()
    }
}

impl PartialEq for FocusTargetElement {
    fn eq(&self, other: &Self) -> bool {
        // Type-based matching: compare only presence of callback, not pointer
        // Nodes are updated via update() method, preserving behavior
        self.on_focus_changed.is_some() == other.on_focus_changed.is_some()
    }
}

impl Hash for FocusTargetElement {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Consistent hash based on callback presence only
        "focus_target".hash(state);
        self.on_focus_changed.is_some().hash(state);
    }
}

impl ModifierNodeElement for FocusTargetElement {
    type Node = FocusTargetNode;

    fn create(&self) -> Self::Node {
        if let Some(callback) = &self.on_focus_changed {
            FocusTargetNode::with_callback({
                let callback = callback.clone();
                move |state| callback(state)
            })
        } else {
            FocusTargetNode::new()
        }
    }

    fn update(&self, node: &mut Self::Node) {
        node.on_focus_changed = self.on_focus_changed.clone();
    }

    fn inspector_name(&self) -> &'static str {
        "focusTarget"
    }

    fn capabilities(&self) -> NodeCapabilities {
        NodeCapabilities::FOCUS
    }

    fn always_update(&self) -> bool {
        // Always update to capture new closure if it changed
        true
    }
}

/// A focus requester node that can request focus for associated targets.
///
/// This node allows programmatic focus requests and is typically used to
/// trigger focus on specific components in response to user actions or
/// app logic.
pub struct FocusRequesterNode {
    state: NodeState,
    requester_id: usize,
}

impl FocusRequesterNode {
    pub fn new(requester_id: usize) -> Self {
        Self {
            state: NodeState::new(),
            requester_id,
        }
    }
}

impl DelegatableNode for FocusRequesterNode {
    fn node_state(&self) -> &NodeState {
        &self.state
    }
}

impl ModifierNode for FocusRequesterNode {
    fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
        self.state.set_attached(true);
    }

    fn on_detach(&mut self) {
        self.state.set_attached(false);
    }
}

/// Modifier element for focus requesters.
///
/// Creates a modifier that can be used to programmatically request focus.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FocusRequesterElement {
    requester_id: usize,
}

impl FocusRequesterElement {
    pub fn new(requester_id: usize) -> Self {
        Self { requester_id }
    }
}

impl ModifierNodeElement for FocusRequesterElement {
    type Node = FocusRequesterNode;

    fn create(&self) -> Self::Node {
        FocusRequesterNode::new(self.requester_id)
    }

    fn update(&self, node: &mut Self::Node) {
        node.requester_id = self.requester_id;
    }

    fn inspector_name(&self) -> &'static str {
        "focusRequester"
    }

    fn capabilities(&self) -> NodeCapabilities {
        NodeCapabilities::FOCUS
    }
}

/// A handle for requesting focus programmatically.
///
/// This mirrors Jetpack Compose's FocusRequester class and provides
/// an API for triggering focus changes from application code.
#[derive(Clone, Debug, Default)]
pub struct FocusRequester {
    id: usize,
}

impl FocusRequester {
    pub fn new() -> Self {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
        Self {
            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
        }
    }

    pub fn id(&self) -> usize {
        self.id
    }

    /// Requests focus for components associated with this requester.
    pub fn request_focus(&self) -> bool {
        // This will be wired up to the focus manager in the next phase
        true
    }

    /// Captures focus, preventing other components from taking focus.
    pub fn capture_focus(&self) -> bool {
        // This will be wired up to the focus manager in the next phase
        true
    }

    /// Releases captured focus.
    pub fn free_focus(&self) -> bool {
        // This will be wired up to the focus manager in the next phase
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cranpose_foundation::{BasicModifierNodeContext, ModifierNodeChain};

    #[test]
    fn focus_target_node_lifecycle() {
        let mut node = FocusTargetNode::new();
        let mut context = BasicModifierNodeContext::new();

        assert_eq!(node.focus_state(), FocusState::Inactive);
        assert!(!node.node_state().is_attached());

        node.on_attach(&mut context);
        assert!(node.node_state().is_attached());

        node.set_focus_state(FocusState::Active);
        assert_eq!(node.focus_state(), FocusState::Active);
        assert!(node.focus_state().is_focused());

        node.on_detach();
        assert!(!node.node_state().is_attached());
        assert_eq!(node.focus_state(), FocusState::Inactive);
    }

    #[test]
    fn focus_target_callback_invoked() {
        use std::cell::RefCell;
        let states = Rc::new(RefCell::new(Vec::new()));
        let states_clone = states.clone();

        let node = FocusTargetNode::with_callback(move |state| {
            states_clone.borrow_mut().push(state);
        });

        node.set_focus_state(FocusState::Active);
        node.set_focus_state(FocusState::ActiveParent);
        node.set_focus_state(FocusState::Inactive);

        let recorded = states.borrow();
        assert_eq!(recorded.len(), 3);
        assert_eq!(recorded[0], FocusState::Active);
        assert_eq!(recorded[1], FocusState::ActiveParent);
        assert_eq!(recorded[2], FocusState::Inactive);
    }

    #[test]
    fn focus_element_creates_node() {
        let element = FocusTargetElement::new();
        let node = element.create();
        assert_eq!(node.focus_state(), FocusState::Inactive);
    }

    #[test]
    fn focus_chain_integration() {
        let element = FocusTargetElement::new();
        let dyn_element = cranpose_foundation::modifier_element(element);

        let mut chain = ModifierNodeChain::new();
        let mut context = BasicModifierNodeContext::new();

        chain.update(vec![dyn_element], &mut context);

        assert_eq!(chain.len(), 1);
        assert!(chain.has_capability(NodeCapabilities::FOCUS));
    }

    #[test]
    fn focus_requester_unique_ids() {
        let req1 = FocusRequester::new();
        let req2 = FocusRequester::new();
        assert_ne!(req1.id(), req2.id());
    }

    #[test]
    fn focus_state_predicates() {
        assert!(FocusState::Active.is_focused());
        assert!(FocusState::Captured.is_focused());
        assert!(!FocusState::Inactive.is_focused());
        assert!(!FocusState::ActiveParent.is_focused());

        assert!(FocusState::Active.has_focus());
        assert!(FocusState::ActiveParent.has_focus());
        assert!(FocusState::Captured.has_focus());
        assert!(!FocusState::Inactive.has_focus());

        assert!(FocusState::Captured.is_captured());
        assert!(!FocusState::Active.is_captured());
    }
}