Skip to main content

euv_core/reactive/hook/
impl.rs

1use super::*;
2
3/// Implementation of hook context lifecycle and hook index management.
4impl HookContext {
5    /// Resets the hook index for a new render cycle.
6    ///
7    /// Sets the internal hook index back to zero so that subsequent
8    /// `use_signal` calls start indexing from the beginning of the hook list.
9    pub fn reset_index(&mut self) {
10        if let Ok(mut inner) = self.get_inner().try_borrow_mut() {
11            inner.set_hook_index(0);
12        }
13    }
14
15    /// Notifies the hook context that a match arm is being entered.
16    ///
17    /// If the arm index has changed, all existing hooks and cleanups
18    /// are cleared and re-initialized for the new arm. If the arm
19    /// is unchanged, only the hook index is reset.
20    ///
21    /// # Arguments
22    ///
23    /// - `usize` - The index of the new match arm.
24    pub fn switch_arm(&mut self, changed: usize) {
25        let cleanups: Vec<Box<dyn FnOnce()>>;
26        {
27            let Ok(mut inner) = self.get_inner().try_borrow_mut() else {
28                return;
29            };
30            if inner.get_arm_changed() == changed {
31                drop(inner);
32                self.reset_index();
33                return;
34            }
35            cleanups = take(inner.get_mut_cleanups());
36            inner.get_mut_hooks().clear();
37            inner.set_arm_changed(changed);
38        }
39        for cleanup in cleanups {
40            cleanup();
41        }
42        self.reset_index();
43    }
44
45    /// Creates or reuses a `NodeRef<T>` at the current hook index.
46    ///
47    /// On the first call at a given hook index, a fresh empty `NodeRef`
48    /// is stored. On subsequent re-renders the same instance is returned,
49    /// so a ref cloned into a closure stays attached to the live DOM
50    /// element across renders.
51    ///
52    /// The element type `T` is a phantom marker only — we downcast the
53    /// stored `Box<dyn Any>` back to `NodeRef<T>` using the same pattern
54    /// as `Signal::signal` above. Note that two calls at the same hook
55    /// index with different `T` would still match (both are `NodeRef<...>`)
56    /// because the `downcast_ref` ignores the phantom parameter.
57    ///
58    /// # Returns
59    ///
60    /// - `NodeRef<T>` - A `NodeRef<T>` value.
61    pub fn noderef<T>() -> NodeRef<T>
62    where
63        T: ?Sized + 'static,
64    {
65        let hook_context: HookContext = Self::current();
66        let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
67            // Borrow failed (renderer re-entered); fall back to a fresh
68            // empty ref so the caller still gets a usable handle.
69            return NodeRef::new();
70        };
71        let index: usize = inner.get_hook_index();
72        inner.set_hook_index(index + 1);
73        if index < inner.get_hooks().len() {
74            // Re-render path: try to reuse the existing NodeRef stored at
75            // this hook index. If a different hook type was at this slot
76            // (e.g. user swapped `use_signal` for `use_node_ref`), replace
77            // it with a fresh ref rather than panicking.
78            if let Some(existing) = inner.get_hooks()[index].downcast_ref::<NodeRef<T>>() {
79                return existing.clone();
80            }
81            let new_ref: NodeRef<T> = NodeRef::new();
82            inner.get_mut_hooks()[index] = Box::new(new_ref.clone());
83            return new_ref;
84        }
85        let new_ref: NodeRef<T> = NodeRef::new();
86        inner.get_mut_hooks().push(Box::new(new_ref.clone()));
87        new_ref
88    }
89}
90
91/// Clones the hook context, sharing the same inner state.
92///
93/// All clones share the same underlying `Rc<RefCell<HookContextInner>>`,
94/// so modifications through one clone are visible through all others.
95///
96/// # Returns
97///
98/// - `Self` - A new `HookContext` sharing the same inner state.
99impl Clone for HookContext {
100    /// Clones the [`HookContext`] by reusing shared, cheap-to-clone state where possible.
101    fn clone(&self) -> Self {
102        Self::new(self.get_inner().clone())
103    }
104}
105
106/// Provides a default empty hook context.
107///
108/// Creates a fresh `Rc<RefCell<HookContextInner>>` with default values
109/// (empty hook list, zero hook index, empty cleanup list).
110///
111/// # Returns
112///
113/// - `Self` - A new `HookContext` with default inner state.
114impl Default for HookContext {
115    /// Constructs a default [`HookContext`] value.
116    fn default() -> Self {
117        Self::new(Rc::new(RefCell::new(HookContextInner::default())))
118    }
119}
120
121/// Implementation of interval handle lifecycle management.
122impl IntervalHandle {
123    /// Cancels the associated browser interval timer.
124    ///
125    /// Calls `window.clearInterval` with the stored interval ID.
126    /// After calling this method the interval callback will no longer fire.
127    ///
128    /// # Panics
129    ///
130    /// Panics if `window()` is unavailable on the current platform.
131    pub fn clear(&self) {
132        if let Some(cleanup_window) = web_sys::window() {
133            cleanup_window.clear_interval_with_handle(self.get_interval_id());
134        }
135    }
136}
137
138/// Associated functions for hook context management.
139///
140/// These are crate-internal static methods for managing the active hook
141/// context, creating signals, registering cleanups, and scheduling intervals.
142impl HookContext {
143    /// Returns a shared reference to the current hook context global state.
144    ///
145    /// SAFETY: Must only be called from the main thread (WASM single-threaded context).
146    #[allow(static_mut_refs)]
147    fn try_get_current() -> &'static Option<HookContextRc> {
148        unsafe { &*CURRENT_HOOK_CONTEXT.get_0().get() }
149    }
150
151    /// Returns a mutable reference to the current hook context global state.
152    ///
153    /// SAFETY: Must only be called from the main thread (WASM single-threaded context).
154    #[allow(static_mut_refs)]
155    fn try_get_mut_current() -> &'static mut Option<HookContextRc> {
156        unsafe { &mut *CURRENT_HOOK_CONTEXT.get_0().get() }
157    }
158
159    /// Returns the currently active `HookContext`.
160    ///
161    /// If no hook context has been set, creates and stores a default one
162    /// in the global `CURRENT_HOOK_CONTEXT` cell so subsequent calls
163    /// return the same instance.
164    ///
165    /// # Returns
166    ///
167    /// - `HookContext` - The currently active hook context.
168    pub fn current() -> HookContext {
169        match Self::try_get_current() {
170            Some(hook_context_rc) => HookContext::new(hook_context_rc.clone()),
171            None => {
172                let rc: HookContextRc = Rc::new(RefCell::new(HookContextInner::default()));
173                *Self::try_get_mut_current() = Some(rc.clone());
174                HookContext::new(rc)
175            }
176        }
177    }
178
179    /// Runs a closure with the given `HookContext` set as the active context.
180    ///
181    /// Saves the previous context, sets the new one, executes the closure,
182    /// and restores the previous context afterward.
183    ///
184    /// # Arguments
185    ///
186    /// - `HookContext` - The hook context to set as active during closure execution.
187    /// - `F: FnOnce() -> R` - The closure to execute with the given context.
188    ///
189    /// # Returns
190    ///
191    /// - `R` - The result of the closure execution.
192    pub fn with<F, R>(context: HookContext, callback: F) -> R
193    where
194        F: FnOnce() -> R,
195    {
196        let previous: Option<HookContextRc> = Self::try_get_mut_current().take();
197        *Self::try_get_mut_current() = Some(context.get_inner().clone());
198        let result: R = callback();
199        *Self::try_get_mut_current() = previous;
200        result
201    }
202
203    /// Creates a new reactive signal with the given initial value.
204    ///
205    /// Uses the current `HookContext` to maintain signal identity across
206    /// re-renders. On the first call at a given hook index, the signal
207    /// is created with `init()` and stored. On subsequent re-renders,
208    /// the existing signal at that index is returned unchanged.
209    ///
210    /// # Arguments
211    ///
212    /// - `FnOnce() -> T` - A closure that computes the initial value of the signal.
213    ///
214    /// # Returns
215    ///
216    /// - `Signal<T>` - A reactive signal containing the initialized or existing value.
217    pub fn signal<T, F>(init: F) -> Signal<T>
218    where
219        T: Clone + PartialEq + 'static,
220        F: FnOnce() -> T,
221    {
222        let hook_context: HookContext = Self::current();
223        let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
224            return Signal::create(init());
225        };
226        let index: usize = inner.get_hook_index();
227        inner.set_hook_index(index + 1);
228        if index < inner.get_hooks().len()
229            && let Some(existing) = inner.get_hooks()[index].downcast_ref::<Signal<T>>()
230        {
231            return *existing;
232        }
233        let signal: Signal<T> = Signal::create(init());
234        inner
235            .get_mut_cleanups()
236            .push(Box::new(move || signal.deactivate()));
237        if index < inner.get_hooks().len() {
238            inner.get_mut_hooks()[index] = Box::new(signal);
239        } else {
240            inner.get_mut_hooks().push(Box::new(signal));
241        }
242        signal
243    }
244
245    /// Registers a cleanup callback that will be executed when the current
246    /// hook context is cleared (e.g., when a `match` arm switches).
247    ///
248    /// This is useful for cleaning up side effects like intervals, timeouts,
249    /// or subscriptions that are not automatically managed by signals.
250    ///
251    /// The cleanup callback is only registered once on the first render.
252    /// On subsequent re-renders at the same hook index, this is a no-op.
253    ///
254    /// # Arguments
255    ///
256    /// - `FnOnce() + 'static` - The cleanup callback to execute on context teardown.
257    pub fn cleanup<F>(cleanup: F)
258    where
259        F: FnOnce() + 'static,
260    {
261        let hook_context: HookContext = Self::current();
262        let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
263            return;
264        };
265        let index: usize = inner.get_hook_index();
266        inner.set_hook_index(index + 1);
267        if index < inner.get_hooks().len() {
268            return;
269        }
270        inner.get_mut_cleanups().push(Box::new(cleanup));
271        inner.get_mut_hooks().push(Box::new(()));
272    }
273
274    /// Registers a `window.addEventListener` callback using event delegation,
275    /// automatically removed when the hook context is cleared.
276    ///
277    /// Uses the global window event proxy registry so that only one
278    /// `window.addEventListener` call is made per event name regardless of
279    /// how many components listen to the same event. On cleanup, only the
280    /// handler entry is removed from the proxy registry; the shared window
281    /// listener remains active for other consumers.
282    ///
283    /// The event listener is only registered once on the first render.
284    /// On subsequent re-renders at the same hook index, this is a no-op.
285    ///
286    /// # Arguments
287    ///
288    /// - `E: AsRef<str>` - The event name to listen for (e.g., "hashchange", "popstate", "resize").
289    /// - `FnMut() + 'static` - The callback to invoke when the event fires.
290    pub fn window_event<E, F>(event_name: E, callback: F)
291    where
292        E: AsRef<str>,
293        F: FnMut() + 'static,
294    {
295        let event_name: &str = event_name.as_ref();
296        let hook_context: HookContext = Self::current();
297        let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
298            return;
299        };
300        let index: usize = inner.get_hook_index();
301        inner.set_hook_index(index + 1);
302        if index < inner.get_hooks().len() {
303            return;
304        }
305        let event_name_owned: String = event_name.to_owned();
306        let handler_id: usize = Registry::register_window_event(event_name, callback);
307        inner.get_mut_cleanups().push(Box::new(move || {
308            Registry::unregister_window_event(&event_name_owned, handler_id);
309        }));
310        inner.get_mut_hooks().push(Box::new(()));
311    }
312
313    /// Creates a recurring interval that invokes the given closure at the
314    /// specified period, returning an `IntervalHandle` that is automatically
315    /// cleared when the hook context is cleared (i.e., when the component
316    /// unmounts or a `match` arm switches).
317    ///
318    /// Unlike calling `set_interval_with_callback_and_timeout_and_arguments_0`
319    /// + `Closure::forget()` manually, this hook ensures the interval is
320    ///   properly cleaned up, preventing memory leaks and stale callbacks.
321    ///
322    /// The interval is only created once on the first render.
323    /// On subsequent re-renders at the same hook index, the existing handle
324    /// is returned unchanged.
325    ///
326    /// # Arguments
327    ///
328    /// - `i32` - The interval period in milliseconds.
329    /// - `FnMut() + 'static` - The closure to invoke on each interval tick.
330    ///
331    /// # Returns
332    ///
333    /// - `IntervalHandle` - A handle that can be used to cancel the interval early.
334    ///
335    /// # Panics
336    ///
337    /// Panics if `window()` is unavailable on the current platform.
338    pub fn interval<F>(millis: i32, callback: F) -> IntervalHandle
339    where
340        F: FnMut() + 'static,
341    {
342        let hook_context: HookContext = Self::current();
343        let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
344            return IntervalHandle::new(0);
345        };
346        let index: usize = inner.get_hook_index();
347        inner.set_hook_index(index + 1);
348        if index < inner.get_hooks().len()
349            && let Some(existing) = inner.get_hooks()[index].downcast_ref::<IntervalHandle>()
350        {
351            return *existing;
352        }
353        let closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(callback));
354        let Some(window) = window() else {
355            closure.forget();
356            return IntervalHandle::new(0);
357        };
358        let Ok(interval_id) = window.set_interval_with_callback_and_timeout_and_arguments_0(
359            closure.as_ref().unchecked_ref(),
360            millis,
361        ) else {
362            closure.forget();
363            return IntervalHandle::new(0);
364        };
365        closure.forget();
366        let handle: IntervalHandle = IntervalHandle::new(interval_id);
367        inner.get_mut_cleanups().push(Box::new(move || {
368            let Some(cleanup_window) = web_sys::window() else {
369                return;
370            };
371            cleanup_window.clear_interval_with_handle(interval_id);
372        }));
373        if index < inner.get_hooks().len() {
374            inner.get_mut_hooks()[index] = Box::new(handle);
375        } else {
376            inner.get_mut_hooks().push(Box::new(handle));
377        }
378        handle
379    }
380}
381
382/// Inherent implementation of [`HookContext`].
383impl HookContext {
384    /// Registers a hook value with the current hook context and returns
385    /// the existing instance if one was stored at this index from a
386    /// previous render cycle.
387    ///
388    /// This is the public extension point for custom hook types.
389    /// `ui` and downstream crates implement `use_form`, `use_i18n`, etc.
390    /// on top of this primitive instead of poking at the hook array
391    /// directly. `factory` runs once per hook slot on the first render;
392    /// subsequent renders in the same arm return the previously stored
393    /// instance.
394    ///
395    /// # Arguments
396    ///
397    /// - `F: FnOnce() -> T` - Constructor that produces a fresh value
398    ///   of type `T` when the slot has never been written.
399    ///
400    /// # Returns
401    ///
402    /// - `T: Clone + 'static` - Either the previously-stored
403    ///   value (cheap clone / copy) or a fresh one from
404    ///   `factory`.
405    pub fn use_hook<T, F>(factory: F) -> T
406    where
407        F: FnOnce() -> T,
408        T: Clone + 'static,
409    {
410        let hook_context: HookContext = Self::current();
411        let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
412            return factory();
413        };
414        let index: usize = inner.get_hook_index();
415        inner.set_hook_index(index + 1);
416        if index < inner.get_hooks().len()
417            && let Some(existing) = inner.get_hooks()[index].downcast_ref::<T>()
418        {
419            return existing.clone();
420        }
421        let state: T = factory();
422        if index < inner.get_hooks().len() {
423            inner.get_mut_hooks()[index] = Box::new(state.clone());
424        } else {
425            inner.get_mut_hooks().push(Box::new(state.clone()));
426        }
427        state
428    }
429}