rnk 0.17.3

A React-like declarative terminal UI framework for Rust, inspired by Ink
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Focus management hooks

use std::cell::RefCell;
use std::sync::atomic::{AtomicUsize, Ordering};

/// Unique focus ID generator
static FOCUS_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);

fn generate_focus_id() -> usize {
    FOCUS_ID_COUNTER.fetch_add(1, Ordering::SeqCst)
}

/// Focus state for a component
#[derive(Debug, Clone)]
pub struct FocusState {
    pub is_focused: bool,
}

/// Options for use_focus hook
#[derive(Debug, Clone, Default)]
pub struct UseFocusOptions {
    /// Whether this element should auto-focus on mount
    pub auto_focus: bool,
    /// Whether this element is focusable (default: true)
    pub is_active: bool,
    /// ID for this focusable element (optional, auto-generated if not provided)
    pub id: Option<String>,
}

impl UseFocusOptions {
    pub fn new() -> Self {
        Self {
            auto_focus: false,
            is_active: true,
            id: None,
        }
    }

    pub fn auto_focus(mut self) -> Self {
        self.auto_focus = true;
        self
    }

    pub fn is_active(mut self, active: bool) -> Self {
        self.is_active = active;
        self
    }

    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }
}

/// Focus manager state - tracks all focusable elements
#[derive(Debug, Clone)]
struct FocusableElement {
    id: usize,
    custom_id: Option<String>,
    is_active: bool,
}

/// Global focus manager state
#[derive(Debug, Default)]
pub struct FocusManager {
    elements: Vec<FocusableElement>,
    focused_index: Option<usize>,
}

impl FocusManager {
    pub fn new() -> Self {
        Self {
            elements: Vec::new(),
            focused_index: None,
        }
    }

    /// Register a focusable element
    pub fn register(
        &mut self,
        custom_id: Option<String>,
        is_active: bool,
        auto_focus: bool,
    ) -> usize {
        let id = generate_focus_id();
        self.elements.push(FocusableElement {
            id,
            custom_id,
            is_active,
        });

        // Auto-focus if requested and no element is currently focused
        if auto_focus && self.focused_index.is_none() && is_active {
            self.focused_index = Some(self.elements.len() - 1);
        }

        id
    }

    /// Unregister a focusable element
    pub fn unregister(&mut self, id: usize) {
        if let Some(pos) = self.elements.iter().position(|e| e.id == id) {
            self.elements.remove(pos);

            // Adjust focused index if needed
            if let Some(focused) = self.focused_index {
                if pos == focused {
                    self.focused_index = None;
                } else if pos < focused {
                    self.focused_index = Some(focused - 1);
                }
            }
        }
    }

    /// Update a focusable element's metadata
    pub fn update(
        &mut self,
        id: usize,
        custom_id: Option<String>,
        is_active: bool,
        auto_focus: bool,
    ) {
        if let Some(elem) = self.elements.iter_mut().find(|e| e.id == id) {
            elem.custom_id = custom_id;
            elem.is_active = is_active;
        }

        if auto_focus && self.focused_index.is_none() && is_active {
            if let Some(pos) = self.elements.iter().position(|e| e.id == id) {
                self.focused_index = Some(pos);
            }
        }
    }

    /// Check if an element is focused
    pub fn is_focused(&self, id: usize) -> bool {
        self.focused_index
            .and_then(|idx| self.elements.get(idx))
            .map(|e| e.id == id)
            .unwrap_or(false)
    }

    /// Focus next element
    pub fn focus_next(&mut self) {
        let active_elements: Vec<usize> = self
            .elements
            .iter()
            .enumerate()
            .filter(|(_, e)| e.is_active)
            .map(|(i, _)| i)
            .collect();

        if active_elements.is_empty() {
            return;
        }

        let current = self.focused_index.unwrap_or(0);
        let current_pos = active_elements
            .iter()
            .position(|&i| i == current)
            .unwrap_or(0);
        let next_pos = (current_pos + 1) % active_elements.len();
        self.focused_index = Some(active_elements[next_pos]);
    }

