web_sys_main_loop/
main_loop.rs

1// Copyright 2024 arongeo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{cell::RefCell, rc::Rc};
16
17use wasm_bindgen::prelude::*;
18use wasm_bindgen::JsCast;
19
20use crate::frame_state::FrameState;
21use crate::input_handler::input_state::InputState;
22
23fn request_animation_frame(window: &web_sys::Window, function: &Closure<dyn FnMut()>) {
24    window
25        .request_animation_frame(function.as_ref().unchecked_ref())
26        .expect("Frame dropped");
27}
28
29/// Runs the closure provided with [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
30/// every possible frame
31///
32/// Use it as:
33/// ```
34/// use web_sys_main_loop::{start, FrameState};
35///
36/// let window = web_sys::window().unwrap();
37/// ...
38/// start(&window, move |frame_state: FrameState| {
39///     ...
40/// });
41///
42/// ```
43pub fn start<F>(window: &web_sys::Window, mut main_loop_function: F)
44where
45    F: FnMut(FrameState) + 'static,
46{
47    let main_loop = Rc::new(RefCell::new(None));
48    let main_loop_starter = main_loop.clone();
49    let window_clone = window.clone();
50
51    let input_state = InputState::new(&window);
52
53    *main_loop_starter.borrow_mut() = Some(Closure::new(move || {
54        main_loop_function(input_state.create_frame_state());
55
56        input_state.clear();
57
58        request_animation_frame(&window_clone, main_loop.borrow().as_ref().unwrap());
59    }));
60
61    request_animation_frame(&window, main_loop_starter.borrow().as_ref().unwrap());
62}