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
use crate::{
Cmd,
Component,
Dispatch,
DomUpdater,
};
use std::{
cell::RefCell,
fmt::Debug,
rc::Rc,
};
use wasm_bindgen::closure::Closure;
use web_sys::Node;
pub struct Program<APP, MSG> {
pub app: Rc<RefCell<APP>>,
pub dom_updater: Rc<RefCell<DomUpdater<Self, MSG>>>,
}
impl<APP, MSG> Program<APP, MSG>
where
MSG: Debug + Clone + 'static,
APP: Component<MSG> + 'static,
{
fn new(app: APP, root_node: &Node) -> Rc<Self> {
let dom_updater: DomUpdater<Self, MSG> =
DomUpdater::new(app.view(), root_node);
let program = Program {
app: Rc::new(RefCell::new(app)),
dom_updater: Rc::new(RefCell::new(dom_updater)),
};
let rc_program: Rc<Self> = Rc::new(program);
let cmds: Cmd<APP, MSG> = rc_program.app.borrow().init();
cmds.emit(&rc_program);
rc_program
}
pub fn new_replace_mount(app: APP, root_node: &Node) -> Rc<Self> {
let program = Self::new(app, root_node);
program.start_replace_mount();
program
}
pub fn new_append_to_mount(app: APP, root_node: &Node) -> Rc<Self> {
let program = Self::new(app, root_node);
program.start_append_to_mount();
program
}
pub fn mount_to_body(app: APP) -> Rc<Self> {
Self::new_append_to_mount(app, &crate::body())
}
fn start_append_to_mount(self: &Rc<Self>) {
self.dom_updater.borrow_mut().append_to_mount(self)
}
fn start_replace_mount(self: &Rc<Self>) {
self.dom_updater.borrow_mut().replace_mount(self)
}
fn dispatch_inner(self: &Rc<Self>, msg: MSG) {
#[cfg(feature = "measure")]
let t1 = crate::now();
let cmd = self.app.borrow_mut().update(msg);
cmd.emit(self);
crate::log("Executing cmd..");
#[cfg(feature = "measure")]
let t2 = {
let t2 = crate::now();
crate::log!("app update took: {}ms", t2 - t1);
t2
};
let view = self.app.borrow().view();
#[cfg(feature = "measure")]
let t3 = {
let t3 = crate::now();
crate::log!("app view took: {}ms", t3 - t2);
t3
};
self.dom_updater.borrow_mut().update_dom(self, view);
#[cfg(feature = "measure")]
{
let t4 = crate::now();
crate::log!("dom update took: {}ms", t4 - t3);
};
}
}
impl<APP, MSG> Dispatch<MSG> for Program<APP, MSG>
where
MSG: Debug + Clone + 'static,
APP: Component<MSG> + 'static,
{
fn dispatch(self: &Rc<Self>, msg: MSG) {
let program_clone = Rc::clone(self);
let closure_raf: Closure<dyn FnMut() + 'static> =
Closure::once(move || {
program_clone.dispatch_inner(msg);
});
crate::request_animation_frame(&closure_raf);
closure_raf.forget();
}
}