-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
lib.rs
349 lines (319 loc) · 10.9 KB
/
lib.rs
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use std::borrow::Borrow;
use std::cell::RefCell;
use std::ops::DerefMut;
use std::rc::Rc;
use yew::{Component, ComponentLink, Html, Properties};
thread_local! {
static CURRENT_HOOK: RefCell<Option<HookState>> = RefCell::new(None);
}
pub trait Hook {
fn tear_down(&mut self) {}
}
type ProcessMessage = Rc<dyn Fn(Box<dyn FnOnce() -> bool>)>;
struct HookState {
counter: usize,
process_message: ProcessMessage,
hooks: Vec<Rc<RefCell<dyn std::any::Any>>>,
destroy_listeners: Vec<Box<dyn FnOnce()>>,
}
pub trait FunctionProvider {
type TProps: Properties + PartialEq;
fn run(props: &Self::TProps) -> Html;
}
pub struct FunctionComponent<T: FunctionProvider> {
_never: std::marker::PhantomData<T>,
props: T::TProps,
hook_state: RefCell<Option<HookState>>,
}
impl<T: 'static> Component for FunctionComponent<T>
where
T: FunctionProvider,
{
type Message = Box<dyn FnOnce() -> bool>;
type Properties = T::TProps;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
FunctionComponent {
_never: std::marker::PhantomData::default(),
props,
hook_state: RefCell::new(Some(HookState {
counter: 0,
process_message: Rc::new(move |msg| link.send_message(msg)),
hooks: vec![],
destroy_listeners: vec![],
})),
}
}
fn update(&mut self, msg: Self::Message) -> bool {
msg()
}
fn change(&mut self, props: Self::Properties) -> bool {
let mut props = props;
std::mem::swap(&mut self.props, &mut props);
props != self.props
}
//noinspection DuplicatedCode
fn view(&self) -> Html {
// Reset hook
self.hook_state
.try_borrow_mut()
.expect("Unexpected concurrent/nested view call")
.as_mut()
.unwrap()
.counter = 0;
// Load hook
CURRENT_HOOK.with(|previous_hook| {
std::mem::swap(
previous_hook
.try_borrow_mut()
.expect("Previous hook still borrowed")
.deref_mut(),
self.hook_state.borrow_mut().deref_mut(),
);
});
let ret = T::run(&self.props);
// Unload hook
CURRENT_HOOK.with(|previous_hook| {
std::mem::swap(
previous_hook
.try_borrow_mut()
.expect("Previous hook still borrowed")
.deref_mut(),
self.hook_state.borrow_mut().deref_mut(),
);
});
ret
}
}
impl<T> Drop for FunctionComponent<T>
where
T: FunctionProvider,
{
fn drop(&mut self) {
if let Some(hook_state) = self.hook_state.borrow_mut().deref_mut() {
for hook in hook_state.destroy_listeners.drain(..) {
hook()
}
}
}
}
pub fn use_ref<T: 'static, InitialProvider>(initial_value: InitialProvider) -> Rc<RefCell<T>>
where
InitialProvider: FnOnce() -> T,
{
#[derive(Clone)]
struct UseRefState<T>(Rc<RefCell<T>>);
impl<T> Hook for UseRefState<T> {}
use_hook(
|state: &mut UseRefState<T>, pretrigger_change_acceptor| {
let _ignored = || pretrigger_change_acceptor(|_| false); // we need it to be a specific closure type, even if we never use it
state.0.clone()
},
move || UseRefState(Rc::new(RefCell::new(initial_value()))),
)
}
pub fn use_reducer<Action: 'static, Reducer, State: 'static>(
reducer: Reducer,
initial_state: State,
) -> (Rc<State>, Rc<impl Fn(Action)>)
where
Reducer: Fn(Rc<State>, Action) -> State + 'static,
{
use_reducer_with_init(reducer, initial_state, |a| a)
}
pub fn use_reducer_with_init<Action: 'static, Reducer, State: 'static, InitialState, InitFn>(
reducer: Reducer,
initial_state: InitialState,
init: InitFn,
) -> (Rc<State>, Rc<impl Fn(Action)>)
where
Reducer: Fn(Rc<State>, Action) -> State + 'static,
InitFn: Fn(InitialState) -> State,
{
struct UseReducerState<State> {
current_state: Rc<State>,
}
impl<T> Hook for UseReducerState<T> {};
let init = Box::new(init);
let reducer = Rc::new(reducer);
use_hook(
|internal_hook_change: &mut UseReducerState<State>, pretrigger_change_runner| {
(
internal_hook_change.current_state.clone(),
Rc::new(move |action: Action| {
let reducer = reducer.clone();
pretrigger_change_runner(
move |internal_hook_change: &mut UseReducerState<State>| {
internal_hook_change.current_state = Rc::new((reducer)(
internal_hook_change.current_state.clone(),
action,
));
true
},
);
}),
)
},
move || UseReducerState {
current_state: Rc::new(init(initial_state)),
},
)
}
pub fn use_state<T, F>(initial_state_fn: F) -> (Rc<T>, Box<impl Fn(T)>)
where
F: FnOnce() -> T,
T: 'static,
{
struct UseStateState<T2> {
current: Rc<T2>,
}
impl<T> Hook for UseStateState<T> {}
use_hook(
|prev: &mut UseStateState<T>, hook_update| {
let current = prev.current.clone();
(
current,
Box::new(move |o: T| {
hook_update(|state: &mut UseStateState<T>| {
state.current = Rc::new(o);
true
});
}),
)
},
move || UseStateState {
current: Rc::new(initial_state_fn()),
},
)
}
pub fn use_effect<F, Destructor>(callback: F)
where
F: FnOnce() -> Destructor + 'static,
Destructor: FnOnce() + 'static,
{
let callback = Box::new(callback);
struct UseEffectState<Destructor> {
destructor: Option<Box<Destructor>>,
}
impl<T: FnOnce() + 'static> Hook for UseEffectState<T> {
fn tear_down(&mut self) {
if let Some(destructor) = self.destructor.take() {
destructor()
}
}
}
use_hook(
|_: &mut UseEffectState<Destructor>, hook_update| {
move || {
hook_update(move |state: &mut UseEffectState<Destructor>| {
if let Some(de) = state.destructor.take() {
de();
}
let new_destructor = callback();
state.destructor.replace(Box::new(new_destructor));
false
});
}
},
|| UseEffectState { destructor: None },
)();
}
pub fn use_effect_with_deps<F, Destructor, Dependents>(callback: F, deps: Dependents)
where
F: FnOnce(&Dependents) -> Destructor + 'static,
Destructor: FnOnce() + 'static,
Dependents: PartialEq + 'static,
{
struct UseEffectState<Dependents, Destructor> {
deps: Rc<Dependents>,
destructor: Option<Box<Destructor>>,
}
let deps = Rc::new(deps);
let deps_c = deps.clone();
impl<Dependents, Destructor: FnOnce() + 'static> Hook for UseEffectState<Dependents, Destructor> {
fn tear_down(&mut self) {
if let Some(destructor) = self.destructor.take() {
destructor()
}
}
}
use_hook(
move |state: &mut UseEffectState<Dependents, Destructor>, hook_update| {
let mut should_update = *state.deps != *deps;
move || {
hook_update(move |state: &mut UseEffectState<Dependents, Destructor>| {
if should_update {
if let Some(de) = state.destructor.take() {
de();
}
let new_destructor = callback(deps.borrow());
state.deps = deps.clone();
state.destructor.replace(Box::new(new_destructor));
} else if state.destructor.is_none() {
should_update = true;
state
.destructor
.replace(Box::new(callback(state.deps.borrow())));
}
false
})
}
},
|| UseEffectState {
deps: deps_c,
destructor: None,
},
)();
}
pub fn use_hook<InternalHookState, HookRunner, R, InitialStateProvider, PretriggerChange: 'static>(
hook_runner: HookRunner,
initial_state_producer: InitialStateProvider,
) -> R
where
HookRunner: FnOnce(&mut InternalHookState, Box<dyn Fn(PretriggerChange)>) -> R,
InternalHookState: Hook + 'static,
InitialStateProvider: FnOnce() -> InternalHookState,
PretriggerChange: FnOnce(&mut InternalHookState) -> bool,
{
// Extract current hook
let (hook, process_message) = CURRENT_HOOK.with(|hook_state_holder| {
let hook_state_holder = hook_state_holder.try_borrow_mut();
let mut hook_state_holder = hook_state_holder.expect("Nested hooks not supported");
let mut hook_state = hook_state_holder
.as_mut()
.expect("No current hook. Hooks can only be called inside functional components");
// Determine which hook position we're at and increment for the next hook
let hook_pos = hook_state.counter;
hook_state.counter += 1;
// Initialize hook if this is the first call
if hook_pos >= hook_state.hooks.len() {
let initial_state = Rc::new(RefCell::new(initial_state_producer()));
hook_state.hooks.push(initial_state.clone());
hook_state.destroy_listeners.push(Box::new(move || {
initial_state.borrow_mut().deref_mut().tear_down();
}));
}
let hook = hook_state.hooks[hook_pos].clone();
(hook, hook_state.process_message.clone())
});
let trigger = {
let hook = hook.clone();
Box::new(move |pretrigger_change: PretriggerChange| {
let hook = hook.clone();
process_message(Box::new(move || {
let mut hook = hook.borrow_mut();
let hook = hook.downcast_mut::<InternalHookState>();
let hook = hook.expect(
"Incompatible hook type. Hooks must always be called in the same order",
);
pretrigger_change(hook)
}));
})
};
let mut hook = hook.borrow_mut();
let hook = hook.downcast_mut::<InternalHookState>();
let mut hook =
hook.expect("Incompatible hook type. Hooks must always be called in the same order");
// Execute the actual hook closure we were given. Let it mutate the hook state and let
// it create a callback that takes the mutable hook state.
hook_runner(&mut hook, trigger)
}