Skip to main content

repose_core/
lib.rs

1//! # State, Signals, and Effects
2//!
3//! Repose uses a small reactive core instead of an explicit widget tree with
4//! mutable fields. There are three main pieces:
5//!
6//! - `Signal<T>` - observable, reactive value.
7//! - `remember*` - lifecycle‑aware storage bound to composition.
8//! - `effect` / `scoped_effect` - side‑effects with cleanup.
9//!
10//! ## Signals
11//!
12//! `Signal<T>` is a cloneable handle to a piece of state:
13//!
14//! ```rust
15//! use repose_core::*;
16//!
17//! let count = signal(0);
18//! count.set(1);
19//! count.update(|v| *v += 1);
20//! assert_eq!(count.get(), 2);
21//! ```
22//!
23//! Reads participate in a dependency graph: when you call `get()` inside an
24//! observer or `produce_state`, future writes will automatically recompute that
25//! observer.
26//!
27//! ## Remembered state
28//!
29//! UI state is typically held in `remember_*` slots rather than globals:
30//!
31//! ```ignore
32//! use repose_core::*;
33//!
34//! fn CounterView() -> View {
35//!     let count = remember_state(|| 0); // Rc<RefCell<i32>>
36//!
37//!     let on_click = {
38//!         let count = count.clone();
39//!         move || *count.borrow_mut() += 1
40//!     };
41//!
42//!     repose_ui::Button(
43//!         format!("Count = {}", *count.borrow()),
44//!         on_click,
45//!     )
46//! }
47//! ```
48//!
49//! - `remember` and `remember_state` are order‑based: the Nth call in a
50//!   composition slot always refers to the Nth stored value.
51//! - `remember_with_key` and `remember_state_with_key` are key‑based and more
52//!   stable across conditional branches.
53//!
54//! ## Derived state
55//!
56//! `produce_state` computes a `Signal<T>` from other signals and recomputes it
57//! automatically when dependencies change:
58//!
59//! ```rust
60//! use repose_core::*;
61//!
62//! let first = signal("Jane".to_string());
63//! let last  = signal("Doe".to_string());
64//!
65//! let full = produce_state("full_name", {
66//!     let first = first.clone();
67//!     let last  = last.clone();
68//!     move || format!("{} {}", first.get(), last.get())
69//! });
70//!
71//! assert_eq!(full.get(), "Jane Doe");
72//! ```
73//!
74//! ## Effects and cleanup
75//!
76//! Use `effect` / `scoped_effect` for one‑off side‑effects with cleanups:
77//!
78//! ```ignore
79//! use repose_core::*;
80//!
81//! fn Example() -> View {
82//!     scoped_effect(|| {
83//!         log::info!("Mounted Example");
84//!         on_unmount(|| log::info!("Unmounted Example"))
85//!     });
86//!
87//!     // ...
88//!     repose_ui::Box(Modifier::new())
89//! }
90//! ```
91//!
92//! - `effect` runs once when the view is composed and returns a `Dispose`
93//!   guard that will be run when the scope is torn down.
94//! - `scoped_effect` is wired to the current `Scope` and is cleaned up on
95//!   scope disposal (e.g. when a navigation entry is popped).
96//!
97//! For long‑running tasks (network, timers), prefer building small helpers on
98//! top of `scoped_effect` so everything cleans up correctly when the UI that
99//! owns it disappears.
100
101pub mod animation;
102pub mod animation_driver;
103pub mod clipboard;
104pub mod color;
105pub mod cursor;
106pub mod dnd;
107pub mod effects;
108pub mod effects_ext;
109pub mod error;
110pub mod focus;
111pub mod frame_clock;
112pub mod geometry;
113pub mod indication;
114pub mod input;
115pub mod locals;
116pub mod modifier;
117pub mod nested_scroll;
118pub mod scroll;
119pub mod prelude;
120pub mod reactive;
121pub mod render_api;
122pub mod runtime;
123pub mod scope;
124pub mod scope_cache;
125pub mod semantics;
126pub mod shortcuts;
127pub mod signal;
128pub mod state;
129pub mod tests;
130pub mod text;
131pub mod view;
132
133pub use color::*;
134pub use cursor::*;
135pub use dnd::*;
136pub use effects::*;
137pub use effects_ext::*;
138pub use focus::*;
139pub use frame_clock::{
140    peek_frame_request, request_frame, signal_fired, take_frame_request, take_signal_fired,
141};
142pub use geometry::*;
143pub use indication::*;
144pub use locals::*;
145pub use modifier::*;
146pub use prelude::*;
147pub use reactive::*;
148pub use render_api::*;
149pub use runtime::*;
150pub use runtime::{FocusDirection, FocusManager, FocusRequester, take_focus_request};
151pub use semantics::*;
152pub use signal::*;
153pub use state::*;
154pub use text::*;
155pub use view::*;
156
157pub use repose_macros::View;
158
159/// Memoized composition scope with input + signal tracking.
160///
161/// Wraps a composable block, caching its output as long as:
162/// 1. The explicit inputs are unchanged (by `Hash` comparison).
163/// 2. No signal read during body execution has been written since last run.
164///
165/// When the cache is hit, the body is NOT executed -> the previously-composed
166/// View is returned instead, with proper ID and composer cursor advancement
167/// to keep sibling scopes consistent.
168///
169/// # Usage
170///
171/// ```ignore
172/// use repose_core::*;
173///
174/// fn MyView(s: &mut Scheduler, title: &str, count: i32) -> View {
175///     scope!("my_view", s, [title, count], {
176///         Column(Modifier::new()).child((
177///             Text(title),
178///             Text(format!("Count: {count}")),
179///         ))
180///     })
181/// }
182/// ```
183///
184/// # Signal auto-tracking
185///
186/// Any `Signal::get()` call inside the body automatically registers the scope
187/// as a dependency. When that signal is written, the scope is marked dirty and
188/// recomposed on the next frame. You don't need to put signal values in the
189/// input list -> the reactive system handles dependencies implicitly.
190///
191/// ```ignore
192/// let size = signal(100.0);
193/// scope!("animated", s, [], {
194///     let cur = size.get();  // auto-tracked; cache invalidated on write
195///     Box(Modifier::new().size(cur, cur))
196/// })
197/// ```
198///
199/// # `f32`/`f64` in explicit inputs
200///
201/// Float types don't implement `Hash`. For float inputs, use `.to_bits()`:
202///
203/// ```ignore
204/// scope!("s", s, [my_float.to_bits()], { ... })
205/// ```
206///
207/// Or -> better -> read floats from a `Signal<f32>` inside the body (auto-tracked).
208///
209/// # Compatibility with `remember`
210///
211/// `remember` slots consumed inside the body are tracked and properly advanced
212/// on cache hit, so sibling `remember` calls remain consistent.
213#[macro_export]
214macro_rules! scope {
215    // With explicit inputs
216    ($key:expr, $s:expr, [$($input:expr),+ $(,)?], $body:block) => {{
217        let _key: &str = $key;
218
219        let _input_hash = {
220            use std::hash::{Hash, Hasher};
221            let mut _hasher = std::collections::hash_map::DefaultHasher::new();
222            $(
223                Hash::hash(&$input, &mut _hasher);
224            )*
225            _hasher.finish()
226        };
227
228        if !$crate::scope_cache::should_run(_key, _input_hash) {
229            $crate::scope_cache::get_cached(_key, $s)
230        } else {
231            $crate::scope_cache::clear_scope_deps(_key);
232
233            let _prev_cursor = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor);
234
235            $s.enter_scope(_key);
236            let mut _result = $crate::scope_cache::with_scope_key(_key, || $body);
237            $s.exit_scope();
238
239            _result.modifier.repaint_boundary = true;
240            _result.scope_key = Some(_key.to_string());
241
242            let _slot_delta = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor) - _prev_cursor;
243
244            $crate::scope_cache::set_cache(_key, _input_hash, _result.clone(), _slot_delta);
245
246            _result
247        }
248    }};
249
250    // Without explicit inputs -> skip Hash import
251    ($key:expr, $s:expr, [], $body:block) => {{
252        let _key: &str = $key;
253        let _input_hash: u64 = 0;
254
255        if !$crate::scope_cache::should_run(_key, _input_hash) {
256            $crate::scope_cache::get_cached(_key, $s)
257        } else {
258            $crate::scope_cache::clear_scope_deps(_key);
259
260            let _prev_cursor = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor);
261
262            $s.enter_scope(_key);
263            let mut _result = $crate::scope_cache::with_scope_key(_key, || $body);
264            $s.exit_scope();
265
266            _result.modifier.repaint_boundary = true;
267            _result.scope_key = Some(_key.to_string());
268
269            let _slot_delta = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor) - _prev_cursor;
270
271            $crate::scope_cache::set_cache(_key, _input_hash, _result.clone(), _slot_delta);
272
273            _result
274        }
275    }};
276}