scroll.rs 899 B

12345678910111213141516171819202122232425262728
  1. use wasm_bindgen::{prelude::Closure, JsCast};
  2. use web_sys::Window;
  3. #[derive(Clone, Copy, Debug, Default)]
  4. pub(crate) struct ScrollPosition {
  5. pub x: f64,
  6. pub y: f64,
  7. }
  8. impl ScrollPosition {
  9. pub(crate) fn of_window(window: &Window) -> Self {
  10. Self {
  11. x: window.scroll_x().unwrap_or_default(),
  12. y: window.scroll_y().unwrap_or_default(),
  13. }
  14. }
  15. pub(crate) fn scroll_to(&self, window: Window) {
  16. let Self { x, y } = *self;
  17. let f = Closure::wrap(
  18. Box::new(move || window.scroll_to_with_x_and_y(x, y)) as Box<dyn FnMut()>
  19. );
  20. web_sys::window()
  21. .expect("should be run in a context with a `Window` object (dioxus cannot be run from a web worker)")
  22. .request_animation_frame(&f.into_js_value().unchecked_into())
  23. .expect("should register `requestAnimationFrame` OK");
  24. }
  25. }