lib.rs 2.1 KB

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