    /// Focus previous element
    pub fn focus_previous(&mut self) {
        let active_elements: Vec<usize> = self
            .elements
            .iter()
            .enumerate()
            .filter(|(_, e)| e.is_active)
            .map(|(i, _)| i)
            .collect();

        if active_elements.is_empty() {
            return;
        }

        let current = self.focused_index.unwrap_or(0);
        let current_pos = active_elements
            .iter()
            .position(|&i| i == current)
            .unwrap_or(0);
        let prev_pos = if current_pos == 0 {
            active_elements.len() - 1
        } else {
            current_pos - 1
        };
        self.focused_index = Some(active_elements[prev_pos]);
    }

    /// Focus a specific element by custom ID
    pub fn focus(&mut self, custom_id: &str) {
        if let Some(pos) = self
            .elements
            .iter()
            .position(|e| e.custom_id.as_deref() == Some(custom_id) && e.is_active)
        {
            self.focused_index = Some(pos);
        }
    }

    /// Enable/disable focus for an element
    pub fn enable_focus(&mut self, id: usize, enabled: bool) {
        if let Some(elem) = self.elements.iter_mut().find(|e| e.id == id) {
            elem.is_active = enabled;
        }
    }

    /// Clear focus state for next render
    pub fn clear(&mut self) {
        self.elements.clear();
        // Keep focused_index for persistence across renders
    }
}

// Thread-local storage for focus manager (legacy fallback)
thread_local! {
    static FOCUS_MANAGER: RefCell<FocusManager> = RefCell::new(FocusManager::new());
}

/// Hook to make a component focusable
///
/// # Example
///
/// ```ignore
/// let focus = use_focus(UseFocusOptions::new().auto_focus());
///
/// Box::new()
///     .border_style(if focus.is_focused {
///         BorderStyle::Bold
///     } else {
///         BorderStyle::Single
///     })
/// ```
pub fn use_focus(options: UseFocusOptions) -> FocusState {
    use crate::hooks::use_signal;

    #[derive(Clone, Copy)]
    struct FocusRegistration {
        id: usize,
        use_runtime: bool,
    }

    let registration = use_signal(|| {
        if let Some(ctx) = crate::runtime::current_runtime() {
            let id = ctx.borrow_mut().focus_manager_mut().register(
                options.id.clone(),
                options.is_active,
                options.auto_focus,
            );
            FocusRegistration {
                id,
                use_runtime: true,
            }
        } else {
            let id = FOCUS_MANAGER.with(|fm| {
                fm.borrow_mut()
                    .register(options.id.clone(), options.is_active, options.auto_focus)
            });
            FocusRegistration {
                id,
                use_runtime: false,
            }
        }
    });

    let registration = registration.get();

    // Update metadata when options change
    if registration.use_runtime {
        if let Some(ctx) = crate::runtime::current_runtime() {
            ctx.borrow_mut().focus_manager_mut().update(
                registration.id,
                options.id.clone(),
                options.is_active,
                options.auto_focus,
            );
        }
    } else {
        FOCUS_MANAGER.with(|fm| {
            fm.borrow_mut().update(
                registration.id,
                options.id.clone(),
                options.is_active,
                options.auto_focus,
            );
        });
    }

    // Unregister on unmount
    crate::hooks::use_effect_once({
        move || {
            Some(Box::new(move || {
                if registration.use_runtime {
                    if let Some(ctx) = crate::runtime::current_runtime() {
                        ctx.borrow_mut()
                            .focus_manager_mut()
                            .unregister(registration.id);
                    }
                } else {
                    FOCUS_MANAGER.with(|fm| fm.borrow_mut().unregister(registration.id));
                }
            }))
        }
    });

    let is_focused = if registration.use_runtime {
        crate::runtime::current_runtime()
            .map(|ctx| ctx.borrow().focus_manager().is_focused(registration.id))
            .unwrap_or(false)
    } else {
        FOCUS_MANAGER.with(|fm| fm.borrow().is_focused(registration.id))
    };

    FocusState { is_focused }
}

/// Hook to access the focus manager
///
/// # Example
///
/// ```ignore
/// let fm = use_focus_manager();
///
/// use_input(move |_, key| {
///     if key.tab {
///         fm.focus_next();
///     }
/// });
/// ```
pub fn use_focus_manager() -> FocusManagerHandle {
    FocusManagerHandle
}

