reratui 1.1.0

A modern, reactive TUI framework for Rust with React-inspired hooks and components, powered by ratatui
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
# Architecture Overview


This document explains the internal architecture of Reratui, including the fiber system, render pipeline, and hook implementation.

## Table of Contents


- [Overview]#overview
- [Fiber Architecture]#fiber-architecture
- [Render Pipeline]#render-pipeline
- [Hook System]#hook-system
- [State Management]#state-management
- [Effect System]#effect-system
- [Context System]#context-system
- [Event Handling]#event-handling

## Overview


Reratui is built on a fiber-based architecture inspired by React Fiber. The key components are:

```
┌────────────────────────────────────────────────────────────┐
│                        Runtime                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                   Render Loop                       │   │
│  │  ┌─────┐  ┌────────┐  ┌────────┐  ┌───────┐  ┌─────┐│   │
│  │  │Poll │→ │ Render │→ │ Commit │→ │ Event │ →│Effect│   │
│  │  └─────┘  └────────┘  └────────┘  └───────┘  └─────┘│   │
│  └─────────────────────────────────────────────────────┘   │
│                            ↓                               │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                    Fiber Tree                       │   │
│  │  ┌────────┐    ┌────────┐    ┌────────┐             │   │
│  │  │ Fiber  │───→│ Fiber  │───→│ Fiber  │             │   │
│  │  │ (Root) │    │(Child) │    │(Child) │             │   │
│  │  └────────┘    └────────┘    └────────┘             │   │
│  └─────────────────────────────────────────────────────┘   │
│                            ↓                               │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                   Scheduler                         │   │
│  │  ┌──────────────┐  ┌──────────────┐                 │   │
│  │  │ State Batch  │  │ Effect Queue │                 │   │
│  │  └──────────────┘  └──────────────┘                 │   │
│  └─────────────────────────────────────────────────────┘   │
└────────────────────────────────────────────────────────────┘
```

## Fiber Architecture


### What is a Fiber?


A Fiber is a unit of work that represents a component instance. Each fiber maintains:

```rust
pub struct Fiber {
    pub id: FiberId,                    // Unique identifier
    pub hooks: Vec<Box<dyn Any>>,       // Hook state storage
    pub hook_index: usize,              // Current hook position
    pub pending_effects: Vec<PendingEffect>,
    pub cleanup_by_hook: HashMap<usize, CleanupFn>,
    pub async_cleanup_by_hook: HashMap<usize, AsyncCleanupFn>,
    pub provided_contexts: Vec<TypeId>,
    pub parent: Option<FiberId>,
    pub children: Vec<FiberId>,
    pub dirty: bool,                    // Needs re-render
    pub key: Option<String>,            // For reconciliation
}
```

### Fiber Tree


The `FiberTree` manages all fibers:

```rust
pub struct FiberTree {
    fibers: HashMap<FiberId, Fiber>,
    root: Option<FiberId>,
    render_stack: Vec<FiberId>,         // Currently rendering
    pending_unmount: Vec<FiberId>,      // Scheduled for cleanup
}
```

### Fiber Lifecycle


```
Mount → Render → Update → Unmount
  │        │        │        │
  │        │        │        └─ Run cleanups, remove fiber
  │        │        └─ Re-render on state change
  │        └─ Execute render, call hooks
  └─ Create fiber, initialize hooks
```

## Render Pipeline


The render loop consists of 5 phases:

### 1. Poll Phase


Wait for terminal events or scheduled updates:

```rust
// Simplified
loop {
    let event = poll_event(frame_interval)?;
    if event.is_some() || has_dirty_fibers() {
        // Continue to render
    }
}
```

### 2. Render Phase


Execute component render functions:

```rust
// For each dirty fiber
fiber_tree.begin_render(fiber_id);
component.render(area, buffer);
fiber_tree.end_render();
```

During render:

- Hook index is reset to 0
- Hooks are called in order
- State reads return current values
- State writes are batched

### 3. Commit Phase


Apply batched state updates:

```rust
// Process state batch
for update in state_batch.drain() {
    let fiber = tree.get_mut(update.fiber_id);
    fiber.set_hook(update.hook_index, update.new_value);
    fiber.dirty = true;
}
```

### 4. Event Phase


Process terminal events:

```rust
// Set current event for hooks to read
set_current_event(event);

// Re-render to process event
// (hooks like use_keyboard read the event)
```

### 5. Effect Phase


Run effects and cleanups:

```rust
// Run cleanups first (LIFO order)
for cleanup in cleanups.drain().rev() {
    cleanup();
}

// Run new effects
for effect in pending_effects.drain() {
    let cleanup = (effect.effect)();
    if let Some(cleanup) = cleanup {
        fiber.cleanup_by_hook.insert(effect.hook_index, cleanup);
    }
}
```

## Hook System


### Hook Storage


Hooks store state in the fiber's `hooks` vector:

```rust
// Each hook gets an index
let hook_index = fiber.next_hook_index();

// State is stored at that index
fiber.set_hook(hook_index, initial_value);

// Retrieved on subsequent renders
let value = fiber.get_hook::<T>(hook_index);
```

### Hook Index Management


```rust
impl Fiber {
    pub fn next_hook_index(&mut self) -> usize {
        let index = self.hook_index;
        self.hook_index += 1;
        index
    }

    pub fn reset_hook_index(&mut self) {
        self.hook_index = 0;
    }
}
```

This is why hooks must be called in the same order - the index determines which state belongs to which hook.

### Hook Implementation Pattern


```rust
pub fn use_state<T, F>(initializer: F) -> (T, StateSetter<T>)
where
    T: Clone + Send + Sync + PartialEq + 'static,
    F: FnOnce() -> T,
{
    with_current_fiber(|fiber| {
        let hook_index = fiber.next_hook_index();
        let fiber_id = fiber.id;

        // Initialize on first render
        let value = fiber.get_or_init_hook(hook_index, initializer);

        // Create setter
        let setter = StateSetter {
            fiber_id,
            hook_index,
            _marker: PhantomData,
        };

        (value, setter)
    })
}
```

## State Management


### State Batching


State updates are batched during render:

```rust
pub struct StateBatch {
    updates: Vec<StateUpdate>,
    is_batching: bool,
}

pub struct StateUpdate {
    pub fiber_id: FiberId,
    pub hook_index: usize,
    pub update: StateUpdateKind,
}

pub enum StateUpdateKind {
    Value(Box<dyn Any + Send>),
    Updater(Box<dyn FnOnce(Box<dyn Any>) -> Box<dyn Any> + Send>),
}
```

### Update Flow


```
set_count.set(5)
queue_update(fiber_id, StateUpdate { ... })
StateBatch.updates.push(update)
    ▼ (end of render phase)
StateBatch.end_batch(tree)
Apply updates to fibers
Mark fibers dirty
```

## Effect System


### Effect Types


```rust
// Sync effect
pub struct PendingEffect {
    pub effect: Box<dyn FnOnce() -> Option<CleanupFn>>,
    pub hook_index: usize,
}

// Async effect
pub struct AsyncPendingEffect {
    pub effect: AsyncEffectFn,
    pub hook_index: usize,
}
```

### Effect Queue


```rust
pub struct EffectQueue {
    sync_effects: Vec<PendingEffect>,
    async_effects: Vec<AsyncPendingEffect>,
    sync_cleanups: Vec<CleanupFn>,
    async_cleanups: Vec<AsyncCleanupFn>,
}
```

### Effect Execution Order


1. Run sync cleanups (LIFO)
2. Run async cleanups (LIFO)
3. Run sync effects
4. Spawn async effects

### Dependency Tracking


Effects track dependencies to determine when to re-run:

```rust
pub fn use_effect<D, F>(effect: F, deps: D)
where
    D: PartialEq + Clone + Send + Sync + 'static,
{
    with_current_fiber(|fiber| {
        let hook_index = fiber.next_hook_index();

        // Get previous deps
        let prev_deps = fiber.get_hook::<D>(hook_index);

        // Check if deps changed
        let should_run = prev_deps.map_or(true, |prev| prev != deps);

        if should_run {
            // Store new deps
            fiber.set_hook(hook_index, deps.clone());

            // Queue effect
            fiber.pending_effects.push(PendingEffect {
                effect: Box::new(effect),
                hook_index,
            });
        }
    });
}
```

## Context System


### Context Stack


Context uses a thread-local stack:

```rust
thread_local! {
    static CONTEXT_STACK: RefCell<ContextStack> = RefCell::new(ContextStack::new());
}

pub struct ContextStack {
    // TypeId -> Vec<(FiberId, Value)>
    contexts: HashMap<TypeId, Vec<(FiberId, Box<dyn Any + Send + Sync>)>>,
}
```

### Provider


```rust
pub fn use_context_provider<T, F>(initializer: F)
where
    T: Clone + Send + Sync + 'static,
    F: FnOnce() -> T,
{
    with_current_fiber(|fiber| {
        let hook_index = fiber.next_hook_index();
        let value = fiber.get_or_init_hook(hook_index, initializer);

        // Push to context stack
        push_context(fiber.id, value);

        // Track for cleanup
        fiber.provided_contexts.push(TypeId::of::<T>());
    });
}
```

### Consumer


```rust
pub fn use_context<T>() -> T
where
    T: Clone + Send + Sync + 'static,
{
    get_context::<T>().expect("Context not found")
}

fn get_context<T: Clone + 'static>() -> Option<T> {
    CONTEXT_STACK.with(|stack| {
        let stack = stack.borrow();
        let type_id = TypeId::of::<T>();

        stack.contexts.get(&type_id)
            .and_then(|vec| vec.last())
            .and_then(|(_, value)| value.downcast_ref::<T>())
            .cloned()
    })
}
```

## Event Handling


### Event Storage


```rust
thread_local! {
    static CURRENT_EVENT: RefCell<Option<Arc<Event>>> = RefCell::new(None);
}

pub fn set_current_event(event: Option<Arc<Event>>) {
    CURRENT_EVENT.with(|e| *e.borrow_mut() = event);
}

pub fn use_event() -> Option<Event> {
    CURRENT_EVENT.with(|e| e.borrow().as_ref().map(|arc| (**arc).clone()))
}
```

### Event Hooks


Event hooks use the effect event pattern for stable callbacks:

```rust
pub fn use_keyboard<F>(handler: F)
where
    F: Fn(KeyEvent) + Send + Sync + 'static,
{
    // Create stable callback
    let stable_handler = use_effect_event(move |key_event: KeyEvent| {
        handler(key_event);
    });

    // Check for keyboard events
    if let Some(Event::Key(key_event)) = use_event() {
        stable_handler.call(key_event);
    }
}
```

## Thread Safety


### Requirements


All hook state must be `Send + Sync` because:

- State may be accessed from async effects
- The runtime uses async/await

### Patterns


```rust
// Use Arc for shared state
let shared = Arc::new(Mutex::new(data));

// Use parking_lot for better performance
use parking_lot::Mutex;
let shared = Arc::new(Mutex::new(data));
```

## Performance Considerations


### Dirty Tracking


Only dirty fibers are re-rendered:

```rust
impl FiberTree {
    pub fn dirty_fibers(&self) -> HashSet<FiberId> {
        self.fibers
            .iter()
            .filter(|(_, fiber)| fiber.dirty)
            .map(|(id, _)| *id)
            .collect()
    }
}
```

### Conditional Updates


Use `set_if_changed` to avoid unnecessary re-renders:

```rust
impl<T: PartialEq> StateSetter<T> {
    pub fn set_if_changed(&self, value: T) {
        // Only queue update if value differs
        if current_value != value {
            self.set(value);
        }
    }
}
```

### Memoization


`use_memo` caches expensive computations:

```rust
pub fn use_memo<T, D, F>(compute: F, deps: D) -> T {
    with_current_fiber(|fiber| {
        let hook_index = fiber.next_hook_index();

        // Check if deps changed
        let prev = fiber.get_hook::<(D, T)>(hook_index);

        if let Some((prev_deps, cached)) = prev {
            if prev_deps == deps {
                return cached; // Return cached value
            }
        }

        // Recompute
        let value = compute();
        fiber.set_hook(hook_index, (deps, value.clone()));
        value
    })
}
```

## Debugging


### Tracing


Enable tracing for detailed logs:

```rust
tracing_subscriber::fmt()
    .with_max_level(tracing::Level::DEBUG)
    .init();
```

### Strict Mode


Enable strict mode to catch hook violations:

```rust
render_with_options(|| App, RenderOptions {
    strict_mode: true,
    ..Default::default()
}).await?;
```

### Fiber Inspection


In debug builds, fibers track hook types:

```rust
#[cfg(debug_assertions)]

pub previous_hook_types: Vec<&'static str>,
#[cfg(debug_assertions)]

pub current_hook_types: Vec<&'static str>,
```