rnk 0.19.1

A React-like declarative terminal UI framework for Rust, inspired by Ink and Bubbletea
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Unified runtime context for rnk applications
//!
//! This module provides a centralized context that holds all runtime state,
//! replacing scattered global/thread-local state with explicit context passing.
//!
//! # Architecture
//!
//! The `RuntimeContext` is the single source of truth for:
//! - Hook state (HookContext)
//! - Input handlers
//! - Mouse handlers
//! - Focus management
//! - App control (exit, render requests)
//! - Accessibility state
//!
//! This design enables:
//! - Multiple concurrent apps (each with its own context)
//! - Better testability (no global state pollution)
//! - Clearer ownership and lifecycle

use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use crate::cmd::Cmd;
use crate::components::Theme;
use crate::hooks::context::{HookContext, HookStorage};
use crate::hooks::paste::PasteEvent;
use crate::hooks::use_focus::FocusManager;
use crate::hooks::use_input::Key;
use crate::hooks::use_mouse::Mouse;
use crate::renderer::{IntoPrintable, RenderHandle, SharedFrameRateStats};

/// Input handler function type
pub type InputHandlerFn = Rc<dyn Fn(&str, &Key)>;

/// Mouse handler function type
pub type MouseHandlerFn = Rc<dyn Fn(&Mouse)>;

/// Paste handler function type
pub type PasteHandlerFn = Rc<dyn Fn(&PasteEvent)>;

/// Unified runtime context for an rnk application
///
/// This context holds all state needed during rendering and event handling.
/// It replaces the previous scattered thread-local and global state.
pub struct RuntimeContext {
    /// Hook state for the component tree
    hook_context: Rc<RefCell<HookContext>>,

    /// Input handlers registered via use_input
    input_handlers: Vec<InputHandlerFn>,

    /// Mouse handlers registered via use_mouse
    mouse_handlers: Vec<MouseHandlerFn>,

    /// Whether mouse mode is enabled
    mouse_enabled: bool,

    /// Focus manager for Tab navigation
    focus_manager: FocusManager,

    /// Exit flag for the application
    exit_flag: Arc<AtomicBool>,

    /// Render handle for cross-thread communication
    render_handle: Option<RenderHandle>,

    /// Whether screen reader mode is enabled
    screen_reader_enabled: bool,
    /// Whether screen reader state has been initialized/detected
    screen_reader_initialized: bool,

    /// Paste handlers registered via use_paste
    paste_handlers: Vec<PasteHandlerFn>,

    /// Last user activity timestamp for idle detection
    last_activity: Instant,

    /// Measured element dimensions (element_id -> (width, height))
    measurements: std::collections::HashMap<crate::core::ElementId, (u16, u16)>,
    /// Measured element dimensions by user key (key -> (width, height))
    measurements_by_key: std::collections::HashMap<String, (u16, u16)>,

    /// Shared frame rate statistics
    frame_rate_stats: Option<Arc<SharedFrameRateStats>>,

    /// Current theme for this runtime (isolated per app/runtime context)
    theme: Theme,
}

impl RuntimeContext {
    /// Create a new runtime context
    pub fn new() -> Self {
        Self {
            hook_context: Rc::new(RefCell::new(HookContext::new())),
            input_handlers: Vec::new(),
            mouse_handlers: Vec::new(),
            mouse_enabled: false,
            focus_manager: FocusManager::new(),
            exit_flag: Arc::new(AtomicBool::new(false)),
            render_handle: None,
            screen_reader_enabled: false,
            screen_reader_initialized: false,
            paste_handlers: Vec::new(),
            last_activity: Instant::now(),
            measurements: std::collections::HashMap::new(),
            measurements_by_key: std::collections::HashMap::new(),
            frame_rate_stats: None,
            theme: Theme::dark(),
        }
    }

