rusty_bubbletea/model.rs
1//! Cleanroom Rust port of upstream Go source file: `tea.go` (Model interface)
2//! Upstream Target Tag / Version: `v2.0.8`
3//!
4//! <upstream-docs>
5//! Package tea provides a framework for building rich terminal user interfaces
6//! based on the paradigms of The Elm Architecture. It's well-suited for simple
7//! and complex terminal applications, either inline, full-window, or a mix of
8//! both. It's been battle-tested in several large projects and is
9//! production-ready.
10//!
11//! A tutorial is available at https://github.com/charmbracelet/bubbletea/tree/master/tutorials
12//!
13//! Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/master/examples
14//! </upstream-docs>
15
16use crate::view::View;
17use std::any::Any;
18use std::fmt::Debug;
19
20/// Msg represents an event message delivered to the Model's Update function.
21pub trait Msg: Any + Send + Sync + Debug {
22 /// Helper to downcast to Any.
23 fn as_any(&self) -> &dyn Any;
24
25 /// Consumes the boxed message and returns it as a `Box<dyn Any>`, so the
26 /// program can move the concrete message out of the trait object (used to
27 /// dispatch the commands carried by `BatchMsg`/`SequenceMsg`).
28 fn into_any(self: Box<Self>) -> Box<dyn Any>;
29}
30
31impl<T: Any + Send + Sync + Debug> Msg for T {
32 fn as_any(&self) -> &dyn Any {
33 self
34 }
35
36 fn into_any(self: Box<Self>) -> Box<dyn Any> {
37 self
38 }
39}
40
41/// Cmd is an asynchronous command closure returning an optional Msg.
42pub type Cmd = Option<Box<dyn FnOnce() -> Option<Box<dyn Msg>> + Send + Sync>>;
43
44/// Model defines the application state machine according to The Elm Architecture in Bubble Tea v2.0.8.
45pub trait Model: Send + Sync + Sized + 'static {
46 /// Init is called when the program starts, returning an optional initial command.
47 fn init(&self) -> Cmd {
48 None
49 }
50
51 /// Update receives a message and returns an updated Model and optional command.
52 fn update(&mut self, msg: &dyn Msg) -> Cmd;
53
54 /// View renders the program's UI as a declarative `View` struct.
55 fn view(&self) -> View;
56}