reratui 0.2.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
<div align="center">

<img src=".github/reratui-light.png" alt="Reratui Logo" width="300"/>

# Reratui

**A Modern, Reactive TUI Framework for Rust**

[![Crates.io](https://img.shields.io/crates/v/reratui.svg)](https://crates.io/crates/reratui)
[![Documentation](https://docs.rs/reratui/badge.svg)](https://docs.rs/reratui)
[![License](https://img.shields.io/crates/l/reratui.svg)](https://github.com/sabry-awad97/reratui#license)
[![Build Status](https://img.shields.io/github/workflow/status/sabry-awad97/reratui/CI)](https://github.com/sabry-awad97/reratui/actions)

_Build beautiful, interactive terminal applications with React-inspired components and hooks_

[Getting Started](#quick-start) β€’ [Documentation](#documentation) β€’ [Examples](#examples) β€’ [Contributing](#contributing)

</div>

---

## Overview

Reratui brings modern web development patterns to terminal user interfaces. Inspired by React, it provides a component-based architecture with hooks, enabling you to build complex, stateful TUI applications with clean, maintainable code.

### Why Reratui?

- 🎨 **Declarative UI** - Build interfaces with JSX-like syntax using the `rsx!` macro
- πŸͺ **React-Style Hooks** - Manage state and side effects with familiar patterns
- ⚑ **High Performance** - Zero-cost abstractions with compile-time optimizations
- πŸ”’ **Type-Safe** - Leverage Rust's type system for compile-time correctness
- πŸ”„ **Async-First** - Built on Tokio with first-class async/await support
- 🧩 **Modular** - Compose complex UIs from simple, reusable components

## ✨ Features

<table>
<tr>
<td width="50%">

### πŸ—οΈ Component System

- Component-based architecture with lifecycle hooks
- Reusable, composable components
- Type-safe props with `#[derive(Props)]`
- Automatic prop validation

</td>
<td width="50%">

### πŸͺ Comprehensive Hooks

- State management (`use_state`, `use_reducer`)
- Side effects (`use_effect`, `use_async_effect`)
- Performance (`use_memo`, `use_callback`)
- Events (keyboard, mouse, resize)

</td>
</tr>
<tr>
<td width="50%">

### 🎯 Developer Experience

- JSX-like `rsx!` macro syntax
- Compile-time hook rules validation
- Comprehensive error messages
- Hot-reload support (coming soon)

</td>
<td width="50%">

### ⚑ Performance

- Zero-cost abstractions
- Compile-time macro expansion
- Efficient event handling
- Minimal runtime overhead

</td>
</tr>
</table>

<details>
<summary><b>πŸ“š Complete Hooks Reference</b> (click to expand)</summary>

<br/>

| Category        | Hook                      | Description                                    |
| --------------- | ------------------------- | ---------------------------------------------- |
| **State**       | `use_state`               | Local component state management               |
|                 | `use_reducer`             | Complex state logic with actions (Redux-style) |
|                 | `use_ref`                 | Mutable references that persist across renders |
| **Effects**     | `use_effect`              | Side effects with dependency tracking          |
|                 | `use_effect_once`         | Run effect only on mount                       |
|                 | `use_async_effect`        | Async side effects with cleanup                |
| **Performance** | `use_callback`            | Memoized callbacks to prevent re-renders       |
|                 | `use_memo`                | Memoized computed values                       |
|                 | `use_effect_event`        | Stable event handlers with latest values       |
| **Context**     | `use_context`             | Access shared data without prop drilling       |
|                 | `use_context_provider`    | Provide context values to children             |
| **Events**      | `use_event`               | Generic terminal event handling                |
|                 | `use_keyboard`            | Keyboard events with stable callbacks          |
|                 | `use_keyboard_press`      | Handle key press events only                   |
|                 | `use_keyboard_shortcut`   | Specific key combinations                      |
|                 | `use_mouse`               | Mouse events with stable callbacks             |
|                 | `use_mouse_click`         | Handle mouse click events                      |
|                 | `use_mouse_drag`          | Track drag operations                          |
|                 | `use_double_click`        | Detect double-click gestures                   |
|                 | `on_global_event`         | Global keyboard event handlers                 |
| **Layout**      | `use_frame`               | Frame timing and render context                |
|                 | `use_area`                | Component's rendering area                     |
|                 | `use_on_resize`           | Handle terminal resize events                  |
|                 | `use_terminal_dimensions` | Current terminal size                          |

</details>

## πŸš€ Installation

Add Reratui to your `Cargo.toml`:

```toml
[dependencies]
reratui = "0.1.0"
tokio = { version = "1", features = ["full"] }
```

> **Note:** The main `reratui` crate re-exports all necessary functionality. You typically don't need to add individual sub-crates.

## πŸ“– Quick Start

### Your First Component

```rust
use reratui::prelude::*;

#[component]
fn Counter() -> Element {
    let (count, set_count) = use_state(|| 0);

    // Handle keyboard events
    if let Some(Event::Key(key)) = use_event()
        && key.is_press()
    {
        match key.code {
            KeyCode::Char('j') => set_count.update(|n| n + 1),
            KeyCode::Char('k') => set_count.update(|n| n - 1),
            KeyCode::Char('r') => set_count.set(0),
            _ => {}
        }
    }

    rsx! {
        <Block
            title="Counter Demo"
            borders={Borders::ALL}
            border_style={Style::default().fg(Color::Cyan)}
        >
            <Paragraph alignment={Alignment::Center}>
                {format!("Count: {}", count.get())}
            </Paragraph>
            <Paragraph alignment={Alignment::Center}>
                {"Press 'j' to increment, 'k' to decrement, 'r' to reset"}
            </Paragraph>
        </Block>
    }
}

#[reratui::main]
async fn main() -> Result<()> {
    render(|| rsx! { <Counter /> }).await?;
    Ok(())
}
```

### Component with Props

```rust
use reratui::prelude::*;

#[derive(Props)]
struct ButtonProps {
    label: String,
    on_click: Option<Callback<()>>,
}

#[component]
fn Button(props: &ButtonProps) -> Element {
    rsx! {
        <Block borders={Borders::ALL}>
            <Paragraph alignment={Alignment::Center}>
                {format!("[ {} ]", props.label)}
            </Paragraph>
        </Block>
    }
}

#[component]
fn App() -> Element {
    let (clicks, set_clicks) = use_state(|| 0);

    rsx! {
        <Layout direction={Direction::Vertical}>
            <Button
                label={format!("Clicked {} times", clicks.get())}
                on_click={move |_| set_clicks.update(|n| n + 1)}
            />
        </Layout>
    }
}
```

## πŸŽ“ Advanced Usage

### Complex State with Reducers

```rust
use reratui::prelude::*;

#[derive(Clone)]
enum TodoAction {
    Add(String),
    Toggle(usize),
    Remove(usize),
}

#[derive(Clone)]
struct TodoState {
    todos: Vec<Todo>,
    next_id: usize,
}

fn todo_reducer(state: TodoState, action: TodoAction) -> TodoState {
    match action {
        TodoAction::Add(text) => TodoState {
            todos: {
                let mut todos = state.todos;
                todos.push(Todo { id: state.next_id, text, completed: false });
                todos
            },
            next_id: state.next_id + 1,
        },
        TodoAction::Toggle(id) => TodoState {
            todos: state.todos.into_iter().map(|mut todo| {
                if todo.id == id {
                    todo.completed = !todo.completed;
                }
                todo
            }).collect(),
            ..state
        },
        TodoAction::Remove(id) => TodoState {
            todos: state.todos.into_iter().filter(|t| t.id != id).collect(),
            ..state
        },
    }
}

#[component]
fn TodoApp() -> Element {
    let (state, dispatch) = use_reducer(
        todo_reducer,
        TodoState { todos: vec![], next_id: 1 }
    );

    // Use state and dispatch in your component...
}
```

### Context for Global State

Share state across components without prop drilling:

```rust
#[component]
fn App() -> Element {
    let theme = use_context_provider(|| Theme::Dark);

    rsx! {
        <Layout>
            <Header />
            <Content />
        </Layout>
    }
}

#[component]
fn Header() -> Element {
    let theme = use_context::<Theme>();
    // Use theme...
}
```

## πŸ›οΈ Architecture

Reratui follows a modular, layered architecture with clear separation of concerns:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           reratui (Main Crate)              β”‚  ← Public API
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  reratui-macro  β”‚  reratui-hooks            β”‚  ← Developer Tools
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  reratui-core   β”‚  reratui-runtime          β”‚  ← Core Engine
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚         reratui-ratatui (Backend)           β”‚  ← Rendering
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Crate Structure

| Crate             | Purpose                                       |
| ----------------- | --------------------------------------------- |
| `reratui`         | Main crate - re-exports all functionality     |
| `reratui-core`    | Core types (Element, Component, VNode)        |
| `reratui-macro`   | Procedural macros (#[component], rsx!, Props) |
| `reratui-hooks`   | Hook implementations and state management     |
| `reratui-runtime` | Event loop, lifecycle, and rendering runtime  |
| `reratui-ratatui` | Ratatui backend integration                   |

### Design Principles

| Principle       | Implementation                                                     |
| --------------- | ------------------------------------------------------------------ |
| **SOLID**       | Single responsibility, interface segregation, dependency inversion |
| **DDD**         | Clear domain boundaries with well-defined interfaces               |
| **Composition** | Build complex UIs by composing simple components                   |
| **Type Safety** | Leverage Rust's type system for compile-time correctness           |
| **Zero-Cost**   | No runtime overhead for abstractions                               |

## πŸ’‘ Examples

Explore complete, runnable examples in the [`examples/`](./examples) directory:

| Example             | Description                                       | Command                               |
| ------------------- | ------------------------------------------------- | ------------------------------------- |
| **counter**         | Basic state management and keyboard events        | `cargo run --example counter`         |
| **rsx_demo**        | Comprehensive RSX macro features                  | `cargo run --example rsx_demo`        |
| **events_showcase** | Complete event handling (keyboard, mouse, resize) | `cargo run --example events_showcase` |
| **router**          | Navigation and routing                            | Coming soon                           |

## πŸ“š Documentation

| Resource                                     | Description                          |
| -------------------------------------------- | ------------------------------------ |
| [**API Docs**]https://docs.rs/reratui      | Complete API reference with examples |
| [**Examples**]./examples                   | Working code examples and demos      |
| [**Hooks Guide**]./docs/hooks.md           | Detailed hook usage patterns         |
| [**Component Patterns**]./docs/patterns.md | Best practices and design patterns   |

## πŸ”§ Requirements

**Minimum Supported Rust Version (MSRV): 1.75.0**

Required for:

- `let`-`else` statements
- `let` chains in `if` expressions
- Edition 2024 features

## 🀝 Contributing

We welcome contributions! See our [Contributing Guide](./CONTRIBUTING.md) for:

- πŸ“œ Code of conduct
- πŸ› οΈ Development setup
- βœ… Testing requirements
- πŸ”„ Pull request process

## πŸ—ΊοΈ Roadmap

### βœ… Completed

- [x] Core component system with lifecycle hooks (`on_mount`, `on_unmount`)
- [x] Comprehensive hooks system (state, effect, reducer, context)
- [x] RSX macro with conditional rendering
- [x] Hook rules validation at compile-time
- [x] Event handling (keyboard, mouse, resize)
- [x] Global event system for application-wide shortcuts

### 🚧 In Progress

- [ ] Router with nested routes
- [ ] Form validation helpers
- [ ] Animation system

### πŸ“‹ Planned

- [ ] Dev tools and debugging utilities
- [ ] Performance profiling tools
- [ ] Hot-reload support
- [ ] Component testing utilities

## πŸ“„ License

Dual-licensed under your choice of:

- **Apache License 2.0** ([LICENSE-APACHE]LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- **MIT License** ([LICENSE-MIT]LICENSE-MIT or http://opensource.org/licenses/MIT)

Unless explicitly stated otherwise, any contribution intentionally submitted for inclusion shall be dual licensed as above, without additional terms or conditions.

---

## πŸ™ Acknowledgments

Reratui stands on the shoulders of giants:

- **[Ratatui]https://github.com/ratatui-org/ratatui** - The powerful TUI library that powers our rendering
- **[React]https://react.dev/** - Inspiration for component architecture and hooks patterns
- **[Yew]https://yew.rs/** - Rust web framework with similar design patterns

---

<div align="center">

**Built with ❀️ by the Rust community**

[⭐ Star us on GitHub](https://github.com/sabry-awad97/reratui) β€’ [πŸ“– Read the Docs](https://docs.rs/reratui) β€’ [πŸ’¬ Join Discussions](https://github.com/sabry-awad97/reratui/discussions)

</div>