Ver Fonte

Dioxus Playground Hot Reload Support (#3098)

* feat: playground hr support

* feat: playground hot-reload support

* revision: playground hot reloading
Miles Murgaw há 5 meses atrás
pai
commit
273b70e9d6
1 ficheiros alterados com 27 adições e 1 exclusões
  1. 27 1
      packages/web/src/devtools.rs

+ 27 - 1
packages/web/src/devtools.rs

@@ -30,7 +30,8 @@ pub(crate) fn init(runtime: Rc<Runtime>) -> UnboundedReceiver<HotReloadMsg> {
     let (tx, rx) = unbounded();
 
     // Wire up the websocket to the devserver
-    make_ws(runtime, tx, POLL_INTERVAL_MIN, false);
+    make_ws(runtime, tx.clone(), POLL_INTERVAL_MIN, false);
+    playground(tx);
 
     rx
 }
@@ -265,3 +266,28 @@ pub(crate) fn invalidate_browser_asset_cache() {
         }
     }
 }
+
+/// Initialize required devtools for dioxus-playground.
+///
+/// This listens for window message events from other Windows (such as window.top when this is running in an iframe).
+fn playground(tx: UnboundedSender<HotReloadMsg>) {
+    let window = web_sys::window().expect("this code should be running in a web context");
+
+    let binding = Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
+        let Ok(text) = e.data().dyn_into::<JsString>() else {
+            return;
+        };
+        let string: String = text.into();
+        let Ok(hr_msg) = serde_json::from_str::<HotReloadMsg>(&string) else {
+            return;
+        };
+        _ = tx.unbounded_send(hr_msg);
+    });
+
+    let callback = binding.as_ref().unchecked_ref();
+    window
+        .add_event_listener_with_callback("message", callback)
+        .expect("event listener should be added successfully");
+
+    binding.forget();
+}