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
use std::cell::RefCell;
use wasm_bindgen::{prelude::Closure, JsCast, JsValue};
use crate::window;
pub fn queue_update(x: impl 'static + FnOnce()) {
let len = {
PENDING_UPDATES.with(|update_queue| {
let mut update_queue = update_queue.borrow_mut();
update_queue.push(Box::new(x));
update_queue.len()
})
};
if len == 1 {
request_render_updates();
}
}
pub fn after_render(x: impl 'static + FnOnce()) {
PENDING_EFFECTS.with(|pending_effects| pending_effects.borrow_mut().push(Box::new(x)));
}
pub fn render_updates() {
PENDING_UPDATES.with(|update_queue| {
let update_queue = update_queue.take();
for update in update_queue {
update();
}
});
PENDING_EFFECTS.with(|effect_queue| {
for effect in effect_queue.take() {
effect();
}
});
}
fn request_render_updates() {
ON_ANIMATION_FRAME.with(|process_updates| {
window()
.request_animation_frame(process_updates.as_ref().unchecked_ref())
.unwrap()
});
}
thread_local!(
static PENDING_UPDATES: RefCell<Vec<Box<dyn FnOnce()>>> = RefCell::new(Vec::new());
static PENDING_EFFECTS: RefCell<Vec<Box<dyn FnOnce()>>> = RefCell::new(Vec::new());
static ON_ANIMATION_FRAME: Closure<dyn FnMut(JsValue)> =
Closure::wrap(Box::new(move |_time_stamp: JsValue| {
render_updates();
}));
);