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 image_intrinsic;
120pub mod indication;
121pub mod input;
122pub mod locals;
123pub mod modifier;
124pub mod nested_scroll;
125pub mod prelude;
126pub mod present_mode;
127pub mod reactive;
128pub mod render_api;
129pub mod render_context;
130pub mod runtime;
131pub mod scope;
132pub mod scope_cache;
133pub mod scroll;
134pub mod semantics;
135pub mod shortcuts;
136pub mod signal;
137pub mod state;
138pub mod tests;
139pub mod text;
140pub mod units;
141
142pub mod timer;
143
144#[cfg(feature = "accesskit")]
145pub mod a11y;
146pub mod view;
147pub mod visual;
148
149pub use color::*;
150pub use cursor::*;
151pub use effects::*;
152pub use effects_ext::*;
153pub use focus::*;
154pub use frame_clock::{
155 peek_frame_request, request_frame, request_present, signal_fired, take_frame_request,
156 take_present_request, take_signal_fired,
157};
158pub use geometry::*;
159pub use gesture::*;
160pub use image_intrinsic::{
161 clear_image_intrinsic_size, image_intrinsic_size, set_image_intrinsic_size,
162};
163pub use locals::*;
164pub use modifier::*;
165pub use prelude::*;
166pub use present_mode::*;
167pub use reactive::*;
168pub use render_api::*;
169pub use render_context::{ImageHandleGuard, RenderCommand, RenderContext};
170pub use runtime::*;
171pub use runtime::{FocusDirection, FocusManager, FocusRequester, take_focus_request};
172pub use semantics::*;
173pub use signal::*;
174pub use state::*;
175pub use text::*;
176pub use units::*;
177pub use view::*;
178pub use visual::*;
179
180pub use repose_macros::View;
181
182/// Memoized composition scope with input + signal tracking.
183///
184/// Wraps a composable block, caching its output as long as:
185/// 1. The explicit inputs are unchanged (by `Hash` comparison).
186/// 2. No signal read during body execution has been written since last run.
187///
188/// When the cache is hit, the body is NOT executed -> the previously-composed
189/// View is returned instead, with proper ID and composer cursor advancement
190/// to keep sibling scopes consistent.
191///
192/// # Usage
193///
194/// ```ignore
195/// use repose_core::*;
196///
197/// fn MyView(s: &mut Scheduler, title: &str, count: i32) -> View {
198/// scope!("my_view", s, [title, count], {
199/// Column(Modifier::new()).child((
200/// Text(title),
201/// Text(format!("Count: {count}")),
202/// ))
203/// })
204/// }
205/// ```
206///
207/// Keys are global bare strings: two call sites sharing one key share one
208/// cache entry. Use `scope_auto!` for static call sites or `scope_keyed!`
209/// with a stable item id inside lists.
210///
211/// # Signal auto-tracking
212///
213/// Any `Signal::get()` call inside the body automatically registers the scope
214/// as a dependency. When that signal is written, the scope is marked dirty and
215/// recomposed on the next frame. You don't need to put signal values in the
216/// input list -> the reactive system handles dependencies implicitly.
217///
218/// ```ignore
219/// let size = signal(100.0);
220/// scope!("animated", s, [], {
221/// let cur = size.get(); // auto-tracked; cache invalidated on write
222/// Box(Modifier::new().size(cur, cur))
223/// })
224/// ```
225///
226/// # `f32`/`f64` in explicit inputs
227///
228/// Float types don't implement `Hash`. For float inputs, use `.to_bits()`:
229///
230/// ```ignore
231/// scope!("s", s, [my_float.to_bits()], { ... })
232/// ```
233///
234/// Or -> better -> read floats from a `Signal<f32>` inside the body (auto-tracked).
235///
236/// # Compatibility with `remember`
237///
238/// `remember` slots consumed inside the body are tracked and properly advanced
239/// on cache hit, so sibling `remember` calls remain consistent.
240#[macro_export]
241macro_rules! scope {
242 // With explicit inputs
243 ($key:expr, $s:expr, [$($input:expr),+ $(,)?], $body:block) => {{
244 let _key = $key.to_string();
245 let _key: &str = &_key;
246 $crate::scope_cache::validate_scope_key(_key);
247
248 let _input_hash = {
249 use std::hash::{Hash, Hasher};
250 let mut _hasher = std::collections::hash_map::DefaultHasher::new();
251 $(
252 Hash::hash(&$input, &mut _hasher);
253 )*
254 _hasher.finish()
255 };
256
257 if !$crate::scope_cache::should_run(_key, _input_hash) {
258 $crate::scope_cache::get_cached(_key, $s)
259 } else {
260 let _dirty_before = $crate::scope_cache::dirty_generation(_key);
261 $crate::scope_cache::clear_scope_deps(_key);
262
263 let _prev_cursor = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor);
264
265 let _sched_guard = $s.scope_guard_raw(_key);
266 let mut _result = $crate::scope_cache::with_scope_key(_key, || $body);
267 drop(_sched_guard);
268
269 _result.modifier.repaint_boundary = true;
270 _result.scope_key = Some(_key.to_string());
271
272 let _slot_delta = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor) - _prev_cursor;
273
274 $crate::scope_cache::set_cache_preserving_dirty(
275 _key,
276 _input_hash,
277 _result.clone(),
278 _slot_delta,
279 _dirty_before,
280 );
281
282 _result
283 }
284 }};
285
286 // Without explicit inputs -> skip Hash import
287 ($key:expr, $s:expr, [], $body:block) => {{
288 let _key = $key.to_string();
289 let _key: &str = &_key;
290 $crate::scope_cache::validate_scope_key(_key);
291 let _input_hash: u64 = 0;
292
293 if !$crate::scope_cache::should_run(_key, _input_hash) {
294 $crate::scope_cache::get_cached(_key, $s)
295 } else {
296 let _dirty_before = $crate::scope_cache::dirty_generation(_key);
297 $crate::scope_cache::clear_scope_deps(_key);
298
299 let _prev_cursor = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor);
300
301 let _sched_guard = $s.scope_guard_raw(_key);
302 let mut _result = $crate::scope_cache::with_scope_key(_key, || $body);
303 drop(_sched_guard);
304
305 _result.modifier.repaint_boundary = true;
306 _result.scope_key = Some(_key.to_string());
307
308 let _slot_delta = $crate::runtime::COMPOSER.with(|c| c.borrow().cursor) - _prev_cursor;
309
310 $crate::scope_cache::set_cache_preserving_dirty(
311 _key,
312 _input_hash,
313 _result.clone(),
314 _slot_delta,
315 _dirty_before,
316 );
317
318 _result
319 }
320 }};
321}
322
323/// `scope!` with an auto-namespaced key (`module:file:line:col`). Use for
324/// static call sites so two components cannot share one cache entry.
325/// For dynamic lists, pass a stable item id as part of `$key` instead.
326#[macro_export]
327macro_rules! scope_auto {
328 ($s:expr, [$($input:expr),* $(,)?], $body:block) => {{
329 $crate::scope!(
330 concat!(module_path!(), ":", file!(), ":", line!(), ":", column!()),
331 $s,
332 [$($input),*],
333 $body
334 )
335 }};
336}
337
338/// `scope!` keyed by a stable item id plus the call site. Use inside loops /
339/// lazy lists so each item owns its cache entry.
340#[macro_export]
341macro_rules! scope_keyed {
342 ($s:expr, $id:expr, [$($input:expr),* $(,)?], $body:block) => {{
343 $crate::scope!(
344 format!(
345 "{}:{}:{}:{}:{}",
346 module_path!(),
347 file!(),
348 line!(),
349 column!(),
350 $id
351 ),
352 $s,
353 [$($input),*],
354 $body
355 )
356 }};
357}