eye_declare 0.2.1

Declarative inline TUI rendering library for Rust
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
# eye-declare

A declarative inline TUI rendering library for Rust, built on [Ratatui](https://ratatui.rs).

eye-declare provides a React-like component model for building terminal UIs that render **inline** — content grows into the terminal's native scrollback rather than taking over the full screen. Designed for CLI tools, AI assistants, and interactive prompts where output accumulates and earlier results should remain visible.

![Demo](https://github.com/BinaryMuse/eye-declare/blob/main/assets/demo.gif?raw=true)

## Status

eye-declare is in early development; expect breaking changes.

Coming changes:

- [ ] More ergonomic "leaf" API
- [ ] Improvements to height measurement and vertical layout

## Quick Start

```rust
use eye_declare::{element, Application, ControlFlow, Elements, Spinner, TextBlock};

struct AppState {
    messages: Vec<String>,
    thinking: bool,
}

fn chat_view(state: &AppState) -> Elements {
    element! {
        #(for (i, msg) in state.messages.iter().enumerate() {
            TextBlock {
                Line {
                    Span(text: msg.clone())
                }
            }
        })
        #(if state.thinking {
            Spinner(key: "thinking", label: "Thinking...")
        })
    }
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let (mut app, handle) = Application::builder()
        .state(AppState { messages: vec![], thinking: false })
        .view(chat_view)
        .build()?;

    // Send updates from any thread or async task
    tokio::spawn(async move {
        handle.update(|s| s.messages.push("Hello from eye_declare!".into()));
    });

    app.run().await
}
```

## The `element!` Macro

The `element!` macro is the primary way to build UIs. It provides JSX-like syntax for composing component trees:

```rust
fn dashboard(state: &DashboardState) -> Elements {
    element! {
        VStack {
            "Dashboard"

            #(for (i, item) in state.items.iter().enumerate() {
                Markdown(key: format!("item-{i}"), source: item.clone())
            })

            #(if state.loading {
                Spinner(label: "Refreshing...")
            })

            #(if let Some(ref err) = state.error {
                Markdown(source: err.clone())
            })

            #(footer_view(state))
        }
    }
}
```

### Syntax reference

| Syntax | Description |
|--------|-------------|
| `Component(prop: value)` | Construct with props (struct field init) |
| `Component { ... }` | Component with children |
| `Component(props) { children }` | Both |
| `"text"` | String literal — auto-wrapped as `TextBlock` |
| `key: expr` | Special prop for stable identity across rebuilds |
| `#(if cond { ... })` | Conditional children |
| `#(if let pat = expr { ... })` | Pattern-matching conditional |
| `#(for pat in iter { ... })` | Loop children |
| `#(expr)` | Splice a pre-built `Elements` value inline |

## Components

Components are the building blocks. Props live on `&self` (immutable, set by parent). Internal state lives in the associated `State` type (mutable, framework-managed via automatic dirty tracking).

```rust
use eye_declare::Component;
use ratatui_core::{buffer::Buffer, layout::Rect, style::Style, widgets::Widget};
use ratatui_widgets::paragraph::Paragraph;

#[derive(Default)]
struct StatusBadge {
    pub label: String,
    pub color: Color,
}

impl Component for StatusBadge {
    type State = (); // no internal state needed

    fn render(&self, area: Rect, buf: &mut Buffer, _state: &()) {
        let line = Line::from(Span::styled(&self.label, Style::default().fg(self.color)));
        Paragraph::new(line).render(area, buf);
    }

    fn desired_height(&self, _width: u16, _state: &()) -> u16 { 1 }
}
```

Then use it in a view:

```rust
element! {
    StatusBadge(label: "Online", color: Color::Green)
}
```

### Composite Components

Components can generate child trees via the `children()` method. The `slot` parameter carries externally-provided children (like React's `props.children`):

```rust
#[derive(Default)]
struct Card {
    pub title: String,
}

impl Component for Card {
    type State = ();

    fn children(&self, _state: &(), slot: Option<Elements>) -> Option<Elements> {
        let mut els = Elements::new();
        els.add(TextBlock::new().line(&self.title, heading_style));
        if let Some(children) = slot {
            els.group(children); // slot children rendered here
        }
        Some(els)
    }

    fn content_inset(&self, _state: &()) -> Insets {
        Insets::all(1) // 1-cell border chrome
    }

    fn render(&self, area: Rect, buf: &mut Buffer, _state: &()) {
        // draw border chrome; children render inside the inset area
    }

    fn desired_height(&self, _: u16, _: &()) -> u16 { 0 } // ignored for containers
}
```

Usage with `element!`:

```rust
element! {
    Card(title: "My Card") {
        Spinner(label: "Loading...")
        "Some content"
    }
}
```

Three patterns:
- **Pass through** (default) — VStack, HStack accept external children as-is
- **Generate own tree** — a Spinner builds its own frame + label layout internally
- **Wrap slot** — a Card wraps external children in a header + border

### Lifecycle Hooks

Components declare effects via `lifecycle()`. The framework manages registration and cleanup:

```rust
impl Component for Timer {
    type State = TimerState;

    fn lifecycle(&self, hooks: &mut Hooks<TimerState>, _state: &TimerState) {
        if self.running {
            hooks.use_interval(Duration::from_secs(1), |s| s.elapsed += 1);
        }
        hooks.use_mount(|s| s.started_at = Instant::now());
        hooks.use_unmount(|s| println!("Timer ran for {:?}", s.started_at.elapsed()));
    }

    // ...
}
```

Available hooks:

| Hook | Fires when |
|------|------------|
| `use_interval(duration, handler)` | Periodically, at the given duration |
| `use_mount(handler)` | Once, after the component is first built |
| `use_unmount(handler)` | Once, when the component is removed |
| `use_autofocus()` | Requests focus when the component mounts |
| `provide_context(value)` | Makes a value available to all descendants |
| `use_context::<T>(handler)` | Reads a value provided by an ancestor |

### Context

The context system lets ancestor components provide typed values to their descendants without prop-drilling. This is the primary mechanism for connecting components to app-level services.

**Root-level context** — register values on the application builder:

```rust
let (mut app, handle) = Application::builder()
    .state(MyState::default())
    .view(my_view)
    .with_context(event_sender)       // available to all components
    .with_context(AppConfig::new())   // multiple types supported
    .build()?;
```

**Component-level context** — provide and consume in lifecycle:

```rust
// Provider: makes a value available to descendants
fn lifecycle(&self, hooks: &mut Hooks<MyState>, _state: &MyState) {
    hooks.provide_context(self.theme.clone());
}

// Consumer: reads a value from an ancestor
fn lifecycle(&self, hooks: &mut Hooks<MyState>, _state: &MyState) {
    hooks.use_context::<Theme>(|theme, state| {
        state.current_theme = theme.cloned();
    });
}
```

The `use_context` handler always fires with `Option<&T>` — `None` if no ancestor provides the type. Inner providers shadow outer providers of the same type within their subtree.

## Layout

Vertical stacking is the default. `HStack` provides horizontal layout with width constraints:

```rust
use eye_declare::{Elements, HStack, Column, TextBlock};
use eye_declare::WidthConstraint::Fixed;

fn two_column_view(state: &MyState) -> Elements {
    element! {
        HStack {
            Column(width: Fixed(20)) {
                TextBlock {
                    #(for line in state.lines {
                        Line {
                            Span(text: line)
                        }
                    })
                }
            }
            Column {
                // Fill: takes remaining space
                TextBlock {
                    #(for line in state.content_lines {
                        Line {
                            Span(text: line)
                        }
                    })
                }
            }
        }
    }
}
```

Components can declare `content_inset()` for borders and padding — children render inside the inset area while the component draws chrome in the full area.

## Reconciliation

Elements are matched by key (stable identity) or position (implicit). State is preserved across rebuilds when nodes are reused:

```rust
element! {
    // Keyed: survives reordering, state preserved by key
    #(for msg in &state.messages {
        Markdown(key: format!("msg-{}", msg.id), source: msg.content.clone())
    })

    // Positional: matched by index + type
    "Footer"
}
```

## Application

`Application` owns your state and manages the render loop. `Handle` sends updates from any thread or async task:

```rust
let (mut app, handle) = Application::builder()
    .state(MyState::new())
    .view(my_view)
    .build()?;

// Non-interactive: exits when handle is dropped and effects stop
app.run().await?;
```

```rust
// Component-driven interactive: raw mode with context-based event handling
// Components handle their own events and dispatch app-domain actions via channels
app.run_loop().await?;
```

```rust
// Raw interactive: direct access to terminal events (escape hatch)
app.run_interactive(|event, state| {
    // handle terminal events, mutate state
    ControlFlow::Continue
}).await?;
```

Multiple handle updates between frames are batched into a single rebuild.

### Terminal Options

The builder supports configuring terminal protocols for interactive modes:

```rust
Application::builder()
    .state(state)
    .view(view)
    .ctrl_c(CtrlCBehavior::Deliver)         // route Ctrl+C to components (default: Exit)
    .keyboard_protocol(KeyboardProtocol::Enhanced)  // kitty protocol (default: Legacy)
    .bracketed_paste(true)                   // distinguish pastes from typing (default: false)
    .build()?;
```

| Option | Default | Description |
|--------|---------|-------------|
| `ctrl_c` | `Exit` | `Exit` intercepts Ctrl+C; `Deliver` routes it to components |
| `keyboard_protocol` | `Legacy` | `Enhanced` enables kitty protocol for key disambiguation |
| `bracketed_paste` | `false` | Delivers pasted text as `Event::Paste(String)` |

### Committed Scrollback

For long-running apps, content that scrolls into terminal scrollback can be evicted from state via an `on_commit` callback:

```rust
Application::builder()
    .state(state)
    .view(view)
    .on_commit(|committed, state| {
        // `committed.key` identifies which element scrolled off
        state.messages.remove(0);
    })
    .build()?;
```

This is an opt-in performance optimization. Without it, the framework handles all content normally.

## Imperative API

For direct control over the render loop, use `InlineRenderer`:

```rust
use eye_declare::{InlineRenderer, Spinner, VStack, TextBlock};

let mut renderer = InlineRenderer::new(width);
let spinner_id = renderer.push(Spinner::new("Loading..."));

// Mutate state, render, write to stdout
std::thread::sleep(Duration::from_millis(100));
renderer.tick();
let output = renderer.render();
stdout.write_all(&output)?;

// Declarative subtrees via rebuild
let container = renderer.push(VStack);
renderer.rebuild(container, element! {
    "Hello"
});
```

See the `terminal_demo` and `lifecycle` examples for complete sync event loop patterns.

## Built-in Components

| Component | Description |
|-----------|-------------|
| `TextBlock` | Styled text with display-time word wrapping. Supports `Line`/`Span` children for multi-styled lines. |
| `Spinner` | Animated Braille spinner with auto-tick. Shows a checkmark when `.done()`. |
| `Markdown` | Headings, bold, italic, inline code, code blocks, and lists. |
| `VStack` | Vertical container — children stack top-to-bottom. |
| `HStack` | Horizontal container — children lay left-to-right with `WidthConstraint`-based layout. |

## Examples

```sh
cargo run --example chat            # Interactive chat with streaming
cargo run --example app             # Application wrapper with Handle updates
cargo run --example declarative     # View function pattern with element! macro
cargo run --example lifecycle       # Mount/unmount lifecycle hooks
cargo run --example interactive     # Focus, Tab cycling, text input
cargo run --example terminal_demo   # Sync imperative API with InlineRenderer
cargo run --example agent_sim       # Multi-component agent simulation
cargo run --example markdown_demo   # Markdown rendering showcase
cargo run --example growing         # Dynamically growing content
cargo run --example nested          # Nested component trees
cargo run --example wrapping        # Word wrapping and resize behavior
```

## Architecture

```
Application        State + view function + async event loop
  InlineRenderer   Rendering, reconciliation, layout, diffing, scrollback
    ratatui-core   Buffer, Cell, Style, Widget primitives
    crossterm      Terminal I/O, event types
```

### Inline rendering model

eye-declare uses an **inline rendering model** — content grows downward into the terminal's native scrollback, like standard CLI output. This is fundamentally different from full-screen TUI frameworks (ratatui's `Terminal`, tui-realm, cursive) that redraw a fixed viewport.

The tradeoff is deliberate. Inline rendering is the right model for AI assistants, build tools, and interactive prompts where output accumulates and earlier results should persist in scrollback for the user to review.

**How it works:**

1. **Reconciliation** matches new elements against existing nodes by key or position. State is preserved when nodes are reused, so animations continue seamlessly and internal component state survives rebuilds.

2. **Layout** measures each node's desired height (with word wrapping computed at render time) and allocates widths for horizontal containers. Content insets allow components to declare border/padding chrome while children render inside.

3. **Rendering** produces a Ratatui `Buffer` for each frame. The `InlineRenderer` diffs against the previous frame and emits only changed cells as ANSI escape sequences, wrapped in DEC synchronized output (`?2026h/l`) to prevent tearing.

4. **Growth** is handled by emitting newlines to claim new terminal rows before writing content. Old rows naturally scroll into terminal scrollback.

**Scrollback handling:** When content height exceeds the terminal height, the terminal scrolls rows into scrollback. The framework tracks terminal height and filters diff output to only address visible rows. The `on_commit` callback provides an additional optimization by evicting committed content from application state entirely.

## Crate Structure

```
crates/
  eye_declare/         Main library
  eye_declare_macros/  element! proc macro
```

The macro is behind the `macros` feature flag (enabled by default).

## License

MIT