    /// Create a runtime context with app control
    pub fn with_app_control(exit_flag: Arc<AtomicBool>, render_handle: RenderHandle) -> Self {
        Self {
            hook_context: Rc::new(RefCell::new(HookContext::new())),
            input_handlers: Vec::new(),
            mouse_handlers: Vec::new(),
            mouse_enabled: false,
            focus_manager: FocusManager::new(),
            exit_flag,
            render_handle: Some(render_handle),
            screen_reader_enabled: false,
            screen_reader_initialized: false,
            paste_handlers: Vec::new(),
            last_activity: Instant::now(),
            measurements: std::collections::HashMap::new(),
            measurements_by_key: std::collections::HashMap::new(),
            frame_rate_stats: None,
            theme: Theme::dark(),
        }
    }

    // === Hook Context Methods ===

    /// Clear per-render input/mouse/paste registrations.
    pub fn prepare_render(&mut self) {
        self.input_handlers.clear();
        self.mouse_handlers.clear();
        self.paste_handlers.clear();
        self.mouse_enabled = false;
    }

    /// Begin a render cycle
    pub fn begin_render(&mut self) {
        self.prepare_render();
        self.hook_context.borrow_mut().begin_render();
    }

    /// End a render cycle
    pub fn end_render(&mut self) {
        self.hook_context.borrow_mut().end_render();
    }

    /// Run effects after render
    pub fn run_effects(&mut self) {
        self.hook_context.borrow_mut().run_effects();
    }

