Skip to main content

gpui_hooks/
hooks.rs

1pub mod use_callback;
2pub mod use_effect;
3pub mod use_memo;
4pub mod use_ref;
5pub mod use_state;
6
7pub use use_callback::{UseCallback, UseCallbackHook};
8pub use use_effect::{UseEffect, UseEffectHook};
9pub use use_memo::{UseMemo, UseMemoHook};
10pub use use_ref::{UseRef, UseRefHook};
11pub use use_state::{UseState, UseStateHook};
12
13use std::any::Any;
14use std::cell::RefCell;
15
16/// Trait for hooks that can be stored and managed
17pub trait Hook: Any {
18    fn as_any(&self) -> &dyn Any;
19    fn as_any_mut(&mut self) -> &mut dyn Any;
20}
21
22/// Trait for comparing dependencies
23pub trait Dependency: Any {
24    fn as_any(&self) -> &dyn Any;
25    fn equals(&self, other: &dyn Dependency) -> bool;
26    fn clone_boxed(&self) -> Box<dyn Dependency>;
27}
28
29impl<T: PartialEq + Clone + 'static> Dependency for T {
30    fn as_any(&self) -> &dyn Any {
31        self
32    }
33
34    fn equals(&self, other: &dyn Dependency) -> bool {
35        if let Some(other_t) = other.as_any().downcast_ref::<T>() {
36            self == other_t
37        } else {
38            false
39        }
40    }
41
42    fn clone_boxed(&self) -> Box<dyn Dependency> {
43        Box::new(self.clone())
44    }
45}
46
47impl Clone for Box<dyn Dependency> {
48    fn clone(&self) -> Self {
49        self.clone_boxed()
50    }
51}
52
53/// Internal trait for types that have hook storage
54/// This is implemented by HookedElement and used for blanket implementations
55pub trait HasHooks {
56    fn _hooks_storage(&self) -> &RefCell<Vec<Box<dyn Hook>>>;
57    fn _next_index(&self) -> usize;
58}
59
60// Blanket implementations for hook traits
61impl<T: HasHooks> UseStateHook for T {
62    fn _hooks_ref(&self) -> &RefCell<Vec<Box<dyn Hook>>> {
63        self._hooks_storage()
64    }
65
66    fn _next_hook_index(&self) -> usize {
67        self._next_index()
68    }
69}
70
71impl<T: HasHooks> UseEffectHook for T {
72    fn _hooks_ref(&self) -> &RefCell<Vec<Box<dyn Hook>>> {
73        self._hooks_storage()
74    }
75
76    fn _next_hook_index(&self) -> usize {
77        self._next_index()
78    }
79}
80
81impl<T: HasHooks> UseMemoHook for T {
82    fn _hooks_ref(&self) -> &RefCell<Vec<Box<dyn Hook>>> {
83        self._hooks_storage()
84    }
85
86    fn _next_hook_index(&self) -> usize {
87        self._next_index()
88    }
89}
90
91impl<T: HasHooks> UseRefHook for T {
92    fn _hooks_ref(&self) -> &RefCell<Vec<Box<dyn Hook>>> {
93        self._hooks_storage()
94    }
95
96    fn _next_hook_index(&self) -> usize {
97        self._next_index()
98    }
99}
100
101impl<T: HasHooks> UseCallbackHook for T {}