hot_reload.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #![allow(dead_code)]
  2. use futures_channel::mpsc::UnboundedReceiver;
  3. use dioxus_core::Template;
  4. use wasm_bindgen::closure::Closure;
  5. use wasm_bindgen::JsCast;
  6. use web_sys::{MessageEvent, WebSocket};
  7. #[cfg(not(debug_assertions))]
  8. pub(crate) fn init() -> UnboundedReceiver<Template<'static>> {
  9. let (tx, rx) = futures_channel::mpsc::unbounded();
  10. std::mem::forget(tx);
  11. rx
  12. }
  13. #[cfg(debug_assertions)]
  14. pub(crate) fn init() -> UnboundedReceiver<Template<'static>> {
  15. use std::convert::TryInto;
  16. let window = web_sys::window().unwrap();
  17. let protocol = if window.location().protocol().unwrap() == "https:" {
  18. "wss:"
  19. } else {
  20. "ws:"
  21. };
  22. let url = format!(
  23. "{protocol}//{}/_dioxus/hot_reload",
  24. window.location().host().unwrap()
  25. );
  26. let ws = WebSocket::new(&url).unwrap();
  27. let (tx, rx) = futures_channel::mpsc::unbounded();
  28. // change the rsx when new data is received
  29. let cl = Closure::wrap(Box::new(move |e: MessageEvent| {
  30. if let Ok(text) = e.data().dyn_into::<js_sys::JsString>() {
  31. let text: Result<String, _> = text.try_into();
  32. if let Ok(string) = text {
  33. if let Ok(template) = serde_json::from_str(Box::leak(string.into_boxed_str())) {
  34. _ = tx.unbounded_send(template);
  35. }
  36. }
  37. }
  38. }) as Box<dyn FnMut(MessageEvent)>);
  39. ws.set_onmessage(Some(cl.as_ref().unchecked_ref()));
  40. cl.forget();
  41. rx
  42. }