Skip to main content

orbital_base_components/signals/
component_ref.rs

1use leptos::{
2    logging::debug_warn,
3    prelude::{
4        ArcReadSignal, ArcRwSignal, ArcWriteSignal, Get, GetUntracked, RwSignal, Storage,
5        SyncStorage, Update,
6    },
7};
8
9/// Imperative handle to a child component instance (e.g. focus a button).
10#[derive(Clone, Copy)]
11pub struct ComponentRef<T, S = SyncStorage>(RwSignal<Option<T>, S>);
12
13impl<T> Default for ComponentRef<T>
14where
15    T: Send + Sync + 'static,
16{
17    fn default() -> Self {
18        Self(RwSignal::new(None))
19    }
20}
21
22impl<T> ComponentRef<T>
23where
24    T: Send + Sync + 'static,
25{
26    pub fn new() -> Self {
27        Self::default()
28    }
29}
30
31impl<T, S> ComponentRef<T, S>
32where
33    T: Clone + 'static,
34    S: Storage<ArcRwSignal<Option<T>>> + Storage<ArcReadSignal<Option<T>>>,
35{
36    pub fn get(&self) -> Option<T> {
37        self.0.get()
38    }
39
40    pub fn try_get(&self) -> Option<T> {
41        self.0.try_get().flatten()
42    }
43
44    pub fn get_untracked(&self) -> Option<T> {
45        self.0.get_untracked()
46    }
47
48    pub fn try_get_untracked(&self) -> Option<T> {
49        self.0.try_get_untracked().flatten()
50    }
51}
52
53impl<T, S> ComponentRef<T, S>
54where
55    T: 'static,
56    S: Storage<ArcRwSignal<Option<T>>> + Storage<ArcWriteSignal<Option<T>>>,
57{
58    pub fn load(&self, comp: T) {
59        self.0.update(|current| {
60            if current.is_some() {
61                debug_warn!(
62                    "You are setting a ComponentRef that has already been filled. \
63                     It's possible this is intentional."
64                );
65            }
66            *current = Some(comp);
67        });
68    }
69}