web_history.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. use gloo::console::error;
  2. use wasm_bindgen::JsValue;
  3. use web_sys::History;
  4. pub(crate) fn replace_state_with_url(
  5. history: &History,
  6. value: &[f64; 2],
  7. url: Option<&str>,
  8. ) -> Result<(), JsValue> {
  9. let position = js_sys::Array::new();
  10. position.push(&JsValue::from(value[0]));
  11. position.push(&JsValue::from(value[1]));
  12. history.replace_state_with_url(&position, "", url)
  13. }
  14. pub(crate) fn push_state_and_url(
  15. history: &History,
  16. value: &[f64; 2],
  17. url: String,
  18. ) -> Result<(), JsValue> {
  19. let position = js_sys::Array::new();
  20. position.push(&JsValue::from(value[0]));
  21. position.push(&JsValue::from(value[1]));
  22. history.push_state_with_url(&position, "", Some(&url))
  23. }
  24. pub(crate) fn get_current(history: &History) -> Option<[f64; 2]> {
  25. use wasm_bindgen::JsCast;
  26. let state = history.state();
  27. if let Err(err) = &state {
  28. error!(err);
  29. }
  30. state.ok().and_then(|state| {
  31. let state = state.dyn_into::<js_sys::Array>().ok()?;
  32. let x = state.get(0).as_f64()?;
  33. let y = state.get(1).as_f64()?;
  34. Some([x, y])
  35. })
  36. }