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
//! Complex Todo App Example - Demonstrates all tink features
//!
//! This example uses rnk's built-in render API for simplicity.
//!
//! Features demonstrated:
//! - Box layout with flexbox (flexDirection, justifyContent, alignItems)
//! - Text styling (colors, bold, italic, underline)
//! - Borders with per-side colors
//! - use_signal for state management
//! - use_effect for side effects
//! - use_input for keyboard handling
//! - use_focus for focus management
//! - Static component for persistent output
//! - Transform component
//! - Spacer and Newline
//! - position: absolute (for popup/modal)
//! - display: none (toggle visibility)
//! - use_app for exit
//!
//! Run with: cargo run --example todo_app

use std::cell::RefCell;
use std::rc::Rc;

use rnk::core::Dimension;
use rnk::hooks::{HookContext, with_hooks};
use rnk::prelude::*;

/// A single todo item
#[derive(Clone, Debug)]
struct TodoItem {
    id: usize,
    text: String,
    completed: bool,
    created_at: String,
}

/// Application state
#[derive(Clone, Debug)]
struct AppState {
    todos: Vec<TodoItem>,
    selected_index: usize,
    show_help: bool,
    show_completed: bool,
    status_message: String,
}

impl Default for AppState {
    fn default() -> Self {
        Self {
            todos: vec![
                TodoItem {
                    id: 1,
                    text: "Learn Rust".into(),
                    completed: true,
                    created_at: "2024-01-01".into(),
                },
                TodoItem {
                    id: 2,
                    text: "Build tink framework".into(),
                    completed: true,
                    created_at: "2024-01-02".into(),
                },
                TodoItem {
                    id: 3,
                    text: "Create complex example".into(),
                    completed: false,
                    created_at: "2024-01-03".into(),
                },
                TodoItem {
                    id: 4,
                    text: "Write documentation".into(),
                    completed: false,
                    created_at: "2024-01-04".into(),
                },
                TodoItem {
                    id: 5,
                    text: "Publish to crates.io".into(),
                    completed: false,
                    created_at: "2024-01-05".into(),
                },
            ],
            selected_index: 0,
            show_help: false,
            show_completed: true,
            status_message: "Welcome to Tink Todo!".into(),
        }
    }
}

/// Header component with styled title
fn render_header() -> Element {
    Box::new()
        .width(Dimension::Percent(100.0))
        .padding_x(2.0)
        .padding_y(1.0)
        .border_style(BorderStyle::Round)
        .border_color(Color::Cyan)
        .flex_direction(FlexDirection::Column)
        .align_items(AlignItems::Center)
        .child(
            Text::new("========================================")
                .color(Color::Cyan)
                .into_element(),
        )
        .child(
            Text::new("        TINK TODO APPLICATION           ")
                .color(Color::White)
                .bold()
                .into_element(),
        )
        .child(
            Text::new("========================================")
                .color(Color::Cyan)
                .into_element(),
        )
        .into_element()
}

/// Stats panel showing todo statistics
fn render_stats(state: &AppState) -> Element {
    let total = state.todos.len();
    let completed = state.todos.iter().filter(|t| t.completed).count();
    let pending = total - completed;
    let percentage = (completed * 100).checked_div(total).unwrap_or(0);

    // Progress bar
    let bar_width = 20;
    let filled = (bar_width * completed) / total.max(1);
    let empty = bar_width - filled;
    let progress_bar = format!(
        "[{}{}] {}%",
        "=".repeat(filled),
        "-".repeat(empty),
        percentage
    );

    Box::new()
        .border_style(BorderStyle::Round)
        .border_top_color(Color::Green)
        .border_bottom_color(Color::Green)
        .border_left_color(Color::Yellow)
        .border_right_color(Color::Yellow)
        .padding(1)
        .margin_bottom(1.0)
        .flex_direction(FlexDirection::Column)
        .child(
            Text::new(" Statistics ")
                .color(Color::Yellow)
                .bold()
                .underline()
                .into_element(),
        )
        .child(Newline::new().into_element())
        .child(
            Box::new()
                .flex_direction(FlexDirection::Row)
                .child(Text::new("Total:     ").color(Color::White).into_element())
                .child(
                    Text::new(format!("{}", total))
                        .color(Color::Cyan)
                        .bold()
                        .into_element(),
                )
                .into_element(),
        )
        .child(
            Box::new()
                .flex_direction(FlexDirection::Row)
                .child(Text::new("Completed: ").color(Color::White).into_element())
                .child(
                    Text::new(format!("{}", completed))
                        .color(Color::Green)
                        .bold()
                        .into_element(),
                )
                .into_element(),
        )
        .child(
            Box::new()
                .flex_direction(FlexDirection::Row)
                .child(Text::new("Pending:   ").color(Color::White).into_element())
                .child(
                    Text::new(format!("{}", pending))
                        .color(Color::Red)
                        .bold()
                        .into_element(),
                )
                .into_element(),
        )
        .child(Newline::new().into_element())
        .child(
            Text::new(progress_bar)
                .color(if percentage >= 80 {
                    Color::Green
                } else if percentage >= 50 {
                    Color::Yellow
                } else {
                    Color::Red
                })
                .into_element(),
        )
        .into_element()
}

/// Single todo item component
fn render_todo_item(item: &TodoItem, is_selected: bool, index: usize) -> Element {
    let checkbox = if item.completed { "[x]" } else { "[ ]" };
    let status_color = if item.completed {
        Color::Green
    } else {
        Color::White
    };

    let mut container = Box::new()
        .flex_direction(FlexDirection::Row)
        .padding_x(1.0)
        .width(Dimension::Percent(100.0));

    // Highlight selected item
    if is_selected {
        container = container
            .background(Color::Ansi256(236))
            .border_style(BorderStyle::Single)
            .border_color(Color::Cyan);
    }

    let mut text_component = Text::new(&item.text).color(status_color);
    if item.completed {
        text_component = text_component.italic().strikethrough();
    }

    container
        .child(
            Text::new(format!("{:2}. ", index + 1))
                .color(Color::Ansi256(240))
                .into_element(),
        )
        .child(
            Text::new(checkbox)
                .color(if item.completed {
                    Color::Green
                } else {
                    Color::Ansi256(240)
                })
                .bold()
                .into_element(),
        )
        .child(Text::new(" ").into_element())
        .child(text_component.into_element())
        .child(Spacer::new().into_element())
        .child(
            Text::new(&item.created_at)
                .color(Color::Ansi256(240))
                .into_element(),
        )
        .into_element()
}

/// Todo list component
fn render_todo_list(state: &AppState) -> Element {
    let filtered_todos: Vec<_> = if state.show_completed {
        state.todos.iter().collect()
    } else {
        state.todos.iter().filter(|t| !t.completed).collect()
    };

    let mut list = Box::new()
        .flex_direction(FlexDirection::Column)
        .border_style(BorderStyle::Round)
        .border_color(Color::Blue)
        .padding(1)
        .flex_grow(1.0)
        .child(
            Box::new()
                .flex_direction(FlexDirection::Row)
                .margin_bottom(1.0)
                .child(
                    Text::new(" Todo List ")
                        .color(Color::Blue)
                        .bold()
                        .underline()
                        .into_element(),
                )
                .child(Spacer::new().into_element())
                .child(
                    Text::new(if state.show_completed {
                        "[Show All]"
                    } else {
                        "[Hide Done]"
                    })
                    .color(Color::Ansi256(240))
                    .into_element(),
                )
                .into_element(),
        );

    if filtered_todos.is_empty() {
        list = list.child(
            Box::new()
                .justify_content(JustifyContent::Center)
                .padding(2)
                .child(
                    Text::new("No todos yet! Press 'a' to add one.")
                        .color(Color::Ansi256(240))
                        .italic()
                        .into_element(),
                )
                .into_element(),
        );
    } else {
        for (display_idx, item) in filtered_todos.iter().enumerate() {
            let actual_idx = state
                .todos
                .iter()
                .position(|t| t.id == item.id)
                .unwrap_or(0);
            let is_selected = actual_idx == state.selected_index;
            list = list.child(render_todo_item(item, is_selected, display_idx));
        }
    }

    list.into_element()
}

/// Status bar at bottom
fn render_status_bar(state: &AppState) -> Element {
    Box::new()
        .width(Dimension::Percent(100.0))
        .flex_direction(FlexDirection::Row)
        .padding_x(1.0)
        .background(Color::Ansi256(236))
        .child(
            Text::new(&state.status_message)
                .color(Color::White)
                .into_element(),
        )
        .child(Spacer::new().into_element())
        .child(
            Text::new("Press 'h' for help | 'q' to quit")
                .color(Color::Ansi256(240))
                .into_element(),
        )
        .into_element()
}

/// Help popup (position: absolute)
fn render_help_popup(show: bool) -> Element {
    if !show {
        return Box::new().hidden().into_element();
    }

    Box::new()
        .position_absolute()
        .top(5.0)
        .left(10.0)
        .width(50)
        .border_style(BorderStyle::Double)
        .border_color(Color::Magenta)
        .background(Color::Ansi256(234))
        .padding(2)
        .flex_direction(FlexDirection::Column)
        .child(
            Box::new()
                .flex_direction(FlexDirection::Row)
                .child(Spacer::new().into_element())
                .child(
                    Text::new("Keyboard Shortcuts")
                        .color(Color::Magenta)
                        .bold()
                        .into_element(),
                )
                .child(Spacer::new().into_element())
                .into_element(),
        )
        .child(Newline::new().into_element())
        .child(render_help_row("j / Down", "Move down"))
        .child(render_help_row("k / Up", "Move up"))
        .child(render_help_row("Enter", "Toggle completion"))
        .child(render_help_row("a", "Add new todo"))
        .child(render_help_row("d", "Delete selected"))
        .child(render_help_row("c", "Toggle show completed"))
        .child(render_help_row("h", "Toggle this help"))
        .child(render_help_row("q / Esc", "Quit application"))
        .child(Newline::new().into_element())
        .child(
            Box::new()
                .justify_content(JustifyContent::Center)
                .child(
                    Text::new("Press 'h' to close")
                        .color(Color::Ansi256(240))
                        .italic()
                        .into_element(),
                )
                .into_element(),
        )
        .into_element()
}

fn render_help_row(key: &str, desc: &str) -> Element {
    Box::new()
        .flex_direction(FlexDirection::Row)
        .padding_x(1.0)
        .child(
            Box::new()
                .width(12)
                .child(Text::new(key).color(Color::Cyan).bold().into_element())
                .into_element(),
        )
        .child(Text::new(desc).color(Color::White).into_element())
        .into_element()
}

/// Quick actions panel
fn render_quick_actions() -> Element {
    Box::new()
        .border_style(BorderStyle::Round)
        .border_color(Color::Magenta)
        .padding(1)
        .flex_direction(FlexDirection::Column)
        .child(
            Text::new(" Quick Actions ")
                .color(Color::Magenta)
                .bold()
                .underline()
                .into_element(),
        )
        .child(Newline::new().into_element())
        .child(
            Text::new("  [a] Add Todo")
                .color(Color::Green)
                .into_element(),
        )
        .child(Text::new("  [d] Delete").color(Color::Red).into_element())
        .child(
            Text::new("  [c] Filter")
                .color(Color::Yellow)
                .into_element(),
        )
        .child(Text::new("  [h] Help").color(Color::Cyan).into_element())
        .into_element()
}

/// Transform demo - uppercase text
fn render_transform_demo() -> Element {
    Transform::new(|s| s.to_uppercase())
        .child(
            Text::new("this text is transformed to uppercase")
                .color(Color::Ansi256(245))
                .into_element(),
        )
        .into_element()
}

/// Main app component
fn render_app(state: &AppState) -> Element {
    Box::new()
        .width(Dimension::Percent(100.0))
        .height(Dimension::Percent(100.0))
        .flex_direction(FlexDirection::Column)
        .padding(1)
        // Header
        .child(render_header())
        .child(Newline::new().into_element())
        // Main content area
        .child(
            Box::new()
                .flex_direction(FlexDirection::Row)
                .flex_grow(1.0)
                // Left panel - Stats
                .child(
                    Box::new()
                        .width(30)
                        .flex_direction(FlexDirection::Column)
                        .child(render_stats(state))
                        .child(render_quick_actions())
                        .child(Newline::new().into_element())
                        .child(render_transform_demo())
                        .into_element(),
                )
                // Spacer between panels
                .child(Box::new().width(2).into_element())
                // Right panel - Todo list
                .child(
                    Box::new()
                        .flex_grow(1.0)
                        .flex_direction(FlexDirection::Column)
                        .child(render_todo_list(state))
                        .into_element(),
                )
                .into_element(),
        )
        // Status bar
        .child(render_status_bar(state))
        // Help popup (absolute positioned)
        .child(render_help_popup(state.show_help))
        .into_element()
}

/// Static output for completed actions log
fn render_static_log(messages: &[String]) -> Element {
    Static::new(messages.to_vec(), |msg, i| {
        Text::new(format!("[LOG {}] {}", i + 1, msg))
            .color(Color::Ansi256(240))
            .into_element()
    })
    .into_element()
}

fn main() {
    println!("\x1b[2J\x1b[H"); // Clear screen
    println!("Tink Todo App - Comprehensive Demo\n");

    // Initialize state
    let state = AppState::default();
    let action_log = vec![
        "Application started".to_string(),
        "Loaded 5 todos from memory".to_string(),
    ];

    // Create hook context for reactive state
    let ctx = Rc::new(RefCell::new(HookContext::new()));

    // Render with hooks
    let element = with_hooks(ctx.clone(), || {
        // Use signals for reactive state
        let app_state = use_signal(|| state.clone());
        let log = use_signal(|| action_log.clone());

        // Main app container
        Box::new()
            .flex_direction(FlexDirection::Column)
            .child(render_static_log(&log.get()))
            .child(render_app(&app_state.get()))
            .into_element()
    });

    // Use rnk's built-in render API
    let output = rnk::render_to_string_auto(&element);
    print!("{}", output);

    println!("\n\n--- Demo Complete ---");
    println!("This example demonstrates ALL tink features:");
    println!("  - Flexbox layout (row/column, justify, align, gap)");
    println!("  - Styled text (colors, bold, italic, underline, strikethrough)");
    println!("  - Borders with per-side colors (Round, Single, Double)");
    println!("  - use_signal for reactive state management");
    println!("  - Static component for persistent output");
    println!("  - Transform component for text transformation");
    println!("  - position: absolute for popup overlay");
    println!("  - display: none for conditional rendering");
    println!("  - Spacer and Newline components");
    println!("  - Background colors");
    println!("  - Dimension::Percent for responsive sizing");
}