    /// Get or create a hook at the current index
    pub fn use_hook<T: Clone + Send + Sync + 'static, F: FnOnce() -> T>(
        &mut self,
        init: F,
    ) -> HookStorage {
        self.hook_context.borrow_mut().use_hook(init)
    }

    /// Queue a command to execute after render
    pub fn queue_cmd(&mut self, cmd: Cmd) {
        self.hook_context.borrow_mut().queue_cmd(cmd);
    }

    /// Take all queued commands
    pub fn take_cmds(&mut self) -> Vec<Cmd> {
        self.hook_context.borrow_mut().take_cmds()
    }

    /// Set the render callback for hooks
    pub fn set_render_callback(&mut self, callback: crate::hooks::context::RenderCallback) {
        self.hook_context.borrow_mut().set_render_callback(callback);
    }

    /// Request a re-render
    pub fn request_render(&self) {
        self.hook_context.borrow().request_render();
        if let Some(handle) = &self.render_handle {
            handle.request_render();
        }
    }

    /// Get the shared hook context used by `with_hooks`.
    pub fn hook_context(&self) -> Rc<RefCell<HookContext>> {
        self.hook_context.clone()
    }

    // === Input Handler Methods ===

    /// Register an input handler
    pub fn register_input_handler<F>(&mut self, handler: F)
    where
        F: Fn(&str, &Key) + 'static,
    {
        self.input_handlers.push(Rc::new(handler));
    }

    /// Dispatch input to all handlers
    pub fn dispatch_input(&self, input: &str, key: &Key) {
        for handler in &self.input_handlers {
            handler(input, key);
        }
    }

    /// Get the number of registered input handlers
    pub fn input_handler_count(&self) -> usize {
        self.input_handlers.len()
    }

    // === Mouse Handler Methods ===

    /// Register a mouse handler
    pub fn register_mouse_handler<F>(&mut self, handler: F)
    where
        F: Fn(&Mouse) + 'static,
    {
        self.mouse_handlers.push(Rc::new(handler));
        self.mouse_enabled = true;
    }

    /// Dispatch mouse event to all handlers
    pub fn dispatch_mouse(&self, mouse: &Mouse) {
        for handler in &self.mouse_handlers {
            handler(mouse);
        }
    }

    /// Check if mouse mode is enabled
    pub fn is_mouse_enabled(&self) -> bool {
        self.mouse_enabled
    }

    /// Set mouse enabled state
    pub fn set_mouse_enabled(&mut self, enabled: bool) {
        self.mouse_enabled = enabled;
    }

    // === Paste Handler Methods ===

    /// Register a paste handler
    pub fn register_paste_handler<F>(&mut self, handler: F)
    where
        F: Fn(&PasteEvent) + 'static,
    {
        self.paste_handlers.push(Rc::new(handler));
    }

    /// Dispatch paste event to all handlers
    pub fn dispatch_paste(&self, event: &PasteEvent) {
        for handler in &self.paste_handlers {
            handler(event);
        }
    }

    /// Get the number of registered paste handlers
    pub fn paste_handler_count(&self) -> usize {
        self.paste_handlers.len()
    }

    // === Idle Tracking Methods ===

    /// Record user activity (resets idle timer)
    pub fn record_activity(&mut self) {
        self.last_activity = Instant::now();
    }

    /// Get the duration since last activity
    pub fn idle_duration(&self) -> Duration {
        self.last_activity.elapsed()
    }

    // === Focus Manager Methods ===

    /// Get mutable access to the focus manager
    pub fn focus_manager_mut(&mut self) -> &mut FocusManager {
        &mut self.focus_manager
    }

    /// Get read access to the focus manager
    pub fn focus_manager(&self) -> &FocusManager {
        &self.focus_manager
    }

    // === App Control Methods ===

    /// Get the exit flag
    pub fn exit_flag(&self) -> Arc<AtomicBool> {
        self.exit_flag.clone()
    }

    /// Request app exit
    pub fn exit(&self) {
        self.exit_flag.store(true, Ordering::SeqCst);
    }

    /// Check if exit was requested
    pub fn should_exit(&self) -> bool {
        self.exit_flag.load(Ordering::SeqCst)
    }

    /// Get the render handle
    pub fn render_handle(&self) -> Option<&RenderHandle> {
        self.render_handle.as_ref()
    }

    /// Print a message (delegates to render handle)
    pub fn println(&self, message: impl IntoPrintable) {
        if let Some(handle) = &self.render_handle {
            handle.println(message);
        }
    }

    /// Enter alternate screen mode
    pub fn enter_alt_screen(&self) {
        if let Some(handle) = &self.render_handle {
            handle.enter_alt_screen();
        }
    }

    /// Exit alternate screen mode
    pub fn exit_alt_screen(&self) {
        if let Some(handle) = &self.render_handle {
            handle.exit_alt_screen();
        }
    }

    /// Check if in alternate screen mode
    pub fn is_alt_screen(&self) -> bool {
        self.render_handle
            .as_ref()
            .map(|h| h.is_alt_screen())
            .unwrap_or(false)
    }

    // === Accessibility Methods ===

    /// Check if screen reader mode is enabled
    pub fn is_screen_reader_enabled(&self) -> bool {
        self.screen_reader_enabled
    }

    /// Whether the screen reader status has been initialized.
    pub fn is_screen_reader_initialized(&self) -> bool {
        self.screen_reader_initialized
    }

    /// Set screen reader mode
    pub fn set_screen_reader_enabled(&mut self, enabled: bool) {
        self.screen_reader_enabled = enabled;
        self.screen_reader_initialized = true;
    }

    // === Measurement Methods ===

    /// Store a measurement for an element
    pub fn set_measurement(&mut self, element_id: crate::core::ElementId, width: u16, height: u16) {
        self.measurements.insert(element_id, (width, height));
    }

    /// Get a measurement for an element
    pub fn get_measurement(&self, element_id: crate::core::ElementId) -> Option<(u16, u16)> {
        self.measurements.get(&element_id).copied()
    }

    /// Replace all measurements (called by renderer after layout)
    pub fn set_measure_layouts(
        &mut self,
        layouts: std::collections::HashMap<crate::core::ElementId, crate::layout::Layout>,
    ) {
        self.measurements.clear();
        self.measurements_by_key.clear();
        for (id, layout) in layouts {
            self.measurements
                .insert(id, (layout.width as u16, layout.height as u16));
        }
    }

    /// Replace all measurements with optional key-indexed measurements.
    pub fn set_measure_layouts_with_keys(
        &mut self,
        layouts: std::collections::HashMap<crate::core::ElementId, crate::layout::Layout>,
        keyed_layouts: std::collections::HashMap<String, crate::layout::Layout>,
    ) {
        self.measurements.clear();
        self.measurements_by_key.clear();

        for (id, layout) in layouts {
            self.measurements
                .insert(id, (layout.width as u16, layout.height as u16));
        }

        for (key, layout) in keyed_layouts {
            self.measurements_by_key
                .insert(key, (layout.width as u16, layout.height as u16));
        }
    }

    /// Get measurement as Dimensions (width, height as f32)
    pub fn get_measurement_dims(&self, element_id: crate::core::ElementId) -> Option<(f32, f32)> {
        self.measurements
            .get(&element_id)
            .map(|&(w, h)| (w as f32, h as f32))
    }

    /// Get measurement by user key as Dimensions (width, height as f32)
    pub fn get_measurement_by_key_dims(&self, key: &str) -> Option<(f32, f32)> {
        self.measurements_by_key
            .get(key)
            .map(|&(w, h)| (w as f32, h as f32))
    }

    // === Frame Rate Stats Methods ===

    /// Set the shared frame rate stats
    pub fn set_frame_rate_stats(&mut self, stats: Option<Arc<SharedFrameRateStats>>) {
        self.frame_rate_stats = stats;
    }

    /// Get the shared frame rate stats
    pub fn frame_rate_stats(&self) -> Option<&Arc<SharedFrameRateStats>> {
        self.frame_rate_stats.as_ref()
    }

    // === Theme Methods ===

    /// Set the current theme for this runtime.
    pub fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
    }

    /// Get the current theme for this runtime.
    pub fn theme(&self) -> Theme {
        self.theme.clone()
    }
}

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

