forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
feat_ssr.rs
83 lines (70 loc) · 2.23 KB
/
feat_ssr.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
//! The server-side rendering variant.
use std::cell::RefCell;
use std::rc::Rc;
use base64ct::{Base64, Encoding};
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::functional::{Hook, HookContext, PreparedState};
use crate::suspense::SuspensionResult;
pub(super) struct TransitiveStateBase<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
pub state_fn: RefCell<Option<F>>,
pub deps: Rc<D>,
}
impl<T, D, F> PreparedState for TransitiveStateBase<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
fn prepare(&self) -> String {
let f = self.state_fn.borrow_mut().take().unwrap();
let state = f(self.deps.clone());
let state = bincode::serialize(&(Some(&state), Some(&*self.deps)))
.expect("failed to prepare state");
Base64::encode_string(&state)
}
}
#[doc(hidden)]
pub fn use_transitive_state<T, D, F>(
f: F,
deps: Rc<D>,
) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
struct HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
deps: Rc<D>,
f: F,
}
impl<T, D, F> Hook for HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
let Self { f, deps } = self;
ctx.next_prepared_state(move |_re_render, _| -> TransitiveStateBase<T, D, F> {
TransitiveStateBase {
state_fn: Some(f).into(),
deps,
}
});
Ok(None)
}
}
HookProvider::<T, D, F> { deps, f }
}