/// Handle to the focus manager
#[derive(Clone, Copy)]
pub struct FocusManagerHandle;

impl FocusManagerHandle {
    /// Focus the next focusable element
    pub fn focus_next(&self) {
        if let Some(ctx) = crate::runtime::current_runtime() {
            ctx.borrow_mut().focus_manager_mut().focus_next();
        } else {
            FOCUS_MANAGER.with(|fm| fm.borrow_mut().focus_next());
        }
    }

    /// Focus the previous focusable element
    pub fn focus_previous(&self) {
        if let Some(ctx) = crate::runtime::current_runtime() {
            ctx.borrow_mut().focus_manager_mut().focus_previous();
        } else {
            FOCUS_MANAGER.with(|fm| fm.borrow_mut().focus_previous());
        }
    }

    /// Focus a specific element by ID
    pub fn focus(&self, id: &str) {
        if let Some(ctx) = crate::runtime::current_runtime() {
            ctx.borrow_mut().focus_manager_mut().focus(id);
        } else {
            FOCUS_MANAGER.with(|fm| fm.borrow_mut().focus(id));
        }
    }

    /// Enable/disable focus for the current component
    pub fn enable_focus(&self, id: usize, enabled: bool) {
        if let Some(ctx) = crate::runtime::current_runtime() {
            ctx.borrow_mut()
                .focus_manager_mut()
                .enable_focus(id, enabled);
        } else {
            FOCUS_MANAGER.with(|fm| fm.borrow_mut().enable_focus(id, enabled));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_focus_manager_registration() {
        let mut fm = FocusManager::new();

        let id1 = fm.register(None, true, false);
        let id2 = fm.register(None, true, false);

        assert!(id1 != id2);
        assert_eq!(fm.elements.len(), 2);
    }

    #[test]
    fn test_focus_manager_auto_focus() {
        let mut fm = FocusManager::new();

        let id1 = fm.register(None, true, true); // auto_focus
        let _id2 = fm.register(None, true, false);

        assert!(fm.is_focused(id1));
    }

    #[test]
    fn test_focus_navigation() {
        let mut fm = FocusManager::new();

        let id1 = fm.register(None, true, true);
        let id2 = fm.register(None, true, false);
        let id3 = fm.register(None, true, false);

        assert!(fm.is_focused(id1));

        fm.focus_next();
        assert!(fm.is_focused(id2));

        fm.focus_next();
        assert!(fm.is_focused(id3));

        fm.focus_next();
        assert!(fm.is_focused(id1)); // Wraps around

        fm.focus_previous();
        assert!(fm.is_focused(id3));
    }

    #[test]
    fn test_focus_by_id() {
        let mut fm = FocusManager::new();

        let _id1 = fm.register(Some("first".to_string()), true, true);
        let id2 = fm.register(Some("second".to_string()), true, false);

        fm.focus("second");
        assert!(fm.is_focused(id2));
    }

    #[test]
    fn test_inactive_elements_skipped() {
        let mut fm = FocusManager::new();

        let id1 = fm.register(None, true, true);
        let _id2 = fm.register(None, false, false); // inactive
        let id3 = fm.register(None, true, false);

        assert!(fm.is_focused(id1));

        fm.focus_next();
        assert!(fm.is_focused(id3)); // Skips inactive element
    }

    #[test]
    fn test_focus_with_runtime() {
        use crate::runtime::{RuntimeContext, with_runtime};
        use std::rc::Rc;

        let ctx = Rc::new(RefCell::new(RuntimeContext::new()));

        // Register elements within runtime context
        with_runtime(ctx.clone(), || {
            let fm_handle = use_focus_manager();

            // Register some elements directly on the context
            let id1 = ctx
                .borrow_mut()
                .focus_manager_mut()
                .register(None, true, true);
            let id2 = ctx
                .borrow_mut()
                .focus_manager_mut()
                .register(None, true, false);

            assert!(ctx.borrow().focus_manager().is_focused(id1));

            fm_handle.focus_next();
            assert!(ctx.borrow().focus_manager().is_focused(id2));
        });
    }
}