Skip to main content

gpui_hooks/hooks/
use_callback.rs

1use super::{Dependency, UseMemoHook};
2
3/// UseCallback hook - memoizes a function
4/// This is a type alias for documentation purposes
5pub struct UseCallback<R: 'static>(std::marker::PhantomData<R>);
6
7/// Trait for using callback hooks
8///
9/// This trait is automatically implemented for any type that implements `HasHooks`
10/// (which includes all types using `#[hook_element]`).
11pub trait UseCallbackHook: UseMemoHook {
12    /// Use a callback hook
13    /// Returns a memoized function
14    /// Note: deps parameter should be passed directly (array or tuple) to avoid temporary value lifetime issues
15    /// The factory closure is passed first, followed by the dependencies array.
16    fn use_callback<F, R, D>(&self, factory: F, deps: D) -> Box<dyn Fn() -> R>
17    where
18        R: 'static,
19        F: FnOnce() -> Box<dyn Fn() -> R>,
20        D: IntoIterator<Item: Dependency + Clone>,
21    {
22        // Use use_memo to memoize the factory function wrapped in Rc
23        // use_memo returns Box<dyn Fn() -> Rc<Box<dyn Fn() -> R>>>
24        let getter = self.use_memo(|| std::rc::Rc::new(factory()), deps);
25
26        // Return a closure that calls the memoized function
27        Box::new(move || {
28            let callback_rc = getter();
29            let callback = &**callback_rc; // Deref Rc<Box<dyn Fn() -> R>> to &dyn Fn() -> R
30            callback()
31        })
32    }
33}