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