Skip to main content

euv_core/reactive/signal/
impl.rs

1use super::*;
2
3/// Manual `Clone` implementation so `Signal<T>` is always `Copy` regardless of `T`.
4impl<T> Clone for Signal<T>
5where
6    T: 'static,
7{
8    /// Copies the lightweight 8-byte signal handle.
9    ///
10    /// # Arguments
11    ///
12    /// - `&Self` - Signal handle to copy.
13    ///
14    /// # Returns
15    ///
16    /// - `Self` - Identical signal handle.
17    fn clone(&self) -> Self {
18        *self
19    }
20}
21
22/// Marker `Copy` implementation for `Signal<T>`.
23impl<T> Copy for Signal<T> where T: 'static {}
24
25/// Zero-allocation dangling `Default` handle for `Signal<T>`, used when initializing component prop descriptors.
26impl<T> Default for Signal<T>
27where
28    T: 'static,
29{
30    /// Constructs an unallocated placeholder `Signal<T>` handle with `SignalId::default()`.
31    ///
32    /// # Returns
33    ///
34    /// - `Self` - Zero-cost placeholder signal handle.
35    fn default() -> Self {
36        Self {
37            id: SignalId::default(),
38            marker: PhantomData,
39        }
40    }
41}
42
43/// Equality comparison by underlying `SignalId`.
44impl<T> PartialEq for Signal<T>
45where
46    T: 'static,
47{
48    /// Compares two signal handles by arena identifier.
49    ///
50    /// # Arguments
51    ///
52    /// - `&Self` - Left-hand signal handle.
53    /// - `&Self` - Right-hand signal handle.
54    ///
55    /// # Returns
56    ///
57    /// - `bool` - True if both handles reference the same arena slot and generation.
58    fn eq(&self, other: &Self) -> bool {
59        self.id() == other.id()
60    }
61}
62
63/// Reflexive equality for `Signal<T>`.
64impl<T> Eq for Signal<T> where T: 'static {}
65
66/// Hash implementation based on underlying `SignalId`.
67impl<T> Hash for Signal<T>
68where
69    T: 'static,
70{
71    /// Hashes the underlying arena signal identifier.
72    ///
73    /// # Arguments
74    ///
75    /// - `&Self` - Signal handle to hash.
76    /// - `&mut H` - Hasher state.
77    fn hash<H>(&self, state: &mut H)
78    where
79        H: Hasher,
80    {
81        self.id().hash(state);
82    }
83}
84
85/// Core reactive operations for `Signal<T>`.
86impl<T> Signal<T>
87where
88    T: 'static,
89{
90    /// Allocates a new reactive signal initialized with `initial_value`.
91    ///
92    /// # Arguments
93    ///
94    /// - `T` - Initial signal value.
95    ///
96    /// # Returns
97    ///
98    /// - `Self` - Copyable handle to the created signal.
99    #[must_use]
100    pub fn new(initial_value: T) -> Self {
101        let id: SignalId = with_runtime(
102            |rt: &mut ReactiveRuntime| rt.create_signal(initial_value),
103            SignalId::default(),
104        );
105        Self {
106            id,
107            marker: PhantomData,
108        }
109    }
110
111    /// Allocates a new reactive signal detached from any enclosing transient `Scope` so hub/store state survives UI rebuilds.
112    ///
113    /// # Arguments
114    ///
115    /// - `T` - Initial signal value.
116    ///
117    /// # Returns
118    ///
119    /// - `Self` - Copyable handle to the created detached signal.
120    #[must_use]
121    pub fn new_detached(initial_value: T) -> Self {
122        let id: SignalId = with_runtime(
123            |rt: &mut ReactiveRuntime| rt.create_detached_signal(initial_value),
124            SignalId::default(),
125        );
126        Self {
127            id,
128            marker: PhantomData,
129        }
130    }
131
132    /// Reconstructs a typed `Signal<T>` handle from an arena `SignalId`.
133    ///
134    /// # Arguments
135    ///
136    /// - `SignalId` - Arena signal identifier.
137    ///
138    /// # Returns
139    ///
140    /// - `Self` - Lightweight copyable signal handle.
141    #[must_use]
142    pub(crate) fn from_raw_id(id: SignalId) -> Self {
143        Self {
144            id,
145            marker: PhantomData,
146        }
147    }
148
149    /// Returns the underlying `SignalId`.
150    ///
151    /// # Arguments
152    ///
153    /// - `&Self` - Signal handle.
154    ///
155    /// # Returns
156    ///
157    /// - `SignalId` - Underlying arena identifier.
158    #[must_use]
159    pub fn id(&self) -> SignalId {
160        let Self { id, .. } = *self;
161        id
162    }
163
164    /// Records a dependency on this signal in the active observer without cloning its value.
165    ///
166    /// # Arguments
167    ///
168    /// - `&Self` - Signal handle to track.
169    pub fn track(&self) {
170        let id: SignalId = self.id();
171        with_runtime(
172            |rt: &mut ReactiveRuntime| {
173                rt.track_dependency(DependencyId::Signal(id));
174            },
175            (),
176        );
177    }
178
179    /// Reads the current value by cloning and tracks the active observer dependency.
180    ///
181    /// # Arguments
182    ///
183    /// - `&Self` - Signal handle to read.
184    ///
185    /// # Returns
186    ///
187    /// - `Option<T>` - Current value if the signal is still alive.
188    #[must_use]
189    pub fn try_get(&self) -> Option<T>
190    where
191        T: Clone,
192    {
193        let id: SignalId = self.id();
194        with_runtime(
195            |rt: &mut ReactiveRuntime| rt.read_signal_cloned::<T>(id),
196            None,
197        )
198    }
199
200    /// Reads the current value, returning `T::default()` if the signal was disposed.
201    ///
202    /// # Arguments
203    ///
204    /// - `&Self` - Signal handle to read.
205    ///
206    /// # Returns
207    ///
208    /// - `T` - Current value or default fallback.
209    #[must_use]
210    pub fn get(&self) -> T
211    where
212        T: Clone + Default,
213    {
214        self.try_get().unwrap_or_default()
215    }
216
217    /// Reads the current value without tracking any reactive dependency.
218    ///
219    /// # Arguments
220    ///
221    /// - `&Self` - Signal handle to inspect.
222    ///
223    /// # Returns
224    ///
225    /// - `Option<T>` - Current value if alive.
226    #[must_use]
227    pub fn try_get_untracked(&self) -> Option<T>
228    where
229        T: Clone,
230    {
231        let id: SignalId = self.id();
232        with_runtime(
233            |rt: &mut ReactiveRuntime| rt.read_signal_untracked::<T>(id),
234            None,
235        )
236    }
237
238    /// Reads the current value untracked, returning `T::default()` if disposed.
239    ///
240    /// # Arguments
241    ///
242    /// - `&Self` - Signal handle to inspect.
243    ///
244    /// # Returns
245    ///
246    /// - `T` - Current value or default fallback.
247    #[must_use]
248    pub fn get_untracked(&self) -> T
249    where
250        T: Clone + Default,
251    {
252        self.try_get_untracked().unwrap_or_default()
253    }
254
255    /// Applies `reader` to a cloned snapshot outside any `RefCell` borrow so nested reads remain safe.
256    ///
257    /// # Arguments
258    ///
259    /// - `&Self` - Signal handle to read.
260    /// - `F` - Reader closure receiving `&T`.
261    ///
262    /// # Returns
263    ///
264    /// - `Option<R>` - Closure return value if the signal is alive.
265    pub fn with<F, R>(&self, reader: F) -> Option<R>
266    where
267        T: Clone,
268        F: FnOnce(&T) -> R,
269    {
270        let snapshot: T = self.try_get()?;
271        Some(reader(&snapshot))
272    }
273
274    /// Replaces the stored value and flushes downstream reactive effects.
275    ///
276    /// # Arguments
277    ///
278    /// - `&Self` - Signal handle to write.
279    /// - `T` - Replacement value.
280    ///
281    /// # Returns
282    ///
283    /// - `bool` - True when the signal was alive and updated.
284    pub fn set(&self, value: T) -> bool {
285        let id: SignalId = self.id();
286        let (updated, should_flush): (bool, bool) = with_runtime(
287            |rt: &mut ReactiveRuntime| rt.write_signal(id, value),
288            (false, false),
289        );
290        if should_flush {
291            flush_effects();
292        }
293        updated
294    }
295
296    /// Replaces the stored value only when `value` differs from the current stored value.
297    ///
298    /// # Arguments
299    ///
300    /// - `&Self` - Signal handle to write.
301    /// - `T` - Candidate value.
302    ///
303    /// # Returns
304    ///
305    /// - `bool` - True when the value changed and downstream effects were scheduled.
306    pub fn set_if_changed(&self, value: T) -> bool
307    where
308        T: PartialEq,
309    {
310        let id: SignalId = self.id();
311        let (updated, should_flush): (bool, bool) = with_runtime(
312            |rt: &mut ReactiveRuntime| rt.write_signal_if_changed(id, value),
313            (false, false),
314        );
315        if should_flush {
316            flush_effects();
317        }
318        updated
319    }
320
321    /// Mutates the signal value using `updater` outside the runtime borrow and flushes effects.
322    ///
323    /// # Arguments
324    ///
325    /// - `&Self` - Signal handle to update.
326    /// - `F` - Mutation closure receiving `&mut T`.
327    ///
328    /// # Returns
329    ///
330    /// - `bool` - True when the signal was alive and updated.
331    pub fn update<F>(&self, updater: F) -> bool
332    where
333        T: Clone,
334        F: FnOnce(&mut T),
335    {
336        let Some(mut current) = self.try_get_untracked() else {
337            return false;
338        };
339        updater(&mut current);
340        self.set(current)
341    }
342
343    /// Disposes this signal and reclaims its arena slot.
344    ///
345    /// # Arguments
346    ///
347    /// - `&Self` - Signal handle to dispose.
348    pub fn dispose(&self) {
349        let id: SignalId = self.id();
350        with_runtime(
351            |rt: &mut ReactiveRuntime| {
352                rt.dispose_signal(id);
353            },
354            (),
355        );
356    }
357}