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 /// Returns the currently active `HookContext` for this thread.
147 ///
148 /// If no hook context has been set, creates and stores a default one in
149 /// the thread-local `CURRENT_HOOK_CONTEXT` cell so subsequent calls on
150 /// this thread return the same instance.
151 ///
152 /// # Returns
153 ///
154 /// - `HookContext` - The currently active hook context.
155 pub fn current() -> HookContext {
156 CURRENT_HOOK_CONTEXT.with(|slot: &RefCell<Option<HookContextRc>>| {
157 let existing: Option<HookContextRc> = slot.borrow().clone();
158 if let Some(hook_context_rc) = existing {
159 return HookContext::new(hook_context_rc);
160 }
161 let created: HookContextRc = Rc::new(RefCell::new(HookContextInner::default()));
162 *slot.borrow_mut() = Some(created.clone());
163 HookContext::new(created)
164 })
165 }
166
167 /// Runs a closure with the given `HookContext` set as the active context.
168 ///
169 /// Saves the previous context, sets the new one, executes the closure,
170 /// and restores the previous context afterward. The save/restore pair is
171 /// scoped to the current thread, so concurrent callers cannot restore each
172 /// other's context.
173 ///
174 /// # Arguments
175 ///
176 /// - `HookContext` - The hook context to set as active during closure execution.
177 /// - `F` - The closure to execute with the given context.
178 ///
179 /// # Returns
180 ///
181 /// - `R` - The result of the closure execution.
182 pub fn with<F, R>(context: HookContext, callback: F) -> R
183 where
184 F: FnOnce() -> R,
185 {
186 CURRENT_HOOK_CONTEXT.with(|slot: &RefCell<Option<HookContextRc>>| {
187 let previous: Option<HookContextRc> = slot.borrow_mut().take();
188 *slot.borrow_mut() = Some(context.get_inner().clone());
189 let result: R = callback();
190 *slot.borrow_mut() = previous;
191 result
192 })
193 }
194
195 /// Creates a new reactive signal with the given initial value.
196 ///
197 /// Uses the current `HookContext` to maintain signal identity across
198 /// re-renders. On the first call at a given hook index, the signal
199 /// is created with `init()` and stored. On subsequent re-renders,
200 /// the existing signal at that index is returned unchanged.
201 ///
202 /// # Arguments
203 ///
204 /// - `F` - A closure that computes the initial value of the signal.
205 ///
206 /// # Returns
207 ///
208 /// - `Signal<T>` - A reactive signal containing the initialized or existing value.
209 pub fn signal<T, F>(init: F) -> Signal<T>
210 where
211 T: Clone + PartialEq + 'static,
212 F: FnOnce() -> T,
213 {
214 let hook_context: HookContext = Self::current();
215 let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
216 return Signal::create(init());
217 };
218 let index: usize = inner.get_hook_index();
219 inner.set_hook_index(index + 1);
220 if index < inner.get_hooks().len()
221 && let Some(existing) = inner.get_hooks()[index].downcast_ref::<Signal<T>>()
222 {
223 return *existing;
224 }
225 let signal: Signal<T> = Signal::create(init());
226 inner
227 .get_mut_cleanups()
228 .push(Box::new(move || signal.deactivate()));
229 if index < inner.get_hooks().len() {
230 inner.get_mut_hooks()[index] = Box::new(signal);
231 } else {
232 inner.get_mut_hooks().push(Box::new(signal));
233 }
234 signal
235 }
236
237 /// Registers a cleanup callback that will be executed when the current
238 /// hook context is cleared (e.g., when a `match` arm switches).
239 ///
240 /// This is useful for cleaning up side effects like intervals, timeouts,
241 /// or subscriptions that are not automatically managed by signals.
242 ///
243 /// The cleanup callback is only registered once on the first render.
244 /// On subsequent re-renders at the same hook index, this is a no-op.
245 ///
246 /// # Arguments
247 ///
248 /// - `F` - The cleanup callback to execute on context teardown.
249 pub fn cleanup<F>(cleanup: F)
250 where
251 F: FnOnce() + 'static,
252 {
253 let hook_context: HookContext = Self::current();
254 let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
255 return;
256 };
257 let index: usize = inner.get_hook_index();
258 inner.set_hook_index(index + 1);
259 if index < inner.get_hooks().len() {
260 return;
261 }
262 inner.get_mut_cleanups().push(Box::new(cleanup));
263 inner.get_mut_hooks().push(Box::new(()));
264 }
265
266 /// Registers a `window.addEventListener` callback using event delegation,
267 /// automatically removed when the hook context is cleared.
268 ///
269 /// Uses the global window event proxy registry so that only one
270 /// `window.addEventListener` call is made per event name regardless of
271 /// how many components listen to the same event. On cleanup, only the
272 /// handler entry is removed from the proxy registry; the shared window
273 /// listener remains active for other consumers.
274 ///
275 /// The event listener is only registered once on the first render.
276 /// On subsequent re-renders at the same hook index, this is a no-op.
277 ///
278 /// # Arguments
279 ///
280 /// - `E` - The event name to listen for (e.g., "hashchange", "popstate", "resize").
281 /// - `F` - The callback to invoke when the event fires.
282 pub fn window_event<E, F>(event_name: E, callback: F)
283 where
284 E: AsRef<str>,
285 F: FnMut() + 'static,
286 {
287 let event_name: &str = event_name.as_ref();
288 let hook_context: HookContext = Self::current();
289 let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
290 return;
291 };
292 let index: usize = inner.get_hook_index();
293 inner.set_hook_index(index + 1);
294 if index < inner.get_hooks().len() {
295 return;
296 }
297 let event_name_owned: String = event_name.to_owned();
298 let handler_id: usize = Registry::register_window_event(event_name, callback);
299 inner.get_mut_cleanups().push(Box::new(move || {
300 Registry::unregister_window_event(&event_name_owned, handler_id);
301 }));
302 inner.get_mut_hooks().push(Box::new(()));
303 }
304
305 /// Creates a recurring interval that invokes the given closure at the
306 /// specified period, returning an `IntervalHandle` that is automatically
307 /// cleared when the hook context is cleared (i.e., when the component
308 /// unmounts or a `match` arm switches).
309 ///
310 /// Unlike calling `set_interval_with_callback_and_timeout_and_arguments_0`
311 /// + `Closure::forget()` manually, this hook ensures the interval is
312 /// properly cleaned up, preventing memory leaks and stale callbacks.
313 ///
314 /// The interval is only created once on the first render.
315 /// On subsequent re-renders at the same hook index, the existing handle
316 /// is returned unchanged.
317 ///
318 /// # Arguments
319 ///
320 /// - `i32` - The interval period in milliseconds.
321 /// - `F` - The closure to invoke on each interval tick.
322 ///
323 /// # Returns
324 ///
325 /// - `IntervalHandle` - A handle that can be used to cancel the interval early.
326 ///
327 /// # Panics
328 ///
329 /// Panics if `window()` is unavailable on the current platform.
330 pub fn interval<F>(millis: i32, callback: F) -> IntervalHandle
331 where
332 F: FnMut() + 'static,
333 {
334 let hook_context: HookContext = Self::current();
335 let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
336 return IntervalHandle::new(0);
337 };
338 let index: usize = inner.get_hook_index();
339 inner.set_hook_index(index + 1);
340 if index < inner.get_hooks().len()
341 && let Some(existing) = inner.get_hooks()[index].downcast_ref::<IntervalHandle>()
342 {
343 return *existing;
344 }
345 let closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(callback));
346 let Some(window) = window() else {
347 closure.forget();
348 return IntervalHandle::new(0);
349 };
350 let Ok(interval_id) = window.set_interval_with_callback_and_timeout_and_arguments_0(
351 closure.as_ref().unchecked_ref(),
352 millis,
353 ) else {
354 closure.forget();
355 return IntervalHandle::new(0);
356 };
357 closure.forget();
358 let handle: IntervalHandle = IntervalHandle::new(interval_id);
359 inner.get_mut_cleanups().push(Box::new(move || {
360 let Some(cleanup_window) = web_sys::window() else {
361 return;
362 };
363 cleanup_window.clear_interval_with_handle(interval_id);
364 }));
365 if index < inner.get_hooks().len() {
366 inner.get_mut_hooks()[index] = Box::new(handle);
367 } else {
368 inner.get_mut_hooks().push(Box::new(handle));
369 }
370 handle
371 }
372}
373
374/// Inherent implementation of [`HookContext`].
375impl HookContext {
376 /// Registers a hook value with the current hook context and returns
377 /// the existing instance if one was stored at this index from a
378 /// previous render cycle.
379 ///
380 /// This is the public extension point for custom hook types.
381 /// `ui` and downstream crates implement `use_form`, `use_i18n`, etc.
382 /// on top of this primitive instead of poking at the hook array
383 /// directly. `factory` runs once per hook slot on the first render;
384 /// subsequent renders in the same arm return the previously stored
385 /// instance.
386 ///
387 /// # Arguments
388 ///
389 /// - `F` - Constructor that produces a fresh value
390 /// of type `T` when the slot has never been written.
391 ///
392 /// # Returns
393 ///
394 /// - `T` - Either the previously-stored
395 /// value (cheap clone / copy) or a fresh one from
396 /// `factory`.
397 pub fn use_hook<T, F>(factory: F) -> T
398 where
399 F: FnOnce() -> T,
400 T: Clone + 'static,
401 {
402 let hook_context: HookContext = Self::current();
403 let Ok(mut inner) = hook_context.get_inner().try_borrow_mut() else {
404 return factory();
405 };
406 let index: usize = inner.get_hook_index();
407 inner.set_hook_index(index + 1);
408 if index < inner.get_hooks().len()
409 && let Some(existing) = inner.get_hooks()[index].downcast_ref::<T>()
410 {
411 return existing.clone();
412 }
413 let state: T = factory();
414 if index < inner.get_hooks().len() {
415 inner.get_mut_hooks()[index] = Box::new(state.clone());
416 } else {
417 inner.get_mut_hooks().push(Box::new(state.clone()));
418 }
419 state
420 }
421}