{"id":47911267,"url":"https://github.com/atuinsh/eye-declare","last_synced_at":"2026-04-24T23:02:04.592Z","repository":{"id":346488126,"uuid":"1190205515","full_name":"atuinsh/eye-declare","owner":"atuinsh","description":"A declarative inline TUI rendering library for Rust, built on Ratatui","archived":false,"fork":false,"pushed_at":"2026-04-14T21:31:26.000Z","size":4700,"stargazers_count":112,"open_issues_count":6,"forks_count":2,"subscribers_count":4,"default_branch":"main","last_synced_at":"2026-04-14T23:30:07.443Z","etag":null,"topics":["declarative","rendering","rust","terminal","tui"],"latest_commit_sha":null,"homepage":"https://eye-declare.rs","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/atuinsh.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2026-03-24T04:03:42.000Z","updated_at":"2026-04-14T21:31:31.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/atuinsh/eye-declare","commit_stats":null,"previous_names":["binarymuse/eye-declare","atuinsh/eye-declare"],"tags_count":28,"template":false,"template_full_name":null,"purl":"pkg:github/atuinsh/eye-declare","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atuinsh%2Feye-declare","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atuinsh%2Feye-declare/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atuinsh%2Feye-declare/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atuinsh%2Feye-declare/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/atuinsh","download_url":"https://codeload.github.com/atuinsh/eye-declare/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atuinsh%2Feye-declare/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32243803,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-24T13:21:15.438Z","status":"ssl_error","status_checked_at":"2026-04-24T13:21:15.005Z","response_time":64,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["declarative","rendering","rust","terminal","tui"],"created_at":"2026-04-04T05:19:43.082Z","updated_at":"2026-04-24T23:02:04.542Z","avatar_url":"https://github.com/atuinsh.png","language":"Rust","funding_links":[],"categories":["Rust","\u003ca name=\"Rust\"\u003e\u003c/a\u003eRust"],"sub_categories":[],"readme":"# eye-declare\n\n[![Crates.io Version](https://img.shields.io/crates/v/eye_declare)](https://crates.io/crates/eye_declare) [![docs.rs](https://img.shields.io/docsrs/eye_declare)](https://docs.rs/eye_declare)\n\nA declarative inline TUI rendering library for Rust, built on [Ratatui](https://ratatui.rs).\n\neye-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.\n\n![Demo](https://github.com/BinaryMuse/eye-declare/blob/main/assets/demo.gif?raw=true)\n\n## Status\n\neye-declare is in early development; expect breaking changes across v0.x versions until v1.0.\n\n## Installation\n\nAdd to your project with:\n\n```bash\ncargo add eye_declare\n```\n\n## Quick Start\n\n```rust\nuse eye_declare::{element, Application, ControlFlow, Elements, Spinner};\n\nstruct AppState {\n    messages: Vec\u003cString\u003e,\n    thinking: bool,\n}\n\nfn chat_view(state: \u0026AppState) -\u003e Elements {\n    element! {\n        #(for (i, msg) in state.messages.iter().enumerate() {\n            Text(key: format!(\"msg-{i}\")) { Span(text: msg.clone()) }\n        })\n        #(if state.thinking {\n            Spinner(key: \"thinking\", label: \"Thinking...\")\n        })\n    }\n}\n\n#[tokio::main]\nasync fn main() -\u003e std::io::Result\u003c()\u003e {\n    let (mut app, handle) = Application::builder()\n        .state(AppState { messages: vec![], thinking: false })\n        .view(chat_view)\n        .build()?;\n\n    // Send updates from any thread or async task\n    tokio::spawn(async move {\n        handle.update(|s| s.messages.push(\"Hello from eye_declare!\".into()));\n    });\n\n    app.run().await\n}\n```\n\n## The `element!` Macro\n\nThe `element!` macro is the primary way to build UIs. It provides JSX-like syntax for composing component trees:\n\n```rust\nfn dashboard(state: \u0026DashboardState) -\u003e Elements {\n    element! {\n        VStack {\n            \"Dashboard\"\n\n            #(for (i, item) in state.items.iter().enumerate() {\n                Markdown(key: format!(\"item-{i}\"), source: item.clone())\n            })\n\n            #(if state.loading {\n                Spinner(label: \"Refreshing...\")\n            })\n\n            #(if let Some(ref err) = state.error {\n                Markdown(source: err.clone())\n            })\n\n            #(footer_view(state))\n        }\n    }\n}\n```\n\n### Syntax reference\n\n| Syntax | Description |\n|--------|-------------|\n| `Component(prop: value)` | Construct with props (struct field init) |\n| `Component { ... }` | Component with children |\n| `Component(props) { children }` | Both |\n| `\"text\"` | String literal — auto-wrapped as `Text` |\n| `key: expr` | Special prop for stable identity across rebuilds |\n| `#(if cond { ... })` | Conditional children |\n| `#(if let pat = expr { ... })` | Pattern-matching conditional |\n| `#(for pat in iter { ... })` | Loop children |\n| `#(expr)` | Splice a pre-built `Elements` value inline |\n\n## Components\n\nThe primary way to define components is with `#[component]` and `#[props]`:\n\n```rust\nuse eye_declare::{component, element, props, Elements, Canvas, View, BorderType};\nuse ratatui_core::{buffer::Buffer, layout::Rect, style::{Color, Modifier, Style}, text::Line, widgets::Widget};\nuse ratatui_widgets::paragraph::Paragraph;\n\n/// Props are defined with #[props] on a struct.\n#[props]\nstruct Badge {\n    label: String,\n    #[default(Color::Green)]\n    color: Color,\n}\n\n/// The component function receives props (and optionally hooks/state)\n/// and returns Elements.\n#[component(props = Badge)]\nfn badge(props: \u0026Badge) -\u003e Elements {\n    let label = props.label.clone();\n    let color = props.color;\n\n    element!(\n        Canvas(render_fn: move |area: Rect, buf: \u0026mut Buffer| {\n            let line = Line::styled(\n                format!(\" {} \", label),\n                Style::default().fg(Color::Black).bg(color),\n            );\n            Paragraph::new(line).render(area, buf);\n        })\n    )\n}\n```\n\nThen use it in a view:\n\n```rust\nelement! {\n    Badge(label: \"Online\", color: Color::Green)\n}\n```\n\n### Manual Component impl\n\nFor full control, implement the `Component` trait directly. Props live on `\u0026self` (immutable, set by parent). Internal state lives in the associated `State` type (mutable, framework-managed via automatic dirty tracking).\n\n```rust\nuse eye_declare::Component;\nuse ratatui_core::{buffer::Buffer, layout::Rect, style::Style, widgets::Widget};\nuse ratatui_widgets::paragraph::Paragraph;\n\n#[derive(Default)]\nstruct StatusBadge {\n    pub label: String,\n    pub color: Color,\n}\n\nimpl Component for StatusBadge {\n    type State = (); // no internal state needed\n\n    fn render(\u0026self, area: Rect, buf: \u0026mut Buffer, _state: \u0026()) {\n        let line = Line::from(Span::styled(\u0026self.label, Style::default().fg(self.color)));\n        Paragraph::new(line).render(area, buf);\n    }\n}\n```\n\n### Composite Components\n\nComponents can accept children using `#[component(children = Elements)]`. Use `View` for layout and chrome:\n\n```rust\n#[props]\nstruct Card {\n    title: String,\n}\n\n#[component(props = Card, children = Elements)]\nfn card(props: \u0026Card, children: Elements) -\u003e Elements {\n    element!(\n        View(\n            border: BorderType::Rounded,\n            border_style: Style::default().fg(Color::DarkGray),\n            title: props.title.clone(),\n            title_style: Style::default().fg(Color::White).add_modifier(Modifier::BOLD),\n        ) {\n            #(children)\n        }\n    )\n}\n```\n\nUsage with `element!`:\n\n```rust\nelement! {\n    Card(title: \"My Card\") {\n        Spinner(label: \"Loading...\")\n        \"Some content\"\n    }\n}\n```\n\nThree patterns:\n- **Pass through** (default) — VStack, HStack accept external children as-is\n- **Generate own tree** — a Spinner builds its own frame + label layout internally\n- **Wrap slot** — a Card wraps external children in a header + border\n\n### Lifecycle Hooks\n\nComponents declare effects via hooks. In a `#[component]` function, accept `hooks` and optionally `state`:\n\n```rust\n#[derive(Default)]\nstruct TimerState {\n    elapsed: u64,\n    started_at: Option\u003cInstant\u003e,\n}\n\n#[props]\nstruct Timer {\n    running: bool,\n}\n\n#[component(props = Timer, state = TimerState)]\nfn timer(props: \u0026Timer, state: \u0026TimerState, hooks: \u0026mut Hooks\u003cTimerState\u003e) -\u003e Elements {\n    if props.running {\n        hooks.use_interval(Duration::from_secs(1), |s| s.elapsed += 1);\n    }\n    hooks.use_mount(|s| s.started_at = Some(Instant::now()));\n    hooks.use_unmount(|s| {\n        if let Some(at) = s.started_at {\n            println!(\"Timer ran for {:?}\", at.elapsed());\n        }\n    });\n\n    element! {\n        #(format!(\"Elapsed: {}s\", state.elapsed))\n    }\n}\n```\n\nAvailable hooks:\n\n| Hook | Fires when |\n|------|------------|\n| `use_interval(duration, handler)` | Periodically, at the given duration |\n| `use_mount(handler)` | Once, after the component is first built |\n| `use_unmount(handler)` | Once, when the component is removed |\n| `use_autofocus()` | Requests focus when the component mounts |\n| `use_focusable(bool)` | Declares the component as focusable for Tab cycling |\n| `use_cursor(handler)` | Returns cursor position when focused |\n| `use_event(handler)` | Handles events in the bubble phase (focused -\u003e root) |\n| `use_event_capture(handler)` | Handles events in the capture phase (root -\u003e focused) |\n| `use_layout(layout)` | Overrides the component's layout direction |\n| `use_width_constraint(constraint)` | Sets width constraint in horizontal layout |\n| `use_height_hint(height)` | Declares a fixed height, skipping probe measurement |\n| `provide_context(value)` | Makes a value available to all descendants |\n| `use_context::\u003cT\u003e(handler)` | Reads a value provided by an ancestor |\n\n### Context\n\nThe 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.\n\n**Root-level context** — register values on the application builder:\n\n```rust\nlet (mut app, handle) = Application::builder()\n    .state(MyState::default())\n    .view(my_view)\n    .with_context(event_sender)       // available to all components\n    .with_context(AppConfig::new())   // multiple types supported\n    .build()?;\n```\n\n**Component-level context** — provide and consume via hooks:\n\n```rust\n// Provider: makes a value available to descendants\n#[component(props = ThemeProvider, children = Elements)]\nfn theme_provider(props: \u0026ThemeProvider, hooks: \u0026mut Hooks\u003cThemeProvider, ()\u003e, children: Elements) -\u003e Elements {\n    hooks.provide_context(props.theme.clone());\n    children\n}\n\n// Consumer: reads a value from an ancestor\n#[component(props = ThemedButton, state = ButtonState)]\nfn themed_button(props: \u0026ThemedButton, hooks: \u0026mut Hooks\u003cThemedButton, ButtonState\u003e) -\u003e Elements {\n    hooks.use_context::\u003cTheme\u003e(|theme, _props, state| {\n        state.current_theme = theme.cloned();\n    });\n    // ... return element tree\n}\n```\n\nThe `use_context` handler always fires with `Option\u003c\u0026T\u003e` — `None` if no ancestor provides the type. Inner providers shadow outer providers of the same type within their subtree.\n\n## Layout\n\nVertical stacking is the default. `HStack` provides horizontal layout with width constraints:\n\n```rust\nuse eye_declare::{Elements, HStack, Column, Text};\nuse eye_declare::WidthConstraint::Fixed;\n\nfn two_column_view(state: \u0026MyState) -\u003e Elements {\n    element! {\n        HStack {\n            Column(width: Fixed(20)) {\n                Text { \"Sidebar content\" }\n            }\n            Column {\n                // Fill: takes remaining space\n                Text { \"Main content\" }\n            }\n        }\n    }\n}\n```\n\nComponents can declare `content_inset()` for borders and padding — children render inside the inset area while the component draws chrome in the full area.\n\n## Reconciliation\n\nElements are matched by key (stable identity) or position (implicit). State is preserved across rebuilds when nodes are reused:\n\n```rust\nelement! {\n    // Keyed: survives reordering, state preserved by key\n    #(for msg in \u0026state.messages {\n        Markdown(key: format!(\"msg-{}\", msg.id), source: msg.content.clone())\n    })\n\n    // Positional: matched by index + type\n    \"Footer\"\n}\n```\n\n## Application\n\n`Application` owns your state and manages the render loop. `Handle` sends updates from any thread or async task:\n\n```rust\nlet (mut app, handle) = Application::builder()\n    .state(MyState::new())\n    .view(my_view)\n    .build()?;\n\n// Non-interactive: exits when handle is dropped and effects stop\napp.run().await?;\n```\n\n```rust\n// Component-driven interactive: raw mode with context-based event handling\n// Components handle their own events and dispatch app-domain actions via channels\napp.run_loop().await?;\n```\n\n```rust\n// Raw interactive: direct access to terminal events (escape hatch)\napp.run_interactive(|event, state| {\n    // handle terminal events, mutate state\n    ControlFlow::Continue\n}).await?;\n```\n\nMultiple handle updates between frames are batched into a single rebuild.\n\n### Terminal Options\n\nThe builder supports configuring terminal protocols for interactive modes:\n\n```rust\nApplication::builder()\n    .state(state)\n    .view(view)\n    .ctrl_c(CtrlCBehavior::Deliver)         // route Ctrl+C to components (default: Exit)\n    .keyboard_protocol(KeyboardProtocol::Enhanced)  // kitty protocol (default: Legacy)\n    .bracketed_paste(true)                   // distinguish pastes from typing (default: false)\n    .build()?;\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `ctrl_c` | `Exit` | `Exit` intercepts Ctrl+C; `Deliver` routes it to components |\n| `keyboard_protocol` | `Legacy` | `Enhanced` enables kitty protocol for key disambiguation |\n| `bracketed_paste` | `false` | Delivers pasted text as `Event::Paste(String)` |\n\n### Committed Scrollback\n\nFor long-running apps, content that scrolls into terminal scrollback can be evicted from state via an `on_commit` callback:\n\n```rust\nApplication::builder()\n    .state(state)\n    .view(view)\n    .on_commit(|committed, state| {\n        // `committed.key` identifies which element scrolled off\n        state.messages.remove(0);\n    })\n    .build()?;\n```\n\nThis is an opt-in performance optimization. Without it, the framework handles all content normally.\n\n## Imperative API\n\nFor direct control over the render loop, use `InlineRenderer`:\n\n```rust\nuse eye_declare::{InlineRenderer, Spinner, VStack, Text};\n\nlet mut renderer = InlineRenderer::new(width);\nlet spinner_id = renderer.push(Spinner::new(\"Loading...\"));\n\n// Mutate state, render, write to stdout\nstd::thread::sleep(Duration::from_millis(100));\nrenderer.tick();\nlet output = renderer.render();\nstdout.write_all(\u0026output)?;\n\n// Declarative subtrees via rebuild\nlet container = renderer.push(VStack);\nrenderer.rebuild(container, element! {\n    \"Hello\"\n});\n```\n\nSee the `terminal_demo` and `lifecycle` examples for complete sync event loop patterns.\n\n## Built-in Components\n\n| Component | Description |\n|-----------|-------------|\n| `Text` | Styled text with word wrapping. Accepts `Span` and string children. |\n| `Spinner` | Animated Braille spinner with auto-tick. Shows a checkmark when `.done()`. |\n| `Markdown` | Headings, bold, italic, inline code, code blocks, and lists. |\n| `Canvas` | Raw buffer rendering via a user-provided closure. Direct access to the ratatui `Buffer`. |\n| `View` | Unified layout container with optional borders, padding, background, and direction. |\n| `VStack` | Vertical container — children stack top-to-bottom. |\n| `HStack` | Horizontal container — children lay left-to-right with `WidthConstraint`-based layout. |\n| `Column` | Width-constrained wrapper for use inside `HStack`. |\n\n## Examples\n\n```sh\ncargo run --example chat            # Interactive chat with streaming\ncargo run --example app             # Application wrapper with Handle updates\ncargo run --example declarative     # View function pattern with element! macro\ncargo run --example lifecycle       # Mount/unmount lifecycle hooks\ncargo run --example interactive     # Focus, Tab cycling, text input\ncargo run --example terminal_demo   # Sync imperative API with InlineRenderer\ncargo run --example agent_sim       # Multi-component agent simulation\ncargo run --example markdown_demo   # Markdown rendering showcase\ncargo run --example growing         # Dynamically growing content\ncargo run --example nested          # Nested component trees\ncargo run --example wrapping        # Word wrapping and resize behavior\ncargo run --example data_children   # Typed data children with #[component]\n```\n\n## Architecture\n\n```\nApplication        State + view function + async event loop\n  InlineRenderer   Rendering, reconciliation, layout, diffing, scrollback\n    ratatui-core   Buffer, Cell, Style, Widget primitives\n    crossterm      Terminal I/O, event types\n```\n\n### Inline rendering model\n\neye-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.\n\nThe 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.\n\n**How it works:**\n\n1. **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.\n\n2. **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.\n\n3. **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.\n\n4. **Growth** is handled by emitting newlines to claim new terminal rows before writing content. Old rows naturally scroll into terminal scrollback.\n\n**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.\n\n## Crate Structure\n\n```\ncrates/\n  eye_declare/         Main library\n  eye_declare_macros/  element! proc macro\n```\n\nThe macro is behind the `macros` feature flag (enabled by default).\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatuinsh%2Feye-declare","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fatuinsh%2Feye-declare","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatuinsh%2Feye-declare/lists"}