Skip to main content

fission_core/action/
mod.rs

1//! Actions, envelopes, and application state traits.
2//!
3//! This module defines the core data-flow primitives:
4//!
5//! - [`Action`] -- a strongly-typed, serialisable event payload.
6//! - [`ActionEnvelope`] -- the type-erased transport format dispatched through
7//!   the [`Runtime`](crate::Runtime).
8//! - [`ActionId`] -- a stable, content-addressed identifier derived from the
9//!   action's type name.
10//! - [`GlobalState`] -- trait for application state managed by the runtime.
11
12use crate::env::RouteLocation;
13use blake3;
14use downcast_rs::{impl_downcast, Downcast};
15use fission_ir::WidgetId;
16// use fission_macros::Action;
17use lazy_static::lazy_static;
18use serde::{de::DeserializeOwned, Deserialize, Serialize};
19use serde_json;
20use std::any::Any;
21
22pub mod video;
23
24pub use video::{
25    VideoPause, VideoPlay, VideoSeek, VideoSetMuted, VideoSetRate, VideoSetVolume, VideoStop,
26};
27
28/// Built-in action dispatched by shells when the host route changes.
29///
30/// Applications opt in by registering a reducer with
31/// `DesktopApp::with_route_handler(...)` or the equivalent shell API.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct ShellRouteChanged {
34    pub location: RouteLocation,
35}
36
37impl ShellRouteChanged {
38    pub fn new(pathname: impl Into<String>) -> Self {
39        Self {
40            location: RouteLocation::new(pathname),
41        }
42    }
43}
44
45impl From<RouteLocation> for ShellRouteChanged {
46    fn from(location: RouteLocation) -> Self {
47        Self { location }
48    }
49}
50
51impl Action for ShellRouteChanged {
52    fn static_id() -> ActionId {
53        lazy_static! {
54            pub static ref SHELL_ROUTE_CHANGED_ACTION_ID: ActionId =
55                ActionId::from_name("fission_core::ShellRouteChanged");
56        }
57        *SHELL_ROUTE_CHANGED_ACTION_ID
58    }
59}
60
61/// Built-in action to trigger an undo operation.
62///
63/// Applications that support undo/redo should register a reducer for this
64/// action on their state type.
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct Undo;
67
68impl Action for Undo {
69    fn static_id() -> ActionId {
70        lazy_static! {
71            pub static ref UNDO_ACTION_ID: ActionId = ActionId::from_name("fission_core::Undo");
72        }
73        *UNDO_ACTION_ID
74    }
75}
76
77/// Built-in action to trigger a redo operation.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct Redo;
80
81impl Action for Redo {
82    fn static_id() -> ActionId {
83        lazy_static! {
84            pub static ref REDO_ACTION_ID: ActionId = ActionId::from_name("fission_core::Redo");
85        }
86        *REDO_ACTION_ID
87    }
88}
89
90/// A stable, globally unique identifier for an [`Action`] type.
91///
92/// `ActionId` is computed as the first 128 bits of a BLAKE3 hash of the
93/// action's fully-qualified type name, making it deterministic across
94/// compilations and platforms.
95///
96/// # Example
97///
98/// ```rust,ignore
99/// let id = ActionId::from_name("my_app::IncrementCounter");
100/// assert_eq!(id, ActionId::from_name("my_app::IncrementCounter")); // stable
101/// ```
102#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, PartialOrd, Ord)]
103pub struct ActionId(u128);
104
105impl ActionId {
106    /// Creates an `ActionId` from a raw `u128` value.
107    pub const fn from_u128(val: u128) -> Self {
108        Self(val)
109    }
110
111    /// Returns the underlying `u128` value.
112    pub fn as_u128(&self) -> u128 {
113        self.0
114    }
115
116    /// Derives a deterministic `ActionId` from a human-readable name string.
117    ///
118    /// The name is hashed with BLAKE3; the first 16 bytes become the id.
119    pub fn from_name(name: &str) -> Self {
120        let mut hasher = blake3::Hasher::new();
121        hasher.update(name.as_bytes());
122        let hash = hasher.finalize();
123        ActionId(u128::from_le_bytes(
124            hash.as_bytes()[0..16].try_into().unwrap(),
125        ))
126    }
127}
128
129/// A stable scope identifier for raw action dispatch.
130///
131/// Scopes let a host register raw handlers for action IDs that are meaningful
132/// only inside a mounted subtree. The envelope remains unchanged; dispatch
133/// carries the nearest enclosing scope in [`ActionInput`](crate::ActionInput).
134#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, PartialOrd, Ord)]
135pub struct ActionScopeId(u128);
136
137impl ActionScopeId {
138    /// Creates an `ActionScopeId` from a raw `u128` value.
139    pub const fn from_u128(val: u128) -> Self {
140        Self(val)
141    }
142
143    /// Returns the underlying `u128` value.
144    pub fn as_u128(&self) -> u128 {
145        self.0
146    }
147
148    /// Derives a deterministic `ActionScopeId` from a stable name.
149    pub fn from_name(name: &str) -> Self {
150        let mut hasher = blake3::Hasher::new();
151        hasher.update(b"fission.action_scope.v1:");
152        hasher.update(name.as_bytes());
153        let hash = hasher.finalize();
154        ActionScopeId(u128::from_le_bytes(
155            hash.as_bytes()[0..16].try_into().unwrap(),
156        ))
157    }
158}
159
160/// Structured details for a text-input edit.
161///
162/// Every [`TextInput`](crate::ui::TextInput) binding receives this value through
163/// [`ActionInput::text_change`](crate::ActionInput::text_change), while the
164/// bound action payload continues to carry the application's stable context.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub struct UpdateTextInput {
167    /// The widget identity of the text input that changed.
168    pub node_id: WidgetId,
169    /// The complete new text value.
170    pub new_text: String,
171    /// Byte offset of the caret (insertion point).
172    pub new_caret: usize,
173    /// Byte offset of the selection anchor (equals `new_caret` when no
174    /// selection is active).
175    pub new_anchor: usize,
176}
177
178/// Payload dispatched when the caret/anchor position changes in a TextInput.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180pub struct CursorChanged {
181    pub caret: usize,
182    pub anchor: usize,
183}
184
185impl Action for CursorChanged {
186    fn static_id() -> ActionId {
187        lazy_static! {
188            pub static ref CURSOR_CHANGED_ACTION_ID: ActionId =
189                ActionId::from_name("fission_core::CursorChanged");
190        }
191        *CURSOR_CHANGED_ACTION_ID
192    }
193}
194
195/// A strongly-typed, serialisable event payload.
196///
197/// Every action type must be `Serialize + DeserializeOwned + Send + Sync + Debug`
198/// and provide a stable [`ActionId`] via [`Action::static_id`]. The runtime
199/// uses JSON serialisation internally, so actions travel across the
200/// widget/reducer boundary without generics.
201///
202/// # Implementing `Action`
203///
204/// ```rust,ignore
205/// use fission_core::{Action, ActionId};
206/// use serde::{Deserialize, Serialize};
207///
208/// #[derive(Debug, Clone, Serialize, Deserialize)]
209/// struct SetName { name: String }
210///
211/// impl Action for SetName {
212///     fn static_id() -> ActionId {
213///         ActionId::from_name("my_app::SetName")
214///     }
215/// }
216/// ```
217pub trait Action: Serialize + DeserializeOwned + Any + Send + Sync + std::fmt::Debug {
218    /// Returns the globally unique, deterministic identifier for this action type.
219    fn static_id() -> ActionId
220    where
221        Self: Sized;
222
223    /// Serialises the action to JSON bytes for transport inside an
224    /// [`ActionEnvelope`].
225    fn encode(&self) -> Vec<u8> {
226        serde_json::to_vec(self).expect("Action serialization failed")
227    }
228}
229
230/// A type-erased action envelope that can be stored in widget trees and
231/// dispatched through the [`Runtime`](crate::Runtime).
232///
233/// `ActionEnvelope` pairs an [`ActionId`] with opaque JSON bytes so that the
234/// reducer pipeline can route and deserialise actions without compile-time
235/// knowledge of the concrete type.
236///
237/// # Creating an envelope
238///
239/// ```rust,ignore
240/// let envelope: ActionEnvelope = my_action.into();
241/// runtime.dispatch(envelope, widget_id)?;
242/// ```
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244pub struct ActionEnvelope {
245    /// The identifier that routes this envelope to the correct reducer(s).
246    pub id: ActionId,
247    /// Opaque JSON-serialised payload bytes.
248    pub payload: Vec<u8>,
249}
250
251/// A typed wrapper around an [`Action`] value that converts into an
252/// [`ActionEnvelope`] via `From`.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct ActionRef<T: Action>(pub T);
255
256impl<T: Action> From<ActionRef<T>> for ActionEnvelope {
257    fn from(action_ref: ActionRef<T>) -> Self {
258        ActionEnvelope {
259            id: T::static_id(),
260            payload: action_ref.0.encode(),
261        }
262    }
263}
264
265// Also allow direct conversion for convenience if desired?
266impl<T: Action> From<T> for ActionEnvelope {
267    fn from(action: T) -> Self {
268        ActionEnvelope {
269            id: T::static_id(),
270            payload: action.encode(),
271        }
272    }
273}
274
275/// Trait for app-wide state managed by the [`Runtime`](crate::Runtime).
276///
277/// `GlobalState` is for domain state that belongs to the whole app or session:
278/// documents, logged-in user data, navigation state, caches, settings, and
279/// other data that should outlive an individual widget. Transient UI details
280/// that should disappear with one widget instance belong in local widget state
281/// instead.
282///
283/// # Example
284///
285/// ```rust,ignore
286/// #[derive(Debug, Default)]
287/// struct TodoList {
288///     items: Vec<String>,
289/// }
290/// impl GlobalState for TodoList {}
291///
292/// // Register with the runtime:
293/// runtime.add_global_state(Box::new(TodoList::default()))?;
294/// ```
295pub trait GlobalState: Any + Send + Sync + std::fmt::Debug + Downcast {}
296
297impl GlobalState for () {}
298impl GlobalState for bool {}
299impl GlobalState for String {}
300impl GlobalState for i8 {}
301impl GlobalState for i16 {}
302impl GlobalState for i32 {}
303impl GlobalState for i64 {}
304impl GlobalState for isize {}
305impl GlobalState for u8 {}
306impl GlobalState for u16 {}
307impl GlobalState for u32 {}
308impl GlobalState for u64 {}
309impl GlobalState for usize {}
310impl GlobalState for f32 {}
311impl GlobalState for f64 {}
312
313impl_downcast!(GlobalState);
314
315/// Type alias for the legacy 3-argument reducer signature used by
316/// [`Runtime::register_reducer`](crate::Runtime::register_reducer).
317///
318/// Prefer the modern handler signature via `ctx.bind(...)` from
319/// [`build::current`](crate::build::current), which provides access to effects
320/// and input context without exposing internal IR node identities.
321pub type Reducer<S> = fn(&mut S, &ActionEnvelope, WidgetId) -> anyhow::Result<()>;