Skip to main content

euv_core/reactive/signal/
struct.rs

1use crate::*;
2
3/// Inner state of a signal, holding the value and subscribed listeners.
4///
5/// This struct is not exposed directly; use `Signal` instead.
6#[derive(Data)]
7pub(crate) struct SignalInner<T>
8where
9    T: Clone,
10{
11    /// The current value of the signal.
12    #[get(pub(crate))]
13    #[set(pub(crate))]
14    pub(crate) value: T,
15    /// Callbacks to invoke when the value changes.
16    #[get(pub(crate))]
17    #[set(pub(crate))]
18    pub(crate) listeners: Vec<Box<dyn FnMut()>>,
19    /// Whether this signal is still active. Set to `false` by `clear_listeners()`
20    /// to make subsequent `set()` calls complete no-ops (no value update, no
21    /// listener invocation, no `schedule_signal_update()`), ensuring stale
22    /// closures like orphaned `setInterval` handlers become harmless.
23    #[get(pub(crate), type(copy))]
24    #[set(pub(crate))]
25    pub(crate) alive: bool,
26}
27
28/// A reactive signal handle.
29///
30/// Allows reading, writing, and subscribing to changes.
31/// Implements `Copy` for ergonomic use; all copies share the same underlying state.
32///
33/// SAFETY: The inner pointer is allocated via `Box::leak` and lives for the
34/// entire program. This is safe in single-threaded WASM contexts where no
35/// concurrent access can occur.
36pub struct Signal<T>
37where
38    T: Clone + PartialEq,
39{
40    /// Raw pointer to the heap-allocated signal inner state.
41    pub(crate) inner: *mut SignalInner<T>,
42}
43
44/// A `Sync` wrapper for single-threaded global `Signal` access.
45///
46/// SAFETY: This type is only safe to use in single-threaded contexts
47/// (e.g., WASM). It implements `Sync` to allow usage as a `static`
48/// variable, but concurrent access from multiple threads would be
49/// undefined behavior.
50pub struct SignalCell<T>
51where
52    T: Clone + PartialEq,
53{
54    /// Interior-mutable storage for an optional signal handle.
55    pub(crate) inner: UnsafeCell<Option<Signal<T>>>,
56}