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
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
//! 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::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};

use crate::cmd::Cmd;
use crate::hooks::context::{HookContext, HookStorage};
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)>;

/// 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: Arc<RwLock<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,

    /// Measured element dimensions (element_id -> (width, height))
    measurements: std::collections::HashMap<u64, (u16, u16)>,

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

impl RuntimeContext {
    /// Create a new runtime context
    pub fn new() -> Self {
        Self {
            hook_context: Arc::new(RwLock::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,
            measurements: std::collections::HashMap::new(),
            frame_rate_stats: None,
        }
    }

    /// Create a runtime context with app control
    pub fn with_app_control(exit_flag: Arc<AtomicBool>, render_handle: RenderHandle) -> Self {
        Self {
            hook_context: Arc::new(RwLock::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,
            measurements: std::collections::HashMap::new(),
            frame_rate_stats: None,
        }
    }

    // === Hook Context Methods ===

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

    /// Begin a render cycle
    pub fn begin_render(&mut self) {
        self.prepare_render();
        let mut hook_ctx = self
            .hook_context
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        hook_ctx.begin_render();
    }

    /// End a render cycle
    pub fn end_render(&mut self) {
        let mut hook_ctx = self
            .hook_context
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        hook_ctx.end_render();
    }

    /// Run effects after render
    pub fn run_effects(&mut self) {
        let mut hook_ctx = self
            .hook_context
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        hook_ctx.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 {
        let mut hook_ctx = self
            .hook_context
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        hook_ctx.use_hook(init)
    }

    /// Queue a command to execute after render
    pub fn queue_cmd(&mut self, cmd: Cmd) {
        let mut hook_ctx = self
            .hook_context
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        hook_ctx.queue_cmd(cmd);
    }

    /// Take all queued commands
    pub fn take_cmds(&mut self) -> Vec<Cmd> {
        let mut hook_ctx = self
            .hook_context
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        hook_ctx.take_cmds()
    }

    /// Set the render callback for hooks
    pub fn set_render_callback(&mut self, callback: crate::hooks::context::RenderCallback) {
        let mut hook_ctx = self
            .hook_context
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        hook_ctx.set_render_callback(callback);
    }

    /// Request a re-render
    pub fn request_render(&self) {
        let hook_ctx = self
            .hook_context
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        hook_ctx.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) -> Arc<RwLock<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;
    }

    // === 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
    }

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

    // === Measurement Methods ===

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

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

    // === 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()
    }
}

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,
{
    // Set the current context
    set_current_runtime(Some(ctx.clone()));

    // Begin render
    ctx.borrow_mut().begin_render();

    // Run the function
    let result = f();

    // End render
    ctx.borrow_mut().end_render();

    // Run effects
    ctx.borrow_mut().run_effects();

    // Clear the current context
    set_current_runtime(None);

    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() {
        let mut ctx = RuntimeContext::new();
        assert!(ctx.get_measurement(1).is_none());

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

    #[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);
        });
    }
}