// === Thread-local Context Access ===

thread_local! {
    static CURRENT_RUNTIME: RefCell<Option<Rc<RefCell<RuntimeContext>>>> = const { RefCell::new(None) };
}

/// Get the current runtime context
pub fn current_runtime() -> Option<Rc<RefCell<RuntimeContext>>> {
    CURRENT_RUNTIME.with(|ctx| ctx.borrow().clone())
}

/// Set the current runtime context
pub fn set_current_runtime(ctx: Option<Rc<RefCell<RuntimeContext>>>) {
    CURRENT_RUNTIME.with(|current| {
        *current.borrow_mut() = ctx;
    });
}

/// Run a function with a runtime context
pub fn with_runtime<F, R>(ctx: Rc<RefCell<RuntimeContext>>, f: F) -> R
where
    F: FnOnce() -> R,
{
    // Save the previous context so nested calls work correctly
    let prev = current_runtime();

    // Set the current context
    set_current_runtime(Some(ctx.clone()));

    // Run the function (use a guard to ensure cleanup on panic)
    struct RuntimeGuard {
        prev: Option<Rc<RefCell<RuntimeContext>>>,
    }
    impl Drop for RuntimeGuard {
        fn drop(&mut self) {
            set_current_runtime(self.prev.take());
        }
    }
    let guard = RuntimeGuard { prev };

    // Keep runtime + hook lifecycle aligned so closures that run under
    // with_runtime can safely use hook APIs when needed.
    ctx.borrow_mut().prepare_render();
    let hook_context = ctx.borrow().hook_context();
    let result = crate::hooks::context::with_hooks(hook_context, f);

    // Restore the previous context (guard handles this on drop, but
    // we do it explicitly here so the guard doesn't double-restore)
    drop(guard);

    result
}

/// Execute a function with access to the current runtime context
///
/// This is a convenience function for hooks that need to access the context.
pub fn with_current_runtime<F, R>(f: F) -> Option<R>
where
    F: FnOnce(&mut RuntimeContext) -> R,
{
    current_runtime().map(|ctx| f(&mut ctx.borrow_mut()))
}

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

    #[test]
    fn test_runtime_context_creation() {
        let ctx = RuntimeContext::new();
        assert!(!ctx.should_exit());
        assert!(!ctx.is_mouse_enabled());
        assert!(!ctx.is_screen_reader_enabled());
    }

    #[test]
    fn test_runtime_context_exit() {
        let ctx = RuntimeContext::new();
        assert!(!ctx.should_exit());
        ctx.exit();
        assert!(ctx.should_exit());
    }

    #[test]
    fn test_runtime_context_input_handlers() {
        let mut ctx = RuntimeContext::new();
        assert_eq!(ctx.input_handler_count(), 0);

        ctx.register_input_handler(|_, _| {});
        assert_eq!(ctx.input_handler_count(), 1);

        ctx.register_input_handler(|_, _| {});
        assert_eq!(ctx.input_handler_count(), 2);
    }

    #[test]
    fn test_runtime_context_mouse_enabled() {
        let mut ctx = RuntimeContext::new();
        assert!(!ctx.is_mouse_enabled());

        ctx.register_mouse_handler(|_| {});
        assert!(ctx.is_mouse_enabled());
    }

    #[test]
    fn test_runtime_context_measurements() {
        use crate::core::ElementId;
        let mut ctx = RuntimeContext::new();
        let id = ElementId::new();
        assert!(ctx.get_measurement(id).is_none());

        ctx.set_measurement(id, 80, 24);
        assert_eq!(ctx.get_measurement(id), Some((80, 24)));
    }

    #[test]
    fn test_runtime_context_measurements_by_key() {
        use crate::core::ElementId;
        use crate::layout::Layout;
        use std::collections::HashMap;

        let mut ctx = RuntimeContext::new();
        let id = ElementId::new();
        let mut by_id = HashMap::new();
        by_id.insert(
            id,
            Layout {
                x: 0.0,
                y: 0.0,
                width: 42.0,
                height: 9.0,
            },
        );

        let mut by_key = HashMap::new();
        by_key.insert(
            "main-panel".to_string(),
            Layout {
                x: 0.0,
                y: 0.0,
                width: 42.0,
                height: 9.0,
            },
        );

        ctx.set_measure_layouts_with_keys(by_id, by_key);
        assert_eq!(ctx.get_measurement(id), Some((42, 9)));
        assert_eq!(
            ctx.get_measurement_by_key_dims("main-panel"),
            Some((42.0, 9.0))
        );
    }

    #[test]
    fn test_with_runtime() {
        let ctx = Rc::new(RefCell::new(RuntimeContext::new()));

        let result = with_runtime(ctx.clone(), || {
            let runtime = current_runtime().unwrap();
            runtime.borrow_mut().register_input_handler(|_, _| {});
            runtime.borrow().input_handler_count()
        });

        assert_eq!(result, 1);

        // Context should be cleared after with_runtime
        assert!(current_runtime().is_none());
    }

    #[test]
    fn test_hook_state_persistence() {
        let ctx = Rc::new(RefCell::new(RuntimeContext::new()));

        // First render
        with_runtime(ctx.clone(), || {
            let runtime = current_runtime().unwrap();
            let hook = runtime.borrow_mut().use_hook(|| 42i32);
            assert_eq!(hook.get::<i32>(), Some(42));
            hook.set(100i32);
        });

        // Second render - hook state should persist
        with_runtime(ctx.clone(), || {
            let runtime = current_runtime().unwrap();
            let hook = runtime.borrow_mut().use_hook(|| 0i32); // init ignored
            assert_eq!(hook.get::<i32>(), Some(100));
        });
    }

    #[test]
    fn test_handlers_cleared_on_render() {
        let ctx = Rc::new(RefCell::new(RuntimeContext::new()));

        // First render - register handlers
        with_runtime(ctx.clone(), || {
            let runtime = current_runtime().unwrap();
            runtime.borrow_mut().register_input_handler(|_, _| {});
            runtime.borrow_mut().register_input_handler(|_, _| {});
            assert_eq!(runtime.borrow().input_handler_count(), 2);
        });

        // Second render - handlers should be cleared and re-registered
        with_runtime(ctx.clone(), || {
            let runtime = current_runtime().unwrap();
            // Handlers were cleared at begin_render
            assert_eq!(runtime.borrow().input_handler_count(), 0);
            runtime.borrow_mut().register_input_handler(|_, _| {});
            assert_eq!(runtime.borrow().input_handler_count(), 1);
        });
    }
}