lib.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use std::io::{BufRead, BufReader};
  2. use dioxus_core::Template;
  3. #[cfg(file_watcher)]
  4. pub use dioxus_html::HtmlCtx;
  5. use interprocess_docfix::local_socket::LocalSocketStream;
  6. use serde::{Deserialize, Serialize};
  7. #[cfg(file_watcher)]
  8. mod file_watcher;
  9. #[cfg(file_watcher)]
  10. use file_watcher::*;
  11. /// A message the hot reloading server sends to the client
  12. #[derive(Debug, Serialize, Deserialize, Clone, Copy)]
  13. pub enum HotReloadMsg {
  14. /// A template has been updated
  15. #[serde(borrow = "'static")]
  16. UpdateTemplate(Template<'static>),
  17. /// The program needs to be recompiled, and the client should shut down
  18. Shutdown,
  19. }
  20. /// Connect to the hot reloading listener. The callback provided will be called every time a template change is detected
  21. pub fn connect(mut f: impl FnMut(HotReloadMsg) + Send + 'static) {
  22. std::thread::spawn(move || {
  23. if let Ok(socket) = LocalSocketStream::connect("@dioxusin") {
  24. let mut buf_reader = BufReader::new(socket);
  25. loop {
  26. let mut buf = String::new();
  27. match buf_reader.read_line(&mut buf) {
  28. Ok(_) => {
  29. let template: HotReloadMsg =
  30. serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap();
  31. f(template);
  32. }
  33. Err(err) => {
  34. if err.kind() != std::io::ErrorKind::WouldBlock {
  35. break;
  36. }
  37. }
  38. }
  39. }
  40. }
  41. });
  42. }
  43. /// Start the hot reloading server with the current directory as the root
  44. #[macro_export]
  45. macro_rules! hot_reload_init {
  46. () => {
  47. #[cfg(debug_assertions)]
  48. dioxus_hot_reload::init(dioxus_hot_reload::Config::new().root(env!("CARGO_MANIFEST_DIR")));
  49. };
  50. ($cfg: expr) => {
  51. #[cfg(debug_assertions)]
  52. dioxus_hot_reload::init($cfg.root(env!("CARGO_MANIFEST_DIR")));
  53. };
  54. }