rnk 0.6.13

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
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
# rnk

A React-like declarative terminal UI framework for Rust, inspired by [Ink](https://github.com/vadimdemedes/ink) and [Bubbletea](https://github.com/charmbracelet/bubbletea).

[![Crates.io](https://img.shields.io/crates/v/rnk.svg)](https://crates.io/crates/rnk)
[![Documentation](https://docs.rs/rnk/badge.svg)](https://docs.rs/rnk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

## Features

- **React-like API**: Familiar component model with hooks (`use_signal`, `use_effect`, `use_input`, `use_cmd`)
- **Command System**: Elm-inspired side effect management for async tasks, timers, file I/O
- **Declarative UI**: Build TUIs with composable components
- **Flexbox Layout**: Powered by [Taffy]https://github.com/DioxusLabs/taffy for flexible layouts
- **Inline Mode** (default): Output persists in terminal history (like Ink/Bubbletea)
- **Fullscreen Mode**: Uses alternate screen buffer (like vim)
- **Line-level Diff Rendering**: Only changed lines are redrawn for efficiency
- **Persistent Output**: `println()` API for messages that persist above the UI
- **Cross-thread Rendering**: `request_render()` for async/multi-threaded apps
- **Rich Components**: Box, Text, List, Table, Tabs, Progress, Sparkline, BarChart, and more
- **Mouse Support**: Full mouse event handling
- **Cross-platform**: Works on Linux, macOS, and Windows

## Quick Start

Add to your `Cargo.toml`:

```toml
[dependencies]
rnk = "0.6"
```

## Examples

### Hello World

```rust
use rnk::prelude::*;

fn main() -> std::io::Result<()> {
    render(app).run()
}

fn app() -> Element {
    Box::new()
        .padding(1)
        .border_style(BorderStyle::Round)
        .child(Text::new("Hello, rnk!").color(Color::Green).bold().into_element())
        .into_element()
}
```

### Counter with Keyboard Input

```rust
use rnk::prelude::*;

fn main() -> std::io::Result<()> {
    render(app).run()
}

fn app() -> Element {
    let count = use_signal(|| 0i32);
    let app = use_app();

    use_input(move |input, key| {
        if input == "q" {
            app.exit();
        } else if key.up_arrow {
            count.update(|c| *c += 1);
        } else if key.down_arrow {
            count.update(|c| *c -= 1);
        }
    });

    Box::new()
        .flex_direction(FlexDirection::Column)
        .padding(1)
        .child(Text::new(format!("Count: {}", count.get())).bold().into_element())
        .child(Text::new("↑/↓ to change, q to quit").dim().into_element())
        .into_element()
}
```

### Streaming Output Demo

```rust
use rnk::prelude::*;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    // Background thread for periodic updates
    std::thread::spawn(|| {
        let mut tick = 0u32;
        loop {
            std::thread::sleep(Duration::from_millis(100));
            tick += 1;
            rnk::request_render();

            // Print persistent log every 20 ticks
            if tick % 20 == 0 {
                rnk::println(format!("[LOG] Tick {} completed", tick));
            }
        }
    });

    render(app).run()
}

fn app() -> Element {
    let counter = use_signal(|| 0);
    counter.set(counter.get() + 1);

    Box::new()
        .child(Text::new(format!("Frame: {}", counter.get())).into_element())
        .into_element()
}
```

## Render Modes

### Inline Mode (Default)

Output appears at current cursor position and persists in terminal history.

```rust
render(app).run()?;           // Inline mode (default)
render(app).inline().run()?;  // Explicit inline mode
```

### Fullscreen Mode

Uses alternate screen buffer. Content is cleared on exit.

```rust
render(app).fullscreen().run()?;
```

### Configuration Options

```rust
render(app)
    .fullscreen()           // Use alternate screen
    .fps(30)                // Target 30 FPS (default: 60)
    .exit_on_ctrl_c(false)  // Handle Ctrl+C manually
    .run()?;
```

### Runtime Mode Switching

Switch between modes at runtime:

```rust
let app = use_app();

use_input(move |input, _key| {
    if input == " " {
        if rnk::is_alt_screen().unwrap_or(false) {
            rnk::exit_alt_screen();  // Switch to inline
        } else {
            rnk::enter_alt_screen(); // Switch to fullscreen
        }
    }
});
```

## Render APIs

### Interactive Applications

```rust
// Run interactive TUI application
render(app).run()?;
```

### Static Rendering (Non-interactive)

Render elements to string without running the event loop:

```rust
use rnk::prelude::*;

let element = Box::new()
    .border_style(BorderStyle::Round)
    .child(Text::new("Hello!").into_element())
    .into_element();

// Render with specific width
let output = rnk::render_to_string(&element, 80);
println!("{}", output);

// Render with auto-detected terminal width
let output = rnk::render_to_string_auto(&element);
println!("{}", output);
```

## Components

### Box

Flexbox container with full layout support.

```rust
Box::new()
    .flex_direction(FlexDirection::Column)
    .justify_content(JustifyContent::Center)
    .align_items(AlignItems::Center)
    .padding(1)
    .margin(1.0)
    .width(50)
    .height(10)
    .border_style(BorderStyle::Round)
    .border_color(Color::Cyan)
    .background(Color::Ansi256(236))
    .child(/* ... */)
    .into_element()
```

**Border Styles**: `None`, `Single`, `Double`, `Round`, `Bold`, `Custom(chars)`

**Per-side Border Colors**:
```rust
Box::new()
    .border_style(BorderStyle::Single)
    .border_top_color(Color::Red)
    .border_bottom_color(Color::Blue)
    .border_left_color(Color::Green)
    .border_right_color(Color::Yellow)
```

### Text

Styled text with colors and formatting.

```rust
Text::new("Hello, World!")
    .color(Color::Green)
    .background_color(Color::Black)
    .bold()
    .italic()
    .underline()
    .strikethrough()
    .dim()
    .into_element()
```

**Rich Text with Spans**:
```rust
Text::builder()
    .span("Normal ")
    .span_styled("bold", |s| s.bold())
    .span(" and ")
    .span_styled("colored", |s| s.color(Color::Cyan))
    .build()
    .into_element()
```

### List

Selectable list with keyboard navigation.

```rust
List::new()
    .items(vec!["Item 1", "Item 2", "Item 3"])
    .selected(current_index)
    .highlight_style(|s| s.color(Color::Cyan).bold())
    .on_select(|idx| { /* handle selection */ })
    .into_element()
```

### Table

Data table with headers and styling.

```rust
Table::new()
    .headers(vec!["Name", "Age", "City"])
    .rows(vec![
        vec!["Alice", "30", "NYC"],
        vec!["Bob", "25", "LA"],
    ])
    .column_widths(vec![20, 10, 15])
    .header_style(|s| s.bold().color(Color::Yellow))
    .into_element()
```

### Tabs

Tab navigation component.

```rust
Tabs::new()
    .tabs(vec!["Home", "Settings", "About"])
    .selected(current_tab)
    .on_change(|idx| { /* handle tab change */ })
    .into_element()
```

### Progress / Gauge

Progress bars and gauges.

```rust
// Simple progress bar
Progress::new()
    .progress(0.75)  // 75%
    .width(30)
    .filled_char('█')
    .empty_char('░')
    .into_element()

// Gauge with label
Gauge::new()
    .ratio(0.5)
    .label("50%")
    .into_element()
```

### Sparkline

Inline data visualization.

```rust
Sparkline::new()
    .data(&[1, 3, 7, 2, 5, 8, 4])
    .width(20)
    .into_element()
```

### BarChart

Horizontal and vertical bar charts.

```rust
BarChart::new()
    .data(&[("A", 10), ("B", 20), ("C", 15)])
    .bar_width(3)
    .bar_gap(1)
    .into_element()
```

### Static

Permanent output that persists above dynamic UI.

```rust
Static::new(
    items.to_vec(),
    |item, index| {
        Text::new(format!("[{}] {}", index + 1, item))
            .color(Color::Gray)
            .into_element()
    }
).into_element()
```

### Transform

Transform child text content.

```rust
Transform::new(|s| s.to_uppercase())
    .child(Text::new("will be uppercase").into_element())
    .into_element()
```

### Spacer / Newline

Layout helpers.

```rust
Box::new()
    .flex_direction(FlexDirection::Row)
    .child(Text::new("Left").into_element())
    .child(Spacer::new().into_element())  // Flexible space
    .child(Text::new("Right").into_element())
    .into_element()

// Add vertical space
Newline::new().into_element()
```

### Spinner

Animated loading indicator.

```rust
Spinner::new()
    .style(SpinnerStyle::Dots)
    .label("Loading...")
    .into_element()
```

### Message

Styled message boxes for info, success, warning, error.

```rust
Message::info("Information message")
Message::success("Operation completed!")
Message::warning("Please be careful")
Message::error("Something went wrong")
```

## Hooks

### use_signal

Reactive state management.

```rust
let count = use_signal(|| 0);

// Read value
let value = count.get();

// Update value
count.set(value + 1);

// Update with function
count.update(|v| *v += 1);
```

### use_effect

Side effects with dependencies.

```rust
let data = use_signal(|| Vec::new());

use_effect(
    move || {
        // Effect runs when dependencies change
        println!("Data loaded: {:?}", data.get());

        // Optional cleanup
        Some(Box::new(|| {
            println!("Cleanup");
        }))
    },
    vec![data.get().len()],  // Dependencies
);
```

### use_input

Keyboard input handling.

```rust
use_input(move |input, key| {
    if input == "q" {
        // quit
    } else if key.return_key {
        // submit
    } else if key.up_arrow {
        // move up
    } else if key.down_arrow {
        // move down
    }
});
```

**Key struct fields**:
- `up_arrow`, `down_arrow`, `left_arrow`, `right_arrow`
- `page_up`, `page_down`, `home`, `end`
- `return_key`, `escape`, `tab`, `backspace`, `delete`
- `ctrl`, `shift`, `alt` (modifier keys)

### use_mouse

Mouse event handling.

```rust
use_mouse(move |mouse| {
    match mouse.action {
        MouseAction::Press(MouseButton::Left) => {
            println!("Clicked at ({}, {})", mouse.x, mouse.y);
        }
        MouseAction::Move => { /* handle hover */ }
        MouseAction::ScrollUp => { /* scroll up */ }
        MouseAction::ScrollDown => { /* scroll down */ }
        _ => {}
    }
});
```

### use_focus

Focus management for form inputs.

```rust
let focus_state = use_focus(UseFocusOptions {
    auto_focus: true,
    is_active: true,
    id: None,
});

if focus_state.is_focused {
    // Component is focused
}
```

### use_scroll

Scroll state management.

```rust
let scroll = use_scroll();

// Configure content and viewport sizes
scroll.set_content_size(100, 500);
scroll.set_viewport_size(80, 20);

use_input(move |_input, key| {
    if key.up_arrow {
        scroll.scroll_up(1);
    } else if key.down_arrow {
        scroll.scroll_down(1);
    } else if key.page_up {
        scroll.page_up();
    } else if key.page_down {
        scroll.page_down();
    }
});

// Get current scroll position
let offset_y = scroll.offset_y();
```

### use_app

Application control.

```rust
let app = use_app();

use_input(move |input, _key| {
    if input == "q" {
        app.exit();  // Exit the application
    }
});
```

### use_cmd

Elm-inspired command system for side effects (async tasks, timers, file I/O).

```rust
use rnk::prelude::*;
use rnk::cmd::Cmd;
use std::time::Duration;

fn app() -> Element {
    let status = use_signal(|| "Ready".to_string());
    let data = use_signal(|| None::<String>);

    // Run command when status changes
    use_cmd(status.get(), move |_| {
        Cmd::batch(vec![
            // Delay for 1 second
            Cmd::sleep(Duration::from_secs(1)),
            // Then perform async task
            Cmd::perform(
                async {
                    // Simulate async work
                    "Data loaded!".to_string()
                },
                move |result| {
                    data.set(Some(result));
                },
            ),
        ])
    });

    Box::new()
        .child(Text::new(format!("Status: {}", status.get())).into_element())
        .child(Text::new(format!("Data: {:?}", data.get())).into_element())
        .into_element()
}
```

**Available Commands**:

```rust
// No-op command
Cmd::none()

// Batch multiple commands
Cmd::batch(vec![cmd1, cmd2, cmd3])

// Delay execution
Cmd::sleep(Duration::from_secs(1))

// Async task with callback
Cmd::perform(async { /* work */ }, |result| { /* handle result */ })

// Chain commands
cmd.and_then(|| another_cmd)

// File operations
Cmd::read_file("path.txt", |content| { /* handle content */ })
Cmd::write_file("path.txt", "content", |success| { /* handle result */ })

// Spawn process
Cmd::spawn("ls", vec!["-la"], |output| { /* handle output */ })
```

### use_window_title

Set terminal window title.

```rust
use_window_title("My TUI App");
```

## Cross-thread Rendering

When updating state from background threads:

```rust
use std::thread;
use std::sync::{Arc, RwLock};

fn main() -> std::io::Result<()> {
    let shared_data = Arc::new(RwLock::new(String::new()));
    let data_clone = Arc::clone(&shared_data);

    thread::spawn(move || {
        loop {
            // Update shared state
            *data_clone.write().unwrap() = fetch_data();

            // Notify rnk to re-render
            rnk::request_render();

            thread::sleep(Duration::from_secs(1));
        }
    });

    render(move || app(&shared_data)).run()
}
```

## Println API

Print persistent messages above the UI (inline mode only):

```rust
// Simple text
rnk::println("Task completed!");

// Formatted text
rnk::println(format!("Downloaded {} files", count));

// Rich elements
let banner = Box::new()
    .border_style(BorderStyle::Round)
    .child(Text::new("Success!").color(Color::Green).into_element())
    .into_element();
rnk::println(banner);
```

## Colors

```rust
// Basic colors
Color::Black, Color::Red, Color::Green, Color::Yellow,
Color::Blue, Color::Magenta, Color::Cyan, Color::White,
Color::Gray

// 256 colors
Color::Ansi256(240)  // 0-255

// RGB colors
Color::Rgb { r: 255, g: 128, b: 0 }
```

## Testing

rnk provides testing utilities for verifying UI components:

```rust
use rnk::testing::{TestRenderer, assert_layout_valid};

#[test]
fn test_component() {
    let element = my_component();

    // Validate layout
    let renderer = TestRenderer::new(80, 24);
    renderer.validate_layout(&element).expect("valid layout");

    // Check rendered output
    let output = rnk::render_to_string(&element, 80);
    assert!(output.contains("expected text"));
}
```

## Running Examples

```bash
# Hello world
cargo run --example hello

# Interactive counter
cargo run --example counter

# Streaming output demo
cargo run --example streaming_demo

# Static rendering API demo
cargo run --example render_api_demo

# GLM chat demo
cargo run --example glm_chat
```

## Architecture

```
src/
├── components/     # UI components (Box, Text, List, etc.)
├── core/           # Element, Style, Color primitives
├── hooks/          # React-like hooks (use_signal, use_effect, etc.)
├── layout/         # Taffy-based flexbox layout engine
├── renderer/       # Terminal rendering, App runner
└── testing/        # Test utilities
```

## Comparison with Ink/Bubbletea

| Feature | rnk | Ink | Bubbletea |
|---------|-----|-----|-----------|
| Language | Rust | JavaScript | Go |
| Rendering | Line-level diff | Line-level diff | Line-level diff |
| Layout | Flexbox (Taffy) | Flexbox (Yoga) | Manual |
| State | Hooks | React hooks | Model-Update |
| Inline mode ||||
| Fullscreen ||||
| Println || Static component | tea.Println |
| Cross-thread | request_render() | - | tea.Program.Send |

## License

MIT