ric_raf.rs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //! This module provides some utilities around scheduling tasks on the main thread of the browser.
  2. //!
  3. //! The ultimate goal here is to not block the main thread during animation frames, so our animations don't result in "jank".
  4. //!
  5. //! Hence, this module provides Dioxus "Jank Free Rendering" on the web.
  6. //!
  7. //! Because RIC doesn't work on Safari, we polyfill using the "ricpolyfill.js" file and use some basic detection to see
  8. //! if RIC is available.
  9. use gloo_timers::future::TimeoutFuture;
  10. use js_sys::Function;
  11. use wasm_bindgen::{prelude::Closure, JsCast, JsValue};
  12. use web_sys::{window, Window};
  13. pub(crate) struct RafLoop {
  14. window: Window,
  15. ric_receiver: async_channel::Receiver<u32>,
  16. raf_receiver: async_channel::Receiver<()>,
  17. ric_closure: Closure<dyn Fn(JsValue)>,
  18. raf_closure: Closure<dyn Fn(JsValue)>,
  19. }
  20. impl RafLoop {
  21. pub fn new() -> Self {
  22. let (raf_sender, raf_receiver) = async_channel::unbounded();
  23. let raf_closure: Closure<dyn Fn(JsValue)> = Closure::wrap(Box::new(move |_v: JsValue| {
  24. raf_sender.try_send(()).unwrap()
  25. }));
  26. let (ric_sender, ric_receiver) = async_channel::unbounded();
  27. let has_idle_callback = {
  28. let bo = window().unwrap().dyn_into::<js_sys::Object>().unwrap();
  29. bo.has_own_property(&JsValue::from_str("requestIdleCallback"))
  30. };
  31. let ric_closure: Closure<dyn Fn(JsValue)> = Closure::wrap(Box::new(move |v: JsValue| {
  32. let time_remaining = if has_idle_callback {
  33. if let Ok(deadline) = v.dyn_into::<web_sys::IdleDeadline>() {
  34. deadline.time_remaining() as u32
  35. } else {
  36. 10
  37. }
  38. } else {
  39. 10
  40. };
  41. ric_sender.try_send(time_remaining).unwrap()
  42. }));
  43. // execute the polyfill for safari
  44. Function::new_no_args(include_str!("./ricpolyfill.js"))
  45. .call0(&JsValue::NULL)
  46. .unwrap();
  47. let window = web_sys::window().unwrap();
  48. Self {
  49. window,
  50. raf_receiver,
  51. raf_closure,
  52. ric_receiver,
  53. ric_closure,
  54. }
  55. }
  56. /// waits for some idle time and returns a timeout future that expires after the idle time has passed
  57. pub async fn wait_for_idle_time(&self) -> TimeoutFuture {
  58. let ric_fn = self.ric_closure.as_ref().dyn_ref::<Function>().unwrap();
  59. let _cb_id: u32 = self.window.request_idle_callback(ric_fn).unwrap();
  60. let deadline = self.ric_receiver.recv().await.unwrap();
  61. TimeoutFuture::new(deadline)
  62. }
  63. pub async fn wait_for_raf(&self) {
  64. let raf_fn = self.raf_closure.as_ref().dyn_ref::<Function>().unwrap();
  65. let _id: i32 = self.window.request_animation_frame(raf_fn).unwrap();
  66. self.raf_receiver.recv().await.unwrap();
  67. }
  68. }