Skip to main content

euv_core/reactive/state/
impl.rs

1use super::*;
2
3/// Copy handle semantics for `LocalState<T>`.
4impl<ValueType> Copy for LocalState<ValueType> where ValueType: 'static {}
5
6/// Clone handle semantics for `LocalState<T>`.
7impl<ValueType> Clone for LocalState<ValueType>
8where
9    ValueType: '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<ValueType> PartialEq for LocalState<ValueType>
27where
28    ValueType: '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<ValueType> Eq for LocalState<ValueType> where ValueType: 'static {}
49
50/// Scoped local state creation, reading, writing, and change observation for `LocalState<T>`.
51impl<ValueType> LocalState<ValueType>
52where
53    ValueType: 'static,
54{
55    /// Creates a new reactive `LocalState<T>` owned by the active component or page `Scope`.
56    ///
57    /// # Arguments
58    ///
59    /// - `ValueType` - 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: ValueType) -> 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<ValueType>` - Underlying fine-grained reactive signal.
80    #[must_use]
81    pub fn signal(&self) -> Signal<ValueType> {
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    /// - `ValueType` - Current cloned state value.
95    #[must_use]
96    pub fn get(&self) -> ValueType
97    where
98        ValueType: 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    /// - `ValueType` - Current cloned state value.
112    #[must_use]
113    pub fn get_untracked(&self) -> ValueType
114    where
115        ValueType: 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    /// - `ValueType` - Replacement value.
126    ///
127    /// # Returns
128    ///
129    /// - `bool` - `true` when the state slot is still alive.
130    pub fn set(&self, value: ValueType) -> 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    /// - `ValueType` - 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: ValueType) -> bool
145    where
146        ValueType: PartialEq,
147    {
148        self.signal().set_if_changed(value)
149    }
150
151    /// Reads the current value without tracking dependencies, returning `None` if disposed.
152    ///
153    /// # Arguments
154    ///
155    /// - `&Self` - Local state handle.
156    ///
157    /// # Returns
158    ///
159    /// - `Option<ValueType>` - Current cloned state value if alive.
160    #[must_use]
161    pub fn try_get_untracked(&self) -> Option<ValueType>
162    where
163        ValueType: Clone,
164    {
165        self.signal().try_get_untracked()
166    }
167
168    /// Subscribes a change watcher receiving `(&previous, &next)` whenever this local state mutates.
169    ///
170    /// # Arguments
171    ///
172    /// - `&Self` - Local state handle.
173    /// - `CallbackFn` - Change observer invoked on subsequent mutations (skipped during `Scope::freeze()`, coalesced on `Scope::resume()`).
174    ///
175    /// # Returns
176    ///
177    /// - `Effect` - Scope-owned watcher effect handle.
178    #[must_use]
179    pub fn watch<CallbackFn>(&self, mut handler: CallbackFn) -> Effect
180    where
181        ValueType: Clone,
182        CallbackFn: FnMut(&ValueType, &ValueType) + 'static,
183    {
184        let sig: Signal<ValueType> = self.signal();
185        let prev_cell: Rc<RefCell<Option<ValueType>>> = Rc::new(RefCell::new(None));
186        Effect::new(move || {
187            if let Some(next) = sig.try_get() {
188                let prev_opt: Option<ValueType> = match prev_cell.try_borrow_mut() {
189                    Ok(mut guard) => guard.replace(next.clone()),
190                    Err(_) => None,
191                };
192                if let Some(prev) = prev_opt {
193                    handler(&prev, &next);
194                }
195            }
196        })
197    }
198}
199
200/// Global singleton state registration, access, mutation, and scope-aware change watching for `GlobalState`.
201impl GlobalState {
202    /// Registers or replaces a type-keyed root-lifetime global state value of type `T`.
203    ///
204    /// # Arguments
205    ///
206    /// - `ValueType` - Initial or replacement global state value.
207    ///
208    /// # Returns
209    ///
210    /// - `Signal<ValueType>` - Root-lifetime reactive signal bound to global type `T`.
211    pub fn provide<ValueType>(initial: ValueType) -> Signal<ValueType>
212    where
213        ValueType: 'static,
214    {
215        let (id, should_flush): (SignalId, bool) = with_runtime(
216            |runtime_ref: &mut ReactiveRuntime| runtime_ref.provide_global_state(initial),
217            (SignalId::default(), false),
218        );
219        if should_flush {
220            flush_effects();
221        }
222        Signal::from_raw_id(id)
223    }
224
225    /// Looks up a previously registered global state signal of type `T`.
226    ///
227    /// # Returns
228    ///
229    /// - `Option<Signal<ValueType>>` - Registered global signal if present.
230    #[must_use]
231    pub fn use_state<ValueType>() -> Option<Signal<ValueType>>
232    where
233        ValueType: 'static,
234    {
235        with_runtime(
236            |runtime_ref: &mut ReactiveRuntime| runtime_ref.lookup_global_state::<ValueType>(),
237            None,
238        )
239        .map(Signal::from_raw_id)
240    }
241
242    /// Returns the registered global state signal of type `T`, lazily initializing it with `init` when absent.
243    ///
244    /// # Arguments
245    ///
246    /// - `CallbackFn` - Lazy initializer invoked only when global state `T` has not yet been registered.
247    ///
248    /// # Returns
249    ///
250    /// - `Signal<ValueType>` - Root-lifetime reactive signal for global state `T`.
251    #[must_use]
252    pub fn use_or_init<ValueType, CallbackFn>(init: CallbackFn) -> Signal<ValueType>
253    where
254        ValueType: 'static,
255        CallbackFn: FnOnce() -> ValueType,
256    {
257        let id: SignalId = with_runtime(
258            |runtime_ref: &mut ReactiveRuntime| runtime_ref.get_or_init_global_state(init),
259            SignalId::default(),
260        );
261        Signal::from_raw_id(id)
262    }
263
264    /// Reactively reads the current value of global state `T`, tracking dependency on the active observer.
265    ///
266    /// # Returns
267    ///
268    /// - `Option<ValueType>` - Current global state value if registered.
269    #[must_use]
270    pub fn get<ValueType>() -> Option<ValueType>
271    where
272        ValueType: Clone + 'static,
273    {
274        Self::use_state::<ValueType>().and_then(|sig: Signal<ValueType>| sig.try_get())
275    }
276
277    /// Reads the current value of global state `T` without tracking reactive dependencies.
278    ///
279    /// # Returns
280    ///
281    /// - `Option<ValueType>` - Current global state value if registered.
282    #[must_use]
283    pub fn get_untracked<ValueType>() -> Option<ValueType>
284    where
285        ValueType: Clone + 'static,
286    {
287        Self::use_state::<ValueType>().and_then(|sig: Signal<ValueType>| sig.try_get_untracked())
288    }
289
290    /// Replaces the registered global state `T` and notifies all active observers.
291    ///
292    /// # Arguments
293    ///
294    /// - `ValueType` - Replacement global state value.
295    ///
296    /// # Returns
297    ///
298    /// - `bool` - `true` when global state `T` existed and was updated.
299    pub fn set<ValueType>(value: ValueType) -> bool
300    where
301        ValueType: 'static,
302    {
303        match Self::use_state::<ValueType>() {
304            Some(sig) => sig.set(value),
305            None => false,
306        }
307    }
308
309    /// Replaces global state `T` only when `value` differs from the stored value.
310    ///
311    /// # Arguments
312    ///
313    /// - `ValueType` - Candidate replacement value.
314    ///
315    /// # Returns
316    ///
317    /// - `bool` - `true` when the state changed.
318    pub fn set_if_changed<ValueType>(value: ValueType) -> bool
319    where
320        ValueType: PartialEq + 'static,
321    {
322        match Self::use_state::<ValueType>() {
323            Some(sig) => sig.set_if_changed(value),
324            None => false,
325        }
326    }
327
328    /// Subscribes a scope-owned change watcher receiving `(&previous, &next)` whenever global state `T` updates.
329    ///
330    /// # Arguments
331    ///
332    /// - `CallbackFn` - Change callback (automatically suspended when owning page is frozen and coalesced on resume).
333    ///
334    /// # Returns
335    ///
336    /// - `Option<Effect>` - Watcher effect handle if global state `T` is registered.
337    #[must_use]
338    pub fn watch<ValueType, CallbackFn>(mut handler: CallbackFn) -> Option<Effect>
339    where
340        ValueType: Clone + 'static,
341        CallbackFn: FnMut(&ValueType, &ValueType) + 'static,
342    {
343        let sig: Signal<ValueType> = Self::use_state::<ValueType>()?;
344        let prev_cell: Rc<RefCell<Option<ValueType>>> = Rc::new(RefCell::new(None));
345        Some(Effect::new(move || {
346            if let Some(next) = sig.try_get() {
347                let prev_opt: Option<ValueType> = match prev_cell.try_borrow_mut() {
348                    Ok(mut guard) => guard.replace(next.clone()),
349                    Err(_) => None,
350                };
351                if let Some(prev) = prev_opt {
352                    handler(&prev, &next);
353                }
354            }
355        }))
356    }
357
358    /// Registers or replaces a string-keyed global state channel storing `T`.
359    ///
360    /// # Arguments
361    ///
362    /// - `&str` - Channel name.
363    /// - `ValueType` - Initial or replacement value.
364    ///
365    /// # Returns
366    ///
367    /// - `Signal<ValueType>` - Root-lifetime signal handle.
368    pub fn provide_named<ValueType>(name: &str, initial: ValueType) -> Signal<ValueType>
369    where
370        ValueType: 'static,
371    {
372        let (id, should_flush): (SignalId, bool) = with_runtime(
373            |runtime_ref: &mut ReactiveRuntime| {
374                runtime_ref.provide_named_global_state(name, initial)
375            },
376            (SignalId::default(), false),
377        );
378        if should_flush {
379            flush_effects();
380        }
381        Signal::from_raw_id(id)
382    }
383
384    /// Looks up a string-keyed global state channel storing `T`.
385    ///
386    /// # Arguments
387    ///
388    /// - `&str` - Channel name.
389    ///
390    /// # Returns
391    ///
392    /// - `Option<Signal<ValueType>>` - Registered signal handle if present.
393    #[must_use]
394    pub fn use_named<ValueType>(name: &str) -> Option<Signal<ValueType>>
395    where
396        ValueType: 'static,
397    {
398        with_runtime(
399            |runtime_ref: &mut ReactiveRuntime| runtime_ref.lookup_named_global_state(name),
400            None,
401        )
402        .map(Signal::from_raw_id)
403    }
404
405    /// Subscribes a scope-owned watcher receiving `(&previous, &next)` for a string-keyed global state channel.
406    ///
407    /// # Arguments
408    ///
409    /// - `&str` - Channel name.
410    /// - `CallbackFn` - Change callback.
411    ///
412    /// # Returns
413    ///
414    /// - `Option<Effect>` - Watcher effect handle if the named channel exists.
415    #[must_use]
416    pub fn watch_named<ValueType, CallbackFn>(name: &str, mut handler: CallbackFn) -> Option<Effect>
417    where
418        ValueType: Clone + 'static,
419        CallbackFn: FnMut(&ValueType, &ValueType) + 'static,
420    {
421        let sig: Signal<ValueType> = Self::use_named::<ValueType>(name)?;
422        let prev_cell: Rc<RefCell<Option<ValueType>>> = Rc::new(RefCell::new(None));
423        Some(Effect::new(move || {
424            if let Some(next) = sig.try_get() {
425                let prev_opt: Option<ValueType> = match prev_cell.try_borrow_mut() {
426                    Ok(mut guard) => guard.replace(next.clone()),
427                    Err(_) => None,
428                };
429                if let Some(prev) = prev_opt {
430                    handler(&prev, &next);
431                }
432            }
433        }))
434    }
435}