1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use std::rc::Rc;
use yew::{Callback, Properties};
use super::handler::{GlobalHandler, Handler, Reduction, StorageHandler};
type Model<T> = <T as Handler>::Model;
pub trait Handle {
type Handler: Handler;
fn set_local_state(&mut self, state: Rc<Model<Self::Handler>>);
fn set_local_callback(&mut self, callback: Callback<Reduction<Model<Self::Handler>>>);
fn set_local(&mut self, other: &Self);
}
pub trait SharedState {
type Handle: Handle;
fn handle(&mut self) -> &mut Self::Handle;
}
#[derive(Default, Properties)]
pub struct StateHandle<T, H>
where
T: Default + Clone + 'static,
H: Handler,
{
#[prop_or_default]
state: Rc<T>,
#[prop_or_default]
callback: Callback<Reduction<T>>,
#[prop_or_default]
_mark: std::marker::PhantomData<H>,
}
impl<T, H> StateHandle<T, H>
where
T: Default + Clone + 'static,
H: Handler<Model = T>,
{
pub fn state(&self) -> &T {
&self.state
}
pub fn reduce(&self, f: impl FnOnce(&mut T) + 'static) {
self.callback.emit(Box::new(f))
}
pub fn reduce_callback<E: 'static>(
&self,
f: impl FnOnce(&mut T) + Copy + 'static,
) -> Callback<E>
where
T: 'static,
{
self.callback
.reform(move |_| Box::new(move |state| f(state)))
}
pub fn reduce_callback_with<E: 'static>(
&self,
f: impl FnOnce(E, &mut T) + Copy + 'static,
) -> Callback<E>
where
T: 'static,
{
self.callback
.reform(move |e| Box::new(move |state| f(e, state)))
}
}
impl<T, H> Clone for StateHandle<T, H>
where
T: Default + Clone + 'static,
H: Handler,
{
fn clone(&self) -> Self {
Self {
state: self.state.clone(),
callback: self.callback.clone(),
_mark: Default::default(),
}
}
}
impl<T, H> PartialEq for StateHandle<T, H>
where
T: Default + PartialEq + Clone + 'static,
H: Handler,
{
fn eq(&self, other: &Self) -> bool {
self.state == other.state && self.callback == other.callback
}
}
impl<T, H> Handle for StateHandle<T, H>
where
T: Default + Clone,
H: Handler<Model = T>,
{
type Handler = H;
fn set_local_state(&mut self, state: Rc<Model<Self::Handler>>) {
self.state = state;
}
fn set_local_callback(&mut self, callback: Callback<Reduction<Model<Self::Handler>>>) {
self.callback = callback;
}
fn set_local(&mut self, other: &Self) {
*self = other.clone();
}
}
impl<T, H> SharedState for StateHandle<T, H>
where
T: Default + Clone + 'static,
H: Handler<Model = T>,
{
type Handle = Self;
fn handle(&mut self) -> &mut Self::Handle {
self
}
}
pub type GlobalHandle<T> = StateHandle<T, GlobalHandler<T>>;
pub type StorageHandle<T> = StateHandle<T, StorageHandler<T>>;