Skip to main content

euv_core/reactive/hook/
impl.rs

1use crate::*;
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_hook_index(&mut self) {
10        self.get_inner().borrow_mut().set_hook_index(0);
11    }
12
13    /// Notifies the hook context that a match arm is being entered.
14    ///
15    /// If the arm index has changed, all existing hooks and cleanups
16    /// are cleared and re-initialized for the new arm. If the arm
17    /// is unchanged, only the hook index is reset.
18    ///
19    /// # Arguments
20    ///
21    /// - `usize`: The index of the new match arm.
22    pub fn set_arm_changed(&mut self, changed: usize) {
23        let cleanups: Vec<Box<dyn FnOnce()>>;
24        {
25            let mut inner: RefMut<HookContextInner> = self.get_inner().borrow_mut();
26            if inner.get_arm_changed() == changed {
27                drop(inner);
28                self.reset_hook_index();
29                return;
30            }
31            cleanups = take(inner.get_mut_cleanups());
32            inner.get_mut_hooks().clear();
33            inner.set_arm_changed(changed);
34        }
35        for cleanup in cleanups {
36            cleanup();
37        }
38        self.reset_hook_index();
39    }
40}
41
42/// Clones the hook context, sharing the same inner state.
43impl Clone for HookContext {
44    fn clone(&self) -> Self {
45        HookContext::new(self.get_inner().clone())
46    }
47}
48
49/// Provides a default empty hook context.
50impl Default for HookContext {
51    fn default() -> Self {
52        HookContext::new(Rc::new(RefCell::new(HookContextInner::default())))
53    }
54}
55
56/// SAFETY: `HookContextCell` is only used in single-threaded WASM contexts.
57unsafe impl Sync for HookContextCell {}