lib.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use dioxus_core::{ScopeId, VirtualDom};
  2. pub use dioxus_devtools_types::*;
  3. use dioxus_signals::{GlobalKey, Writable};
  4. /// Applies template and literal changes to the VirtualDom
  5. ///
  6. /// Assets need to be handled by the renderer.
  7. pub fn apply_changes(dom: &VirtualDom, msg: &HotReloadMsg) {
  8. dom.runtime().on_scope(ScopeId::ROOT, || {
  9. let ctx = dioxus_signals::get_global_context();
  10. for template in &msg.templates {
  11. let value = template.template.clone();
  12. let key = GlobalKey::File {
  13. file: template.key.file.as_str(),
  14. line: template.key.line as _,
  15. column: template.key.column as _,
  16. index: template.key.index as _,
  17. };
  18. if let Some(mut signal) = ctx.get_signal_with_key(key.clone()) {
  19. signal.set(Some(value));
  20. }
  21. }
  22. });
  23. }
  24. /// Connect to the devserver and handle its messages with a callback.
  25. ///
  26. /// This doesn't use any form of security or protocol, so it's not safe to expose to the internet.
  27. #[cfg(not(target_arch = "wasm32"))]
  28. pub fn connect(endpoint: String, mut callback: impl FnMut(DevserverMsg) + Send + 'static) {
  29. std::thread::spawn(move || {
  30. let (mut websocket, _req) = match tungstenite::connect(endpoint.clone()) {
  31. Ok((websocket, req)) => (websocket, req),
  32. Err(_) => return,
  33. };
  34. while let Ok(msg) = websocket.read() {
  35. if let tungstenite::Message::Text(text) = msg {
  36. if let Ok(msg) = serde_json::from_str(&text) {
  37. callback(msg);
  38. }
  39. }
  40. }
  41. });
  42. }