Skip to main content

euv_core/reactive/state/
impl.rs

1use super::*;
2
3/// Copy handle semantics for `LocalState<T>`.
4impl<T> Copy for LocalState<T> where T: 'static {}
5
6/// Clone handle semantics for `LocalState<T>`.
7impl<T> Clone for LocalState<T>
8where
9    T: 'static,
10{
11    /// Copies the lightweight `LocalState<T>` handle.
12    ///
13    /// # Arguments
14    ///
15    /// - `&Self` - Source handle.
16    ///
17    /// # Returns
18    ///
19    /// - `Self` - Copied handle pointing to the same local state slot.
20    fn clone(&self) -> Self {
21        *self
22    }
23}
24
25/// Handle equality comparison for `LocalState<T>`.
26impl<T> PartialEq for LocalState<T>
27where
28    T: 'static,
29{
30    /// Compares two `LocalState<T>` handles by underlying signal identity.
31    ///
32    /// # Arguments
33    ///
34    /// - `&Self` - Left handle.
35    /// - `&Self` - Right handle.
36    ///
37    /// # Returns
38    ///
39    /// - `bool` - `true` when both handles reference the same state slot.
40    fn eq(&self, other: &Self) -> bool {
41        let Self { signal: lhs } = *self;
42        let Self { signal: rhs } = *other;
43        lhs == rhs
44    }
45}
46
47/// Full equality marker for `LocalState<T>`.
48impl<T> Eq for LocalState<T> where T: 'static {}
49
50/// Scoped local state creation, reading, writing, and change observation for `LocalState<T>`.
51impl<T> LocalState<T>
52where
53    T: 'static,
54{
55    /// Creates a new reactive `LocalState<T>` owned by the active component or page `Scope`.
56    ///
57    /// # Arguments
58    ///
59    /// - `T` - Initial local state value.
60    ///
61    /// # Returns
62    ///
63    /// - `Self` - Lightweight handle to the local reactive state.
64    #[must_use]
65    pub fn new(initial: T) -> Self {
66        Self {
67            signal: Signal::new(initial),
68        }
69    }
70
71    /// Returns the underlying `Signal<T>` handle for interoperability with `view!` and widgets.
72    ///
73    /// # Arguments
74    ///
75    /// - `&Self` - Local state handle.
76    ///
77    /// # Returns
78    ///
79    /// - `Signal<T>` - Underlying fine-grained reactive signal.
80    #[must_use]
81    pub fn signal(&self) -> Signal<T> {
82        let Self { signal } = *self;
83        signal
84    }
85
86    /// Reads the current value reactively and registers dependency tracking on the active observer.
87    ///
88    /// # Arguments
89    ///
90    /// - `&Self` - Local state handle.
91    ///
92    /// # Returns
93    ///
94    /// - `T` - Current cloned state value.
95    #[must_use]
96    pub fn get(&self) -> T
97    where
98        T: Clone + Default,
99    {
100        self.signal().get()
101    }
102
103    /// Reads the current value without tracking dependencies.
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Local state handle.
108    ///
109    /// # Returns
110    ///
111    /// - `T` - Current cloned state value.
112    #[must_use]
113    pub fn get_untracked(&self) -> T
114    where
115        T: Clone + Default,
116    {
117        self.signal().get_untracked()
118    }
119
120    /// Replaces the stored local state value and notifies active subscribers.
121    ///
122    /// # Arguments
123    ///
124    /// - `&Self` - Local state handle.
125    /// - `T` - Replacement value.
126    ///
127    /// # Returns
128    ///
129    /// - `bool` - `true` when the state slot is still alive.
130    pub fn set(&self, value: T) -> bool {
131        self.signal().set(value)
132    }
133
134    /// Replaces the stored value only when `value` differs from the current state.
135    ///
136    /// # Arguments
137    ///
138    /// - `&Self` - Local state handle.
139    /// - `T` - Candidate replacement value.
140    ///
141    /// # Returns
142    ///
143    /// - `bool` - `true` when the value changed and subscribers were notified.
144    pub fn set_if_changed(&self, value: T) -> bool
145    where
146        T: PartialEq,
147    {
148        self.signal().set_if_changed(value)
149    }
150
151    /// Mutates the stored local state in place via `updater`.
152    ///
153    /// # Arguments
154    ///
155    /// - `&Self` - Local state handle.
156    /// - `F` - In-place mutation closure.
157    ///
158    /// # Returns
159    ///
160    /// - `bool` - `true` when updated.
161    pub fn update<F>(&self, updater: F) -> bool
162    where
163        T: Clone,
164        F: FnOnce(&mut T),
165    {
166        self.signal().update(updater)
167    }
168
169    /// Subscribes a change watcher receiving `(&previous, &next)` whenever this local state mutates.
170    ///
171    /// # Arguments
172    ///
173    /// - `&Self` - Local state handle.
174    /// - `F` - Change observer invoked on subsequent mutations (skipped during `Scope::freeze()`, coalesced on `Scope::resume()`).
175    ///
176    /// # Returns
177    ///
178    /// - `Effect` - Scope-owned watcher effect handle.
179    #[must_use]
180    pub fn watch<F>(&self, mut handler: F) -> Effect
181    where
182        T: Clone,
183        F: FnMut(&T, &T) + 'static,
184    {
185        let sig: Signal<T> = self.signal();
186        let prev_cell: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
187        Effect::new(move || {
188            if let Some(next) = sig.try_get() {
189                let prev_opt: Option<T> = match prev_cell.try_borrow_mut() {
190                    Ok(mut guard) => guard.replace(next.clone()),
191                    Err(_) => None,
192                };
193                if let Some(prev) = prev_opt {
194                    handler(&prev, &next);
195                }
196            }
197        })
198    }
199}
200
201/// Global singleton state registration, access, mutation, and scope-aware change watching for `GlobalState`.
202impl GlobalState {
203    /// Registers or replaces a type-keyed root-lifetime global state value of type `T`.
204    ///
205    /// # Arguments
206    ///
207    /// - `T` - Initial or replacement global state value.
208    ///
209    /// # Returns
210    ///
211    /// - `Signal<T>` - Root-lifetime reactive signal bound to global type `T`.
212    pub fn provide<T>(initial: T) -> Signal<T>
213    where
214        T: 'static,
215    {
216        let (id, should_flush): (SignalId, bool) = with_runtime(
217            |rt: &mut ReactiveRuntime| rt.provide_global_state(initial),
218            (SignalId::default(), false),
219        );
220        if should_flush {
221            flush_effects();
222        }
223        Signal::from_raw_id(id)
224    }
225
226    /// Looks up a previously registered global state signal of type `T`.
227    ///
228    /// # Returns
229    ///
230    /// - `Option<Signal<T>>` - Registered global signal if present.
231    #[must_use]
232    pub fn use_state<T>() -> Option<Signal<T>>
233    where
234        T: 'static,
235    {
236        with_runtime(
237            |rt: &mut ReactiveRuntime| rt.lookup_global_state::<T>(),
238            None,
239        )
240        .map(Signal::from_raw_id)
241    }
242
243    /// Returns the registered global state signal of type `T`, lazily initializing it with `init` when absent.
244    ///
245    /// # Arguments
246    ///
247    /// - `F` - Lazy initializer invoked only when global state `T` has not yet been registered.
248    ///
249    /// # Returns
250    ///
251    /// - `Signal<T>` - Root-lifetime reactive signal for global state `T`.
252    #[must_use]
253    pub fn use_or_init<T, F>(init: F) -> Signal<T>
254    where
255        T: 'static,
256        F: FnOnce() -> T,
257    {
258        let id: SignalId = with_runtime(
259            |rt: &mut ReactiveRuntime| rt.get_or_init_global_state(init),
260            SignalId::default(),
261        );
262        Signal::from_raw_id(id)
263    }
264
265    /// Reactively reads the current value of global state `T`, tracking dependency on the active observer.
266    ///
267    /// # Returns
268    ///
269    /// - `Option<T>` - Current global state value if registered.
270    #[must_use]
271    pub fn get<T>() -> Option<T>
272    where
273        T: Clone + 'static,
274    {
275        Self::use_state::<T>().and_then(|sig: Signal<T>| sig.try_get())
276    }
277
278    /// Reads the current value of global state `T` without tracking reactive dependencies.
279    ///
280    /// # Returns
281    ///
282    /// - `Option<T>` - Current global state value if registered.
283    #[must_use]
284    pub fn get_untracked<T>() -> Option<T>
285    where
286        T: Clone + 'static,
287    {
288        Self::use_state::<T>().and_then(|sig: Signal<T>| sig.try_get_untracked())
289    }
290
291    /// Replaces the registered global state `T` and notifies all active observers.
292    ///
293    /// # Arguments
294    ///
295    /// - `T` - Replacement global state value.
296    ///
297    /// # Returns
298    ///
299    /// - `bool` - `true` when global state `T` existed and was updated.
300    pub fn set<T>(value: T) -> bool
301    where
302        T: 'static,
303    {
304        match Self::use_state::<T>() {
305            Some(sig) => sig.set(value),
306            None => false,
307        }
308    }
309
310    /// Replaces global state `T` only when `value` differs from the stored value.
311    ///
312    /// # Arguments
313    ///
314    /// - `T` - Candidate replacement value.
315    ///
316    /// # Returns
317    ///
318    /// - `bool` - `true` when the state changed.
319    pub fn set_if_changed<T>(value: T) -> bool
320    where
321        T: PartialEq + 'static,
322    {
323        match Self::use_state::<T>() {
324            Some(sig) => sig.set_if_changed(value),
325            None => false,
326        }
327    }
328
329    /// Mutates global state `T` in place via `updater`.
330    ///
331    /// # Arguments
332    ///
333    /// - `F` - Mutation closure.
334    ///
335    /// # Returns
336    ///
337    /// - `bool` - `true` when global state `T` existed and was mutated.
338    pub fn update<T, F>(updater: F) -> bool
339    where
340        T: Clone + 'static,
341        F: FnOnce(&mut T),
342    {
343        match Self::use_state::<T>() {
344            Some(sig) => sig.update(updater),
345            None => false,
346        }
347    }
348
349    /// Subscribes a scope-owned change watcher receiving `(&previous, &next)` whenever global state `T` updates.
350    ///
351    /// # Arguments
352    ///
353    /// - `F` - Change callback (automatically suspended when owning page is frozen and coalesced on resume).
354    ///
355    /// # Returns
356    ///
357    /// - `Option<Effect>` - Watcher effect handle if global state `T` is registered.
358    #[must_use]
359    pub fn watch<T, F>(mut handler: F) -> Option<Effect>
360    where
361        T: Clone + 'static,
362        F: FnMut(&T, &T) + 'static,
363    {
364        let sig: Signal<T> = Self::use_state::<T>()?;
365        let prev_cell: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
366        Some(Effect::new(move || {
367            if let Some(next) = sig.try_get() {
368                let prev_opt: Option<T> = match prev_cell.try_borrow_mut() {
369                    Ok(mut guard) => guard.replace(next.clone()),
370                    Err(_) => None,
371                };
372                if let Some(prev) = prev_opt {
373                    handler(&prev, &next);
374                }
375            }
376        }))
377    }
378
379    /// Registers or replaces a string-keyed global state channel storing `T`.
380    ///
381    /// # Arguments
382    ///
383    /// - `&str` - Channel name.
384    /// - `T` - Initial or replacement value.
385    ///
386    /// # Returns
387    ///
388    /// - `Signal<T>` - Root-lifetime signal handle.
389    pub fn provide_named<T>(name: &str, initial: T) -> Signal<T>
390    where
391        T: 'static,
392    {
393        let (id, should_flush): (SignalId, bool) = with_runtime(
394            |rt: &mut ReactiveRuntime| rt.provide_named_global_state(name, initial),
395            (SignalId::default(), false),
396        );
397        if should_flush {
398            flush_effects();
399        }
400        Signal::from_raw_id(id)
401    }
402
403    /// Looks up a string-keyed global state channel storing `T`.
404    ///
405    /// # Arguments
406    ///
407    /// - `&str` - Channel name.
408    ///
409    /// # Returns
410    ///
411    /// - `Option<Signal<T>>` - Registered signal handle if present.
412    #[must_use]
413    pub fn use_named<T>(name: &str) -> Option<Signal<T>>
414    where
415        T: 'static,
416    {
417        with_runtime(
418            |rt: &mut ReactiveRuntime| rt.lookup_named_global_state(name),
419            None,
420        )
421        .map(Signal::from_raw_id)
422    }
423
424    /// Subscribes a scope-owned watcher receiving `(&previous, &next)` for a string-keyed global state channel.
425    ///
426    /// # Arguments
427    ///
428    /// - `&str` - Channel name.
429    /// - `F` - Change callback.
430    ///
431    /// # Returns
432    ///
433    /// - `Option<Effect>` - Watcher effect handle if the named channel exists.
434    #[must_use]
435    pub fn watch_named<T, F>(name: &str, mut handler: F) -> Option<Effect>
436    where
437        T: Clone + 'static,
438        F: FnMut(&T, &T) + 'static,
439    {
440        let sig: Signal<T> = Self::use_named::<T>(name)?;
441        let prev_cell: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
442        Some(Effect::new(move || {
443            if let Some(next) = sig.try_get() {
444                let prev_opt: Option<T> = match prev_cell.try_borrow_mut() {
445                    Ok(mut guard) => guard.replace(next.clone()),
446                    Err(_) => None,
447                };
448                if let Some(prev) = prev_opt {
449                    handler(&prev, &next);
450                }
451            }
452        }))
453    }
454}