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
use std::cell::Cell;
use std::panic::PanicInfo;
use std::rc::Rc;
use web_sys::Element;
use crate::app_handle::AppHandle;
use crate::html::BaseComponent;
thread_local! {
static PANIC_HOOK_IS_SET: Cell<bool> = Cell::new(false);
}
#[cfg(feature = "csr")]
pub fn set_custom_panic_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + Sync + Send + 'static>) {
std::panic::set_hook(hook);
PANIC_HOOK_IS_SET.with(|hook_is_set| hook_is_set.set(true));
}
fn set_default_panic_hook() {
if !PANIC_HOOK_IS_SET.with(|hook_is_set| hook_is_set.replace(true)) {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
}
}
#[cfg(feature = "csr")]
#[derive(Debug)]
#[must_use = "Renderer does nothing unless render() is called."]
pub struct Renderer<COMP>
where
COMP: BaseComponent + 'static,
{
root: Element,
props: COMP::Properties,
}
impl<COMP> Default for Renderer<COMP>
where
COMP: BaseComponent + 'static,
COMP::Properties: Default,
{
fn default() -> Self {
Self::with_props(Default::default())
}
}
impl<COMP> Renderer<COMP>
where
COMP: BaseComponent + 'static,
COMP::Properties: Default,
{
pub fn new() -> Self {
Self::default()
}
pub fn with_root(root: Element) -> Self {
Self::with_root_and_props(root, Default::default())
}
}
impl<COMP> Renderer<COMP>
where
COMP: BaseComponent + 'static,
{
pub fn with_props(props: COMP::Properties) -> Self {
Self::with_root_and_props(
gloo::utils::document()
.body()
.expect("no body node found")
.into(),
props,
)
}
pub fn with_root_and_props(root: Element, props: COMP::Properties) -> Self {
Self { root, props }
}
pub fn render(self) -> AppHandle<COMP> {
set_default_panic_hook();
AppHandle::<COMP>::mount_with_props(self.root, Rc::new(self.props))
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
impl<COMP> Renderer<COMP>
where
COMP: BaseComponent + 'static,
{
pub fn hydrate(self) -> AppHandle<COMP> {
set_default_panic_hook();
AppHandle::<COMP>::hydrate_with_props(self.root, Rc::new(self.props))
}
}
}