Skip to main content

lgui_store/store/
hooks.rs

1use std::{
2    hash::{Hash, Hasher},
3    sync::Arc,
4};
5
6use crate::core::{Observable, ObservableListener, RenderCx, UiEffect};
7use crate::StoreApplicationExt as _;
8
9use super::{
10    StoreDefinition, StoreNotification, StoreObserver, StoreRuntime, StoreUnit, Subscription,
11};
12
13#[derive(Clone)]
14pub struct StoreContext {
15    runtime: Arc<StoreRuntime>,
16}
17
18impl StoreContext {
19    pub fn new(runtime: Arc<StoreRuntime>) -> Self {
20        Self { runtime }
21    }
22
23    pub fn runtime(&self) -> &Arc<StoreRuntime> {
24        &self.runtime
25    }
26}
27
28impl PartialEq for StoreContext {
29    fn eq(&self, other: &Self) -> bool {
30        Arc::ptr_eq(&self.runtime, &other.runtime)
31    }
32}
33
34pub struct StoreAction<T> {
35    store: StoreDefinition<T>,
36    mutate: fn(&mut T),
37}
38
39impl<T> Clone for StoreAction<T> {
40    fn clone(&self) -> Self {
41        *self
42    }
43}
44
45impl<T> Copy for StoreAction<T> {}
46
47pub struct StoreActionWith<T, A> {
48    store: StoreDefinition<T>,
49    mutate: fn(&mut T, A),
50}
51
52impl<T, A> Clone for StoreActionWith<T, A> {
53    fn clone(&self) -> Self {
54        *self
55    }
56}
57
58impl<T, A> Copy for StoreActionWith<T, A> {}
59
60pub struct BoundStoreAction<T> {
61    runtime: Arc<StoreRuntime>,
62    action: StoreAction<T>,
63}
64
65pub struct BoundStoreActionWith<T, A> {
66    runtime: Arc<StoreRuntime>,
67    action: StoreActionWith<T, A>,
68}
69
70impl<T> Clone for BoundStoreAction<T> {
71    fn clone(&self) -> Self {
72        Self {
73            runtime: Arc::clone(&self.runtime),
74            action: self.action,
75        }
76    }
77}
78
79impl<T, A> Clone for BoundStoreActionWith<T, A> {
80    fn clone(&self) -> Self {
81        Self {
82            runtime: Arc::clone(&self.runtime),
83            action: self.action,
84        }
85    }
86}
87
88impl<T> StoreDefinition<T>
89where
90    T: Send + Sync + 'static,
91{
92    pub fn select<S, F>(self, cx: &mut RenderCx<'_, '_>, selector: F) -> S
93    where
94        S: Clone + PartialEq + Send + 'static,
95        F: Fn(&T) -> S + Send + Sync + 'static,
96    {
97        let runtime = store_runtime(cx);
98        use_definition(cx, runtime, self, selector)
99    }
100
101    pub const fn action(self, mutate: fn(&mut T)) -> StoreAction<T> {
102        StoreAction {
103            store: self,
104            mutate,
105        }
106    }
107
108    pub const fn action_with<A>(self, mutate: fn(&mut T, A)) -> StoreActionWith<T, A> {
109        StoreActionWith {
110            store: self,
111            mutate,
112        }
113    }
114}
115
116impl<T> StoreAction<T>
117where
118    T: Send + Sync + 'static,
119{
120    pub fn bind(self, cx: &mut RenderCx<'_, '_>) -> BoundStoreAction<T> {
121        let runtime = store_runtime(cx);
122        BoundStoreAction {
123            runtime,
124            action: self,
125        }
126    }
127
128    pub fn call_in(self, runtime: &StoreRuntime) {
129        runtime.update_defined(self.store, "store.action", self.mutate)
130    }
131}
132
133impl<T, A> StoreActionWith<T, A>
134where
135    T: Send + Sync + 'static,
136{
137    pub fn bind(self, cx: &mut RenderCx<'_, '_>) -> BoundStoreActionWith<T, A> {
138        let runtime = store_runtime(cx);
139        BoundStoreActionWith {
140            runtime,
141            action: self,
142        }
143    }
144
145    pub fn call_in(self, runtime: &StoreRuntime, argument: A) {
146        runtime.update_defined(self.store, "store.action", move |store| {
147            (self.mutate)(store, argument)
148        })
149    }
150}
151
152impl<T> BoundStoreAction<T>
153where
154    T: Send + Sync + 'static,
155{
156    pub fn call(&self) {
157        self.action.call_in(&self.runtime)
158    }
159}
160
161impl<T, A> BoundStoreActionWith<T, A>
162where
163    T: Send + Sync + 'static,
164{
165    pub fn call(&self, argument: A) {
166        self.action.call_in(&self.runtime, argument)
167    }
168}
169
170pub trait StoreHooks {
171    fn use_store<T, S, F>(&mut self, selector: F) -> S
172    where
173        T: StoreUnit,
174        S: Clone + PartialEq + Send + 'static,
175        F: Fn(&T) -> S + Send + Sync + 'static;
176}
177
178impl StoreHooks for RenderCx<'_, '_> {
179    fn use_store<T, S, F>(&mut self, selector: F) -> S
180    where
181        T: StoreUnit,
182        S: Clone + PartialEq + Send + 'static,
183        F: Fn(&T) -> S + Send + Sync + 'static,
184    {
185        let runtime = store_runtime(self);
186        use_unit(self, runtime, selector)
187    }
188}
189
190fn store_runtime(cx: &mut RenderCx<'_, '_>) -> Arc<StoreRuntime> {
191    cx.try_use_context::<StoreContext>()
192        .map(|context| context.runtime)
193        .unwrap_or_else(|| cx.application().stores())
194}
195
196struct CallbackObserver {
197    listener: ObservableListener,
198}
199
200impl StoreObserver for CallbackObserver {
201    fn on_store_notification(&self, _notification: &StoreNotification) {
202        (self.listener)();
203    }
204}
205
206fn use_unit<T, S, F>(cx: &mut RenderCx<'_, '_>, runtime: Arc<StoreRuntime>, selector: F) -> S
207where
208    T: StoreUnit,
209    S: Clone + PartialEq + Send + 'static,
210    F: Fn(&T) -> S + Send + Sync + 'static,
211{
212    let read_runtime = Arc::clone(&runtime);
213    let subscribe_runtime = runtime;
214    let selector = Arc::new(selector);
215    let source = Observable::new(
216        observable_id::<T, F>(),
217        move || read_runtime.read::<T, _>(|store| selector(store)),
218        move |listener| subscribe::<T>(Arc::clone(&subscribe_runtime), listener),
219    );
220    cx.use_observable(source, clone_selected::<S>)
221}
222
223fn use_definition<T, S, F>(
224    cx: &mut RenderCx<'_, '_>,
225    runtime: Arc<StoreRuntime>,
226    store: StoreDefinition<T>,
227    selector: F,
228) -> S
229where
230    T: Send + Sync + 'static,
231    S: Clone + PartialEq + Send + 'static,
232    F: Fn(&T) -> S + Send + Sync + 'static,
233{
234    let read_runtime = Arc::clone(&runtime);
235    let subscribe_runtime = runtime;
236    let selector = Arc::new(selector);
237    let source = Observable::new(
238        observable_id::<T, F>(),
239        move || read_runtime.read_defined(store, |value| selector(value)),
240        move |listener| subscribe_definition(Arc::clone(&subscribe_runtime), store, listener),
241    );
242    cx.use_observable(source, clone_selected::<S>)
243}
244
245fn subscribe<T>(runtime: Arc<StoreRuntime>, listener: ObservableListener) -> UiEffect
246where
247    T: StoreUnit,
248{
249    let observer = Arc::new(CallbackObserver { listener });
250    let token = runtime.subscribe(Subscription::store(T::KEY), observer);
251    Box::new(move || {
252        runtime.unsubscribe(token);
253    })
254}
255
256fn subscribe_definition<T>(
257    runtime: Arc<StoreRuntime>,
258    store: StoreDefinition<T>,
259    listener: ObservableListener,
260) -> UiEffect
261where
262    T: Send + Sync + 'static,
263{
264    let observer = Arc::new(CallbackObserver { listener });
265    let token = runtime.subscribe(Subscription::store(store.key()), observer);
266    Box::new(move || {
267        runtime.unsubscribe(token);
268    })
269}
270
271fn observable_id<T: 'static, F: 'static>() -> u64 {
272    let mut hasher = std::collections::hash_map::DefaultHasher::new();
273    std::any::TypeId::of::<T>().hash(&mut hasher);
274    std::any::TypeId::of::<F>().hash(&mut hasher);
275    hasher.finish()
276}
277
278fn clone_selected<T: Clone>(value: &T) -> T {
279    value.clone()
280}
281
282#[cfg(test)]
283#[path = "hooks_test.rs"]
284mod tests;