pub trait Component {
type Message;
// Required methods
fn on_event(
&mut self,
event: &Event,
) -> impl Future<Output = Option<Vec<Self::Message>>>;
fn render(&mut self, ctx: &ViewContext) -> Frame;
}Expand description
The core abstraction for all interactive widgets. Every built-in widget implements this trait, and parent components compose children through it.
The trait follows an event-message design: on_event receives input and optionally produces typed messages that bubble up to the parent. render produces a Frame from the current state.
§Event handling contract
on_event returns one of three outcomes:
None— the event was not recognized. The parent should propagate it elsewhere.Some(vec![])— the event was consumed but produced no messages (e.g. internal cursor movement).Some(vec![msg, ...])— the event was consumed and produced one or more messages for the parent to handle.
Use merge to combine outcomes from multiple children.
§Rendering
render receives a ViewContext — the allocated render region plus theme — and returns a Frame, a vector of Lines plus an optional Cursor position.
Parents are responsible for narrowing the context to the child’s slot before calling render (using with_width, with_size, or inset). Children should treat ctx.size as authoritative — only the root component should assume the full terminal width. Composition between siblings happens on Frame itself via fit, indent, vstack, and hstack, not by reaching back into the parent’s context.
§Usage
use tui::{Component, Event, Frame, KeyCode, Line, ViewContext};
struct Counter { count: i32 }
impl Component for Counter {
type Message = ();
async fn on_event(&mut self, event: &Event) -> Option<Vec<()>> {
if let Event::Key(key) = event {
match key.code {
KeyCode::Up => self.count += 1,
KeyCode::Down => self.count -= 1,
_ => return None,
}
return Some(vec![]);
}
None
}
fn render(&mut self, _ctx: &ViewContext) -> Frame {
Frame::new(vec![Line::new(format!("Count: {}", self.count))])
}
}§See also
Event— the input events passed toon_event.Frame— the output ofrender.ViewContext— the environment passed torender.merge— combine event outcomes from multiple children.
Required Associated Types§
Required Methods§
Sourcefn on_event(
&mut self,
event: &Event,
) -> impl Future<Output = Option<Vec<Self::Message>>>
fn on_event( &mut self, event: &Event, ) -> impl Future<Output = Option<Vec<Self::Message>>>
Process an event and return the outcome.
None— event not recognized, propagate to parentSome(vec![])— event consumed, no messagesSome(vec![msg, ...])— event consumed, emit messages
Sourcefn render(&mut self, ctx: &ViewContext) -> Frame
fn render(&mut self, ctx: &ViewContext) -> Frame
Render the current state to a frame.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.