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