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 `scoped_effect_once` / `disposable_effect` for mount-once side-effects
77//! with cleanups:
78//!
79//! ```ignore
80//! use repose_core::*;
81//!
82//! fn Example() -> View {
83//! scoped_effect_once(|| {
84//! log::info!("Mounted Example");
85//! on_unmount(|| log::info!("Unmounted Example"))
86//! });
87//!
88//! // ...
89//! repose_ui::Box(Modifier::new())
90//! }
91//! ```
92//!
93//! - `effect` / `scoped_effect` run on every call and register cleanup on the
94//! current `Scope`. Called directly in a composable body they re-run every
95//! frame - use `effect_once` / `scoped_effect_once` for mount-once setup.
96//! - `disposable_effect(key, ..)` re-runs on key change and cleans up on
97//! unmount (callsite-keyed, branch-stable).
98//! - `launched_effect!(key, ..)` is the cancellable launched variant;
99//! `launched_effect_uncancelled!` is explicit fire-and-forget.
100//!
101//! For long‑running tasks (network, timers), prefer building small helpers on
102//! top of `disposable_effect` so everything cleans up correctly when the UI that
103//! owns it disappears.
104
105pub mod animation;
106pub mod animation_driver;
107pub mod clipboard;
108pub mod color;
109pub mod cursor;
110pub mod debounce;
111pub mod dnd;
112pub mod effects;
113pub mod effects_ext;
114pub mod error;
115pub mod focus;
116pub mod frame_clock;
117pub mod geometry;
118pub mod gesture;
119pub mod indication;
120pub mod input;
121pub mod locals;
122pub mod modifier;
123pub mod nested_scroll;
124pub mod prelude;
125pub mod present_mode;
126pub mod reactive;
127pub mod render_api;
128pub mod render_context;
129pub mod runtime;
130pub mod scope;
131pub mod scope_cache;
132pub mod scroll;
133pub mod semantics;
134pub mod shortcuts;
135pub mod signal;
136pub mod state;
137pub mod tests;
138pub mod text;
139pub mod units;
140
141pub mod timer;
142
143#[cfg(feature = "accesskit")]
144pub mod a11y;
145pub mod view;
146
147pub use color::*;
148pub use cursor::*;
149pub use effects::*;
150pub use effects_ext::*;
151pub use focus::*;
152pub use frame_clock::{
153 peek_frame_request, request_frame, request_present, signal_fired, take_frame_request,
154 take_present_request, take_signal_fired,
155};
156pub use geometry::*;
157pub use gesture::*;
158pub use locals::*;
159pub use modifier::*;
160pub use prelude::*;
161pub use present_mode::*;
162pub use reactive::*;
163pub use render_api::*;
164pub use render_context::{ImageHandleGuard, RenderCommand, RenderContext};
165pub use runtime::*;
166pub use runtime::{FocusDirection, FocusManager, FocusRequester, take_focus_request};
167pub use semantics::*;
168pub use signal::*;
169pub use state::*;
170pub use text::*;
171pub use units::*;
172pub use view::*;
173
174pub use repose_macros::View;
175
176/// Memoized composition scope with input + signal tracking.
177///
178/// Wraps a composable block, caching its output as long as:
179/// 1. The explicit inputs are unchanged (by `Hash` comparison).
180/// 2. No signal read during body execution has been written since last run.
181///
182/// When the cache is hit, the body is NOT executed -> the previously-composed
183/// View is returned instead, with proper ID and composer cursor advancement
184/// to keep sibling scopes consistent.
185///
186/// # Usage
187///
188/// ```ignore
189/// use repose_core::*;
190///
191/// fn MyView(s: &mut Scheduler, title: &str, count: i32) -> View {
192/// scope!("my_view", s, [title, count], {
193/// Column(Modifier::new()).child((
194/// Text(title),
195/// Text(format!("Count: {count}")),
196/// ))
197/// })
198/// }
199/// ```
200///
201/// Keys are global bare strings: two call sites sharing one key share one
202/// cache entry. Use `scope_auto!` for static call sites or `scope_keyed!`
203/// with a stable item id inside lists.
204///
205/// # Signal auto-tracking
206///
207/// Any `Signal::get()` call inside the body automatically registers the scope
208/// as a dependency. When that signal is written, the scope is marked dirty and
209/// recomposed on the next frame. You don't need to put signal values in the
210/// input list -> the reactive system handles dependencies implicitly.
211///
212/// ```ignore
213/// let size = signal(100.0);
214/// scope!("animated", s, [], {
215/// let cur = size.get(); // auto-tracked; cache invalidated on write
216/// Box(Modifier::new().size(cur, cur))
217/// })
218/// ```
219///
220/// # `f32`/`f64` in explicit inputs
221///
222/// Float types don't implement `Hash`. For float inputs, use `.to_bits()`:
223///
224/// ```ignore
225/// scope!("s", s, [my_float.to_bits()], { ... })
226/// ```
227///
228/// Or -> better -> read floats from a `Signal<f32>` inside the body (auto-tracked).
229///
230/// # Compatibility with `remember`
231///
232/// `remember` slots consumed inside the body are tracked and properly advanced
233/// on cache hit, so sibling `remember` calls remain consistent.
234#[macro_export]
235macro_rules! scope {
236 // With explicit inputs
237 ($key:expr, $s:expr, [$($input:expr),+ $(,)?], $body:block) => {{
238 let _key: &str = $key;
239
240 let _input_hash = {
241 use std::hash::{Hash, Hasher};
242 let mut _hasher = std::collections::hash_map::DefaultHasher::new();
243 $(
244 Hash::hash(&$input, &mut _hasher);
245 )*
246 _hasher.finish()
247 };
248
249 if !$crate::scope_cache::should_run(_key, _input_hash) {
250 $crate::scope_cache::get_cached(_key, $s)
251 } else {
252 $crate::scope_cache::clear_scope_deps(_key);
253
254 let _prev_cursor = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor);
255
256 let _sched_guard = $s.scope_guard_raw(_key);
257 let mut _result = $crate::scope_cache::with_scope_key(_key, || $body);
258 drop(_sched_guard);
259
260 _result.modifier.repaint_boundary = true;
261 _result.scope_key = Some(_key.to_string());
262
263 let _slot_delta = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor) - _prev_cursor;
264
265 $crate::scope_cache::set_cache(_key, _input_hash, _result.clone(), _slot_delta);
266
267 _result
268 }
269 }};
270
271 // Without explicit inputs -> skip Hash import
272 ($key:expr, $s:expr, [], $body:block) => {{
273 let _key: &str = $key;
274 let _input_hash: u64 = 0;
275
276 if !$crate::scope_cache::should_run(_key, _input_hash) {
277 $crate::scope_cache::get_cached(_key, $s)
278 } else {
279 $crate::scope_cache::clear_scope_deps(_key);
280
281 let _prev_cursor = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor);
282
283 let _sched_guard = $s.scope_guard_raw(_key);
284 let mut _result = $crate::scope_cache::with_scope_key(_key, || $body);
285 drop(_sched_guard);
286
287 _result.modifier.repaint_boundary = true;
288 _result.scope_key = Some(_key.to_string());
289
290 let _slot_delta = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor) - _prev_cursor;
291
292 $crate::scope_cache::set_cache(_key, _input_hash, _result.clone(), _slot_delta);
293
294 _result
295 }
296 }};
297}
298
299/// `scope!` with an auto-namespaced key (`module:file:line:col`). Use for
300/// static call sites so two components cannot share one cache entry.
301/// For dynamic lists, pass a stable item id as part of `$key` instead.
302#[macro_export]
303macro_rules! scope_auto {
304 ($s:expr, [$($input:expr),* $(,)?], $body:block) => {{
305 $crate::scope!(
306 concat!(module_path!(), ":", file!(), ":", line!(), ":", column!()),
307 $s,
308 [$($input),*],
309 $body
310 )
311 }};
312}
313
314/// `scope!` keyed by a stable item id plus the call site. Use inside loops /
315/// lazy lists so each item owns its cache entry.
316#[macro_export]
317macro_rules! scope_keyed {
318 ($s:expr, $id:expr, [$($input:expr),* $(,)?], $body:block) => {{
319 $crate::scope!(
320 concat!(module_path!(), ":", file!(), ":", line!(), ":", column!(), ":", $id),
321 $s,
322 [$($input),*],
323 $body
324 )
325 }};
326}