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_mutable(|| 0); // auto-requests a frame on set/update
36//!
37//!     let on_click = {
38//!         let count = count.clone();
39//!         move || count.update(|c| *c += 1)
40//!     };
41//!
42//!     repose_ui::Button(
43//!         format!("Count = {}", *count.get()),
44//!         on_click,
45//!     )
46//! }
47//! ```
48//!
49//! - `remember` and `remember_mutable` 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 gesture;
114pub mod indication;
115pub mod input;
116pub mod locals;
117pub mod modifier;
118pub mod nested_scroll;
119pub mod scroll;
120pub mod prelude;
121pub mod reactive;
122pub mod render_api;
123pub mod render_context;
124pub mod runtime;
125pub mod scope;
126pub mod scope_cache;
127pub mod semantics;
128pub mod shortcuts;
129pub mod signal;
130pub mod state;
131pub mod tests;
132pub mod text;
133
134#[cfg(feature = "accesskit")]
135pub mod a11y;
136pub mod view;
137
138pub use color::*;
139pub use cursor::*;
140pub use dnd::*;
141pub use effects::*;
142pub use effects_ext::*;
143pub use focus::*;
144pub use frame_clock::{
145    peek_frame_request, request_frame, request_present, signal_fired, take_frame_request,
146    take_present_request, take_signal_fired,
147};
148pub use geometry::*;
149pub use gesture::*;
150pub use indication::*;
151pub use locals::*;
152pub use modifier::*;
153pub use prelude::*;
154pub use reactive::*;
155pub use render_api::*;
156pub use render_context::{ImageHandleGuard, RenderCommand, RenderContext};
157pub use runtime::*;
158pub use runtime::{FocusDirection, FocusManager, FocusRequester, take_focus_request};
159pub use semantics::*;
160pub use signal::*;
161pub use state::*;
162pub use text::*;
163pub use view::*;
164
165pub use repose_macros::View;
166
167/// Memoized composition scope with input + signal tracking.
168///
169/// Wraps a composable block, caching its output as long as:
170/// 1. The explicit inputs are unchanged (by `Hash` comparison).
171/// 2. No signal read during body execution has been written since last run.
172///
173/// When the cache is hit, the body is NOT executed -> the previously-composed
174/// View is returned instead, with proper ID and composer cursor advancement
175/// to keep sibling scopes consistent.
176///
177/// # Usage
178///
179/// ```ignore
180/// use repose_core::*;
181///
182/// fn MyView(s: &mut Scheduler, title: &str, count: i32) -> View {
183///     scope!("my_view", s, [title, count], {
184///         Column(Modifier::new()).child((
185///             Text(title),
186///             Text(format!("Count: {count}")),
187///         ))
188///     })
189/// }
190/// ```
191///
192/// # Signal auto-tracking
193///
194/// Any `Signal::get()` call inside the body automatically registers the scope
195/// as a dependency. When that signal is written, the scope is marked dirty and
196/// recomposed on the next frame. You don't need to put signal values in the
197/// input list -> the reactive system handles dependencies implicitly.
198///
199/// ```ignore
200/// let size = signal(100.0);
201/// scope!("animated", s, [], {
202///     let cur = size.get();  // auto-tracked; cache invalidated on write
203///     Box(Modifier::new().size(cur, cur))
204/// })
205/// ```
206///
207/// # `f32`/`f64` in explicit inputs
208///
209/// Float types don't implement `Hash`. For float inputs, use `.to_bits()`:
210///
211/// ```ignore
212/// scope!("s", s, [my_float.to_bits()], { ... })
213/// ```
214///
215/// Or -> better -> read floats from a `Signal<f32>` inside the body (auto-tracked).
216///
217/// # Compatibility with `remember`
218///
219/// `remember` slots consumed inside the body are tracked and properly advanced
220/// on cache hit, so sibling `remember` calls remain consistent.
221#[macro_export]
222macro_rules! scope {
223    // With explicit inputs
224    ($key:expr, $s:expr, [$($input:expr),+ $(,)?], $body:block) => {{
225        let _key: &str = $key;
226
227        let _input_hash = {
228            use std::hash::{Hash, Hasher};
229            let mut _hasher = std::collections::hash_map::DefaultHasher::new();
230            $(
231                Hash::hash(&$input, &mut _hasher);
232            )*
233            _hasher.finish()
234        };
235
236        if !$crate::scope_cache::should_run(_key, _input_hash) {
237            $crate::scope_cache::get_cached(_key, $s)
238        } else {
239            $crate::scope_cache::clear_scope_deps(_key);
240
241            let _prev_cursor = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor);
242
243            $s.enter_scope(_key);
244            let mut _result = $crate::scope_cache::with_scope_key(_key, || $body);
245            $s.exit_scope();
246
247            _result.modifier.repaint_boundary = true;
248            _result.scope_key = Some(_key.to_string());
249
250            let _slot_delta = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor) - _prev_cursor;
251
252            $crate::scope_cache::set_cache(_key, _input_hash, _result.clone(), _slot_delta);
253
254            _result
255        }
256    }};
257
258    // Without explicit inputs -> skip Hash import
259    ($key:expr, $s:expr, [], $body:block) => {{
260        let _key: &str = $key;
261        let _input_hash: u64 = 0;
262
263        if !$crate::scope_cache::should_run(_key, _input_hash) {
264            $crate::scope_cache::get_cached(_key, $s)
265        } else {
266            $crate::scope_cache::clear_scope_deps(_key);
267
268            let _prev_cursor = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor);
269
270            $s.enter_scope(_key);
271            let mut _result = $crate::scope_cache::with_scope_key(_key, || $body);
272            $s.exit_scope();
273
274            _result.modifier.repaint_boundary = true;
275            _result.scope_key = Some(_key.to_string());
276
277            let _slot_delta = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor) - _prev_cursor;
278
279            $crate::scope_cache::set_cache(_key, _input_hash, _result.clone(), _slot_delta);
280
281            _result
282        }
283    }};
284}