deserialize.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. use serde::de::DeserializeOwned;
  2. use base64::engine::general_purpose::STANDARD;
  3. use base64::Engine;
  4. use super::HTMLDataCursor;
  5. #[allow(unused)]
  6. pub(crate) fn serde_from_bytes<T: DeserializeOwned>(string: &[u8]) -> Option<T> {
  7. let decompressed = match STANDARD.decode(string) {
  8. Ok(bytes) => bytes,
  9. Err(err) => {
  10. log::error!("Failed to decode base64: {}", err);
  11. return None;
  12. }
  13. };
  14. match postcard::from_bytes(&decompressed) {
  15. Ok(data) => Some(data),
  16. Err(err) => {
  17. log::error!("Failed to deserialize: {}", err);
  18. None
  19. }
  20. }
  21. }
  22. static SERVER_DATA: once_cell::sync::Lazy<Option<HTMLDataCursor>> =
  23. once_cell::sync::Lazy::new(|| {
  24. #[cfg(target_arch = "wasm32")]
  25. {
  26. let window = web_sys::window()?.document()?;
  27. let element = match window.get_element_by_id("dioxus-storage-data") {
  28. Some(element) => element,
  29. None => {
  30. log::error!("Failed to get element by id: dioxus-storage-data");
  31. return None;
  32. }
  33. };
  34. let attribute = match element.get_attribute("data-serialized") {
  35. Some(attribute) => attribute,
  36. None => {
  37. log::error!("Failed to get attribute: data-serialized");
  38. return None;
  39. }
  40. };
  41. let data: super::HTMLData = serde_from_bytes(attribute.as_bytes())?;
  42. Some(data.cursor())
  43. }
  44. #[cfg(not(target_arch = "wasm32"))]
  45. {
  46. None
  47. }
  48. });
  49. pub(crate) fn take_server_data<T: DeserializeOwned>() -> Option<T> {
  50. SERVER_DATA.as_ref()?.take()
  51. }
  52. #[cfg(not(feature = "ssr"))]
  53. /// Get the props from the document. This is only available in the browser.
  54. ///
  55. /// When dioxus-fullstack renders the page, it will serialize the root props and put them in the document. This function gets them from the document.
  56. pub fn get_root_props_from_document<T: DeserializeOwned>() -> Option<T> {
  57. #[cfg(not(target_arch = "wasm32"))]
  58. {
  59. None
  60. }
  61. #[cfg(target_arch = "wasm32")]
  62. {
  63. let attribute = web_sys::window()?
  64. .document()?
  65. .get_element_by_id("dioxus-storage-props")?
  66. .get_attribute("data-serialized")?;
  67. serde_from_bytes(attribute.as_bytes())
  68. }
  69. }