tui_dispatch_core/lib.rs
1//! Core traits and types for tui-dispatch
2//!
3//! This crate provides the foundational abstractions for building TUI applications
4//! with centralized state management, following a Redux/Elm-inspired architecture.
5//!
6//! # Core Concepts
7//!
8//! - **Action**: Events that describe state changes
9//! - **Store**: Centralized state container with reducer pattern
10//! - **Component**: Pure UI elements that render based on props
11//! - **EventBus**: Pub/sub system for event routing
12//! - **Keybindings**: Context-aware key mapping
13//!
14//! # Basic Example
15//!
16//! ```ignore
17//! use tui_dispatch_core::prelude::*;
18//!
19//! #[derive(Action, Clone, Debug)]
20//! enum MyAction {
21//! Increment,
22//! Decrement,
23//! }
24//!
25//! #[derive(Default)]
26//! struct AppState {
27//! counter: i32,
28//! }
29//!
30//! fn reducer(state: &mut AppState, action: MyAction) -> bool {
31//! match action {
32//! MyAction::Increment => { state.counter += 1; true }
33//! MyAction::Decrement => { state.counter -= 1; true }
34//! }
35//! }
36//!
37//! let mut store = Store::new(AppState::default(), reducer);
38//! store.dispatch(MyAction::Increment);
39//! ```
40//!
41//! # Async Handler Pattern
42//!
43//! For applications with async operations (API calls, file I/O, etc.), use a two-phase
44//! action pattern:
45//!
46//! 1. **Intent actions** trigger async work (e.g., `FetchData`)
47//! 2. **Result actions** carry the outcome back (e.g., `DidFetchData`, `DidFetchError`)
48//!
49//! ```ignore
50//! use tokio::sync::mpsc;
51//!
52//! #[derive(Action, Clone, Debug)]
53//! #[action(infer_categories)]
54//! enum Action {
55//! // Intent: triggers async fetch
56//! DataFetch { id: String },
57//! // Result: async operation completed
58//! DataDidLoad { id: String, payload: Vec<u8> },
59//! DataDidError { id: String, error: String },
60//! }
61//!
62//! // Async handler spawns a task and sends result back via channel
63//! fn handle_async(action: &Action, tx: mpsc::UnboundedSender<Action>) {
64//! match action {
65//! Action::DataFetch { id } => {
66//! let id = id.clone();
67//! let tx = tx.clone();
68//! tokio::spawn(async move {
69//! match fetch_from_api(&id).await {
70//! Ok(payload) => tx.send(Action::DataDidLoad { id, payload }),
71//! Err(e) => tx.send(Action::DataDidError { id, error: e.to_string() }),
72//! }
73//! });
74//! }
75//! _ => {}
76//! }
77//! }
78//!
79//! // Main loop receives actions from both events and async completions
80//! loop {
81//! tokio::select! {
82//! Some(action) = action_rx.recv() => {
83//! handle_async(&action, action_tx.clone());
84//! store.dispatch(action);
85//! }
86//! // ... event handling
87//! }
88//! }
89//! ```
90//!
91//! The `Did*` naming convention clearly identifies result actions. With `#[action(infer_categories)]`,
92//! these are automatically grouped (e.g., `DataFetch` and `DataDidLoad` both get category `"data"`).
93
94pub mod action;
95pub mod bus;
96pub mod component;
97pub mod debug;
98pub mod event;
99pub mod keybindings;
100pub mod store;
101pub mod testing;
102
103// Core trait exports
104pub use action::{Action, ActionCategory};
105pub use component::Component;
106
107// Event system exports
108pub use bus::{process_raw_event, spawn_event_poller, EventBus, RawEvent};
109pub use event::{ComponentId, Event, EventContext, EventKind, EventType, NumericComponentId};
110
111// Keybindings exports
112pub use keybindings::{format_key_for_display, parse_key_string, BindingContext, Keybindings};
113
114// Store exports
115pub use store::{
116 ComposedMiddleware, LoggingMiddleware, Middleware, NoopMiddleware, Reducer, Store,
117 StoreWithMiddleware,
118};
119
120// Re-export ratatui types for convenience
121pub use ratatui::{
122 layout::Rect,
123 style::{Color, Modifier, Style},
124 text::{Line, Span, Text},
125 Frame,
126};
127
128// Testing exports
129pub use testing::{
130 alt_key, buffer_rect_to_string_plain, buffer_to_string, buffer_to_string_plain, char_key,
131 ctrl_key, into_event, key, key_event, key_events, keys, ActionAssertions, ActionAssertionsEq,
132 RenderHarness, TestHarness,
133};
134
135#[cfg(feature = "testing-time")]
136pub use testing::{advance_time, pause_time, resume_time};
137
138/// Prelude module for convenient imports
139pub mod prelude {
140 pub use crate::action::{Action, ActionCategory};
141 pub use crate::bus::{process_raw_event, spawn_event_poller, EventBus, RawEvent};
142 pub use crate::component::Component;
143 pub use crate::event::{
144 ComponentId, Event, EventContext, EventKind, EventType, NumericComponentId,
145 };
146 pub use crate::keybindings::{
147 format_key_for_display, parse_key_string, BindingContext, Keybindings,
148 };
149 pub use crate::store::{
150 ComposedMiddleware, LoggingMiddleware, Middleware, NoopMiddleware, Reducer, Store,
151 StoreWithMiddleware,
152 };
153
154 // Re-export ratatui types
155 pub use ratatui::{
156 layout::Rect,
157 style::{Color, Modifier, Style},
158 text::{Line, Span, Text},
159 Frame,
160 };
161}