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//! ```
17//! use tui_dispatch_core::{Action, ReducerResult, Store};
18//!
19//! #[derive(Clone, Debug)]
20//! enum MyAction { Increment, Decrement }
21//!
22//! impl Action for MyAction {
23//! fn name(&self) -> &'static str {
24//! match self {
25//! MyAction::Increment => "Increment",
26//! MyAction::Decrement => "Decrement",
27//! }
28//! }
29//! }
30//!
31//! #[derive(Default)]
32//! struct AppState { counter: i32 }
33//!
34//! fn reducer(state: &mut AppState, action: MyAction) -> ReducerResult {
35//! match action {
36//! MyAction::Increment => { state.counter += 1; ReducerResult::changed() }
37//! MyAction::Decrement => { state.counter -= 1; ReducerResult::changed() }
38//! }
39//! }
40//!
41//! let mut store = Store::new(AppState::default(), reducer);
42//! let result = store.dispatch(MyAction::Increment);
43//! assert!(result.changed);
44//! assert_eq!(store.state().counter, 1);
45//! ```
46//!
47//! # Async Handler Pattern
48//!
49//! For applications with async operations (API calls, file I/O, etc.), use a two-phase
50//! action pattern:
51//!
52//! 1. **Intent actions** trigger async work (e.g., `FetchData`)
53//! 2. **Result actions** carry the outcome back (e.g., `DidFetchData`, `DidFetchError`)
54//!
55//! ```ignore
56//! use tokio::sync::mpsc;
57//!
58//! #[derive(Action, Clone, Debug)]
59//! #[action(infer_categories)]
60//! enum Action {
61//! // Intent: triggers async fetch
62//! DataFetch { id: String },
63//! // Result: async operation completed
64//! DataDidLoad { id: String, payload: Vec<u8> },
65//! DataDidError { id: String, error: String },
66//! }
67//!
68//! // Async handler spawns a task and sends result back via channel
69//! fn handle_async(action: &Action, tx: mpsc::UnboundedSender<Action>) {
70//! match action {
71//! Action::DataFetch { id } => {
72//! let id = id.clone();
73//! let tx = tx.clone();
74//! tokio::spawn(async move {
75//! match fetch_from_api(&id).await {
76//! Ok(payload) => tx.send(Action::DataDidLoad { id, payload }),
77//! Err(e) => tx.send(Action::DataDidError { id, error: e.to_string() }),
78//! }
79//! });
80//! }
81//! _ => {}
82//! }
83//! }
84//!
85//! // Main loop receives actions from both events and async completions
86//! loop {
87//! tokio::select! {
88//! Some(action) = action_rx.recv() => {
89//! handle_async(&action, action_tx.clone());
90//! store.dispatch(action);
91//! }
92//! // ... event handling
93//! }
94//! }
95//! ```
96//!
97//! The `Did*` naming convention clearly identifies result actions. With `#[action(infer_categories)]`,
98//! these are automatically grouped (e.g., `DataFetch` and `DataDidLoad` both get category `"data"`).
99
100#[cfg(target_arch = "wasm32")]
101extern crate tinycrossterm as crossterm;
102
103pub mod action;
104pub mod bus;
105pub mod component;
106pub mod event;
107pub mod features;
108pub mod keybindings;
109pub mod resource;
110pub mod runtime;
111pub mod store;
112#[cfg(feature = "subscriptions")]
113pub mod subscriptions;
114#[cfg(feature = "tasks")]
115pub mod tasks;
116pub mod testing;
117
118// Core trait exports
119#[allow(deprecated)]
120pub use action::{Action, ActionCategory, ActionParams, ActionSummary};
121pub use component::Component;
122pub use features::{DynamicFeatures, FeatureFlags};
123
124// Event system exports
125pub use bus::{
126 process_raw_event, spawn_event_poller, DefaultBindingContext, EventBus, EventHandler,
127 EventOutcome, EventRoutingState, HandlerResponse, RawEvent, RouteTarget, RoutedEvent,
128 SimpleEventBus,
129};
130pub use event::{
131 ComponentId, Event, EventContext, EventKind, EventType, GlobalKeyPolicy, NumericComponentId,
132};
133
134// Keybindings exports
135pub use keybindings::{format_key_for_display, parse_key_string, BindingContext, Keybindings};
136
137// Store exports
138#[cfg(feature = "tracing")]
139pub use store::LoggingMiddleware;
140pub use store::{
141 ComposedMiddleware, DispatchError, DispatchLimits, Middleware, NoEffect, NoopMiddleware,
142 Reducer, ReducerResult, Store, StoreWithMiddleware,
143};
144
145// Runtime exports
146pub use runtime::{
147 DispatchErrorPolicy, EffectContext, PollerConfig, RenderContext, Runtime, RuntimeStore,
148};
149
150// Resource exports
151pub use resource::DataResource;
152
153// Task exports (requires "tasks" feature)
154#[cfg(feature = "tasks")]
155pub use tasks::{TaskKey, TaskManager, TaskPauseHandle};
156
157// Subscription exports (requires "subscriptions" feature)
158#[cfg(feature = "subscriptions")]
159pub use subscriptions::{SubKey, SubPauseHandle, Subscriptions};
160
161// Re-export ratatui types for convenience
162pub use ratatui::{
163 layout::Rect,
164 style::{Color, Modifier, Style},
165 text::{Line, Span, Text},
166 Frame,
167};
168
169// Testing exports
170pub use testing::{
171 alt_key, buffer_rect_to_string_plain, buffer_to_string, buffer_to_string_plain, char_key,
172 ctrl_key, into_event, key, key_event, key_events, keys, ActionAssertions, ActionAssertionsEq,
173 EffectAssertions, EffectAssertionsEq, RenderHarness, StoreTestHarness, TestHarness,
174};
175
176#[cfg(feature = "testing-time")]
177pub use testing::{advance_time, pause_time, resume_time};
178
179/// Prelude module for convenient imports
180pub mod prelude {
181 pub use crate::action::{Action, ActionCategory, ActionParams};
182 pub use crate::bus::{
183 process_raw_event, spawn_event_poller, DefaultBindingContext, EventBus, EventHandler,
184 EventOutcome, EventRoutingState, HandlerResponse, RawEvent, RouteTarget, RoutedEvent,
185 SimpleEventBus,
186 };
187 pub use crate::component::Component;
188 pub use crate::event::{
189 ComponentId, Event, EventContext, EventKind, EventType, GlobalKeyPolicy, NumericComponentId,
190 };
191 pub use crate::features::{DynamicFeatures, FeatureFlags};
192 pub use crate::keybindings::{
193 format_key_for_display, parse_key_string, BindingContext, Keybindings,
194 };
195 pub use crate::reducer_compose;
196 pub use crate::resource::DataResource;
197 #[cfg(feature = "tracing")]
198 pub use crate::store::LoggingMiddleware;
199 pub use crate::store::{
200 ComposedMiddleware, DispatchError, DispatchLimits, Middleware, NoEffect, NoopMiddleware,
201 Reducer, ReducerResult, Store, StoreWithMiddleware,
202 };
203
204 // Runtime helpers
205 pub use crate::runtime::{
206 DispatchErrorPolicy, EffectContext, PollerConfig, RenderContext, Runtime, RuntimeStore,
207 };
208 #[cfg(feature = "subscriptions")]
209 pub use crate::subscriptions::{SubKey, SubPauseHandle, Subscriptions};
210 #[cfg(feature = "tasks")]
211 pub use crate::tasks::{TaskKey, TaskManager, TaskPauseHandle};
212
213 // Re-export ratatui types
214 pub use ratatui::{
215 layout::Rect,
216 style::{Color, Modifier, Style},
217 text::{Line, Span, Text},
218 Frame,
219 };
220}