From 107357489605ab9d524847fac3fba67a04dd8799 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 11 Jan 2023 13:40:02 -0600 Subject: [PATCH 01/29] implement hot reloading for desktop --- Cargo.toml | 3 + packages/desktop/Cargo.toml | 2 +- packages/desktop/src/desktop_context.rs | 3 + packages/desktop/src/hot_reload.rs | 46 +++++--------- packages/desktop/src/lib.rs | 12 ++++ packages/hot-reload-macro/Cargo.toml | 13 ++++ packages/hot-reload-macro/src/lib.rs | 7 +++ packages/hot-reload/Cargo.toml | 17 +++++ packages/hot-reload/src/lib.rs | 84 +++++++++++++++++++++++++ 9 files changed, 155 insertions(+), 32 deletions(-) create mode 100644 packages/hot-reload-macro/Cargo.toml create mode 100644 packages/hot-reload-macro/src/lib.rs create mode 100644 packages/hot-reload/Cargo.toml create mode 100644 packages/hot-reload/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 7d8cc6871..ebfe288c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,8 @@ members = [ "packages/native-core-macro", "packages/rsx-rosetta", "packages/signals", + "packages/hot-reload", + "packages/hot-reload-macro", "docs/guide", ] @@ -43,6 +45,7 @@ publish = false dioxus = { path = "./packages/dioxus" } dioxus-desktop = { path = "./packages/desktop", features = ["transparent"] } dioxus-ssr = { path = "./packages/ssr" } +dioxus-hot-reload = { path = "./packages/hot-reload" } dioxus-router = { path = "./packages/router" } dioxus-signals = { path = "./packages/signals" } fermi = { path = "./packages/fermi" } diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index 5f1ea27d7..16cc622c6 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -33,7 +33,7 @@ webbrowser = "0.8.0" infer = "0.11.0" dunce = "1.0.2" -interprocess = { version = "1.1.1", optional = true } +interprocess = { version = "1.2.1", optional = true } futures-util = "0.3.25" [target.'cfg(target_os = "ios")'.dependencies] diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index d3b9216b0..720223e6c 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -8,6 +8,7 @@ use crate::events::IpcMessage; use crate::Config; use crate::WebviewHandler; use dioxus_core::ScopeState; +use dioxus_core::Template; use dioxus_core::VirtualDom; use serde_json::Value; use wry::application::event_loop::EventLoopProxy; @@ -262,6 +263,8 @@ pub enum EventData { Ipc(IpcMessage), + TemplateUpdated(Template<'static>), + NewWindow, CloseWindow, diff --git a/packages/desktop/src/hot_reload.rs b/packages/desktop/src/hot_reload.rs index e1383390d..20907f59d 100644 --- a/packages/desktop/src/hot_reload.rs +++ b/packages/desktop/src/hot_reload.rs @@ -2,43 +2,29 @@ use dioxus_core::Template; -use interprocess::local_socket::{LocalSocketListener, LocalSocketStream}; +use interprocess::local_socket::LocalSocketStream; use std::io::{BufRead, BufReader}; -use std::time::Duration; -use std::{sync::Arc, sync::Mutex}; +use wry::application::{event_loop::EventLoopProxy, window::WindowId}; -fn handle_error(connection: std::io::Result) -> Option { - connection - .map_err(|error| eprintln!("Incoming connection failed: {}", error)) - .ok() -} +use crate::desktop_context::{EventData, UserWindowEvent}; -pub(crate) fn init(proxy: futures_channel::mpsc::UnboundedSender>) { - let latest_in_connection: Arc>>> = - Arc::new(Mutex::new(None)); - - let latest_in_connection_handle = latest_in_connection.clone(); - - // connect to processes for incoming data +pub(crate) fn init(proxy: EventLoopProxy) { std::thread::spawn(move || { let temp_file = std::env::temp_dir().join("@dioxusin"); - - if let Ok(listener) = LocalSocketListener::bind(temp_file) { - for conn in listener.incoming().filter_map(handle_error) { - *latest_in_connection_handle.lock().unwrap() = Some(BufReader::new(conn)); - } - } - }); - - std::thread::spawn(move || { - loop { - if let Some(conn) = &mut *latest_in_connection.lock().unwrap() { + if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) { + let mut buf_reader = BufReader::new(socket); + loop { let mut buf = String::new(); - match conn.read_line(&mut buf) { + match buf_reader.read_line(&mut buf) { Ok(_) => { - let msg: Template<'static> = + let template: Template<'static> = serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); - proxy.unbounded_send(msg).unwrap(); + proxy + .send_event(UserWindowEvent( + EventData::TemplateUpdated(template), + unsafe { WindowId::dummy() }, + )) + .unwrap(); } Err(err) => { if err.kind() != std::io::ErrorKind::WouldBlock { @@ -47,8 +33,6 @@ pub(crate) fn init(proxy: futures_channel::mpsc::UnboundedSender(root: Component

, props: P, cfg: Config) let proxy = event_loop.create_proxy(); + // Intialize hot reloading if it is enabled + #[cfg(all(feature = "hot-reload", debug_assertions))] + hot_reload::init(proxy.clone()); + // We start the tokio runtime *on this thread* // Any future we poll later will use this runtime to spawn tasks and for IO let rt = tokio::runtime::Builder::new_multi_thread() @@ -168,6 +172,14 @@ pub fn launch_with_props(root: Component

, props: P, cfg: Config) } Event::UserEvent(event) => match event.0 { + EventData::TemplateUpdated(template) => { + for webview in webviews.values_mut() { + webview.dom.replace_template(template); + + poll_vdom(webview); + } + } + EventData::CloseWindow => { webviews.remove(&event.1); diff --git a/packages/hot-reload-macro/Cargo.toml b/packages/hot-reload-macro/Cargo.toml new file mode 100644 index 000000000..009c6501a --- /dev/null +++ b/packages/hot-reload-macro/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "dioxus-hot-reload-macro" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +syn = { version = "1.0.107", features = ["full"] } +proc-macro2 = { version = "1.0" } + +[lib] +proc-macro = true \ No newline at end of file diff --git a/packages/hot-reload-macro/src/lib.rs b/packages/hot-reload-macro/src/lib.rs new file mode 100644 index 000000000..211be00cf --- /dev/null +++ b/packages/hot-reload-macro/src/lib.rs @@ -0,0 +1,7 @@ +use proc_macro::TokenStream; +use syn::__private::quote::quote; + +#[proc_macro] +pub fn hot_reload(_: TokenStream) -> TokenStream { + quote!(dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"))).into() +} diff --git a/packages/hot-reload/Cargo.toml b/packages/hot-reload/Cargo.toml new file mode 100644 index 000000000..5c9f34826 --- /dev/null +++ b/packages/hot-reload/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "dioxus-hot-reload" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +dioxus-hot-reload-macro = { path = "../hot-reload-macro" } +dioxus-rsx = { path = "../rsx" } +dioxus-core = { path = "../core", features = ["serialize"] } +dioxus-html = { path = "../html", features = ["hot-reload-context"] } + +interprocess = { version = "1.2.1" } +notify = "5.0.0" +chrono = "0.4.23" +serde_json = "1.0.91" diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs new file mode 100644 index 000000000..4918b0c03 --- /dev/null +++ b/packages/hot-reload/src/lib.rs @@ -0,0 +1,84 @@ +use std::{ + io::Write, + path::PathBuf, + str::FromStr, + sync::{Arc, Mutex}, +}; + +pub use dioxus_hot_reload_macro::hot_reload; +use dioxus_html::HtmlCtx; +use dioxus_rsx::hot_reload::{FileMap, UpdateResult}; +use interprocess::local_socket::LocalSocketListener; +use notify::{RecommendedWatcher, RecursiveMode, Watcher}; + +pub fn init(path: &'static str) { + if let Ok(crate_dir) = PathBuf::from_str(path) { + let temp_file = std::env::temp_dir().join("@dioxusin"); + let channels = Arc::new(Mutex::new(Vec::new())); + if let Ok(local_socket_stream) = LocalSocketListener::bind(temp_file.as_path()) { + // listen for connections + std::thread::spawn({ + let channels = channels.clone(); + move || { + for connection in local_socket_stream.incoming() { + if let Ok(connection) = connection { + channels.lock().unwrap().push(connection); + println!("Connected to hot reloading 🚀"); + } + } + } + }); + + // watch for changes + std::thread::spawn(move || { + let mut last_update_time = chrono::Local::now().timestamp(); + let mut file_map = FileMap::::new(crate_dir.clone()); + + let (tx, rx) = std::sync::mpsc::channel(); + + let mut watcher = RecommendedWatcher::new(tx, notify::Config::default()).unwrap(); + + let mut examples_path = crate_dir.clone(); + examples_path.push("examples"); + let _ = watcher.watch(&examples_path, RecursiveMode::Recursive); + let mut src_path = crate_dir.clone(); + src_path.push("src"); + let _ = watcher.watch(&src_path, RecursiveMode::Recursive); + + for evt in rx { + // Give time for the change to take effect before reading the file + std::thread::sleep(std::time::Duration::from_millis(100)); + if chrono::Local::now().timestamp() > last_update_time { + if let Ok(evt) = evt { + let mut channels = channels.lock().unwrap(); + for path in &evt.paths { + // skip non rust files + if path.extension().and_then(|p| p.to_str()) != Some("rs") { + continue; + } + + // find changes to the rsx in the file + match file_map.update_rsx(&path, crate_dir.as_path()) { + UpdateResult::UpdatedRsx(msgs) => { + for msg in msgs { + for channel in channels.iter_mut() { + let msg = serde_json::to_string(&msg).unwrap(); + channel.write_all(msg.as_bytes()).unwrap(); + channel.write_all(&[b'\n']).unwrap(); + } + } + } + UpdateResult::NeedsRebuild => { + println!("Rebuild needed... shutting down hot reloading"); + return; + } + } + } + } + last_update_time = chrono::Local::now().timestamp(); + } + } + }); + } + } +} From 6eff4438cfb5981e69e641c6d6b880b4f4eab291 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 11 Jan 2023 14:20:38 -0600 Subject: [PATCH 02/29] implement hot reloading for TUI --- packages/tui/Cargo.toml | 9 ++++++++- packages/tui/src/hot_reload.rs | 31 ++++++++++++++++++++++++++++++ packages/tui/src/lib.rs | 35 ++++++++++++++++++++++++++++------ 3 files changed, 68 insertions(+), 7 deletions(-) create mode 100644 packages/tui/src/hot_reload.rs diff --git a/packages/tui/Cargo.toml b/packages/tui/Cargo.toml index 5341d40f4..1e35f8b3e 100644 --- a/packages/tui/Cargo.toml +++ b/packages/tui/Cargo.toml @@ -14,7 +14,7 @@ license = "MIT/Apache-2.0" [dependencies] dioxus = { path = "../dioxus", version = "^0.3.0" } -dioxus-core = { path = "../core", version = "^0.3.0" } +dioxus-core = { path = "../core", version = "^0.3.0", features = ["serialize"] } dioxus-html = { path = "../html", version = "^0.3.0" } dioxus-native-core = { path = "../native-core", version = "^0.2.0" } dioxus-native-core-macro = { path = "../native-core-macro", version = "^0.2.0" } @@ -29,6 +29,9 @@ smallvec = "1.6" rustc-hash = "1.1.0" anymap = "1.0.0-beta.2" futures-channel = "0.3.25" +interprocess = { version = "1.2.1", optional = true } +serde = { version = "1.0.136", optional = true } +serde_json = { version = "1.0.79", optional = true } [dev-dependencies] dioxus = { path = "../dioxus" } @@ -38,3 +41,7 @@ criterion = "0.3.5" [[bench]] name = "update" harness = false + +[features] +default = ["hot-reload"] +hot-reload = ["interprocess", "serde", "serde_json"] diff --git a/packages/tui/src/hot_reload.rs b/packages/tui/src/hot_reload.rs new file mode 100644 index 000000000..8385879e0 --- /dev/null +++ b/packages/tui/src/hot_reload.rs @@ -0,0 +1,31 @@ +#![allow(dead_code)] + +use dioxus_core::Template; + +use interprocess::local_socket::LocalSocketStream; +use std::io::{BufRead, BufReader}; +use tokio::sync::mpsc::UnboundedSender; + +pub(crate) fn init(proxy: UnboundedSender>) { + std::thread::spawn(move || { + let temp_file = std::env::temp_dir().join("@dioxusin"); + if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) { + let mut buf_reader = BufReader::new(socket); + loop { + let mut buf = String::new(); + match buf_reader.read_line(&mut buf) { + Ok(_) => { + let template: Template<'static> = + serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); + proxy.send(template).unwrap(); + } + Err(err) => { + if err.kind() != std::io::ErrorKind::WouldBlock { + break; + } + } + } + } + } + }); +} diff --git a/packages/tui/src/lib.rs b/packages/tui/src/lib.rs index 4c8d8e739..6af02e993 100644 --- a/packages/tui/src/lib.rs +++ b/packages/tui/src/lib.rs @@ -22,11 +22,14 @@ use std::{ use std::{io, time::Duration}; use taffy::Taffy; pub use taffy::{geometry::Point, prelude::*}; +use tokio::{select, sync::mpsc::unbounded_channel}; use tui::{backend::CrosstermBackend, layout::Rect, Terminal}; mod config; mod focus; mod hooks; +#[cfg(all(feature = "hot-reload", debug_assertions))] +mod hot_reload; mod layout; mod node; pub mod prelude; @@ -144,6 +147,12 @@ fn render_vdom( .enable_all() .build()? .block_on(async { + #[cfg(all(feature = "hot-reload", debug_assertions))] + let mut hot_reload_rx = { + let (hot_reload_tx, hot_reload_rx) = unbounded_channel::>(); + hot_reload::init(hot_reload_tx); + hot_reload_rx + }; let mut terminal = (!cfg.headless).then(|| { enable_raw_mode().unwrap(); let mut stdout = std::io::stdout(); @@ -223,16 +232,21 @@ fn render_vdom( } } - use futures::future::{select, Either}; + let mut new_templete = None; { let wait = vdom.wait_for_work(); + #[cfg(all(feature = "hot-reload", debug_assertions))] + let hot_reload_wait = hot_reload_rx.recv(); + #[cfg(not(all(feature = "hot-reload", debug_assertions)))] + let hot_reload_wait = std::future::pending(); + pin_mut!(wait); - match select(wait, event_reciever.next()).await { - Either::Left((_a, _b)) => { - // - } - Either::Right((evt, _o)) => { + select! { + _ = wait => { + + }, + evt = event_reciever.next() => { match evt.as_ref().unwrap() { InputEvent::UserInput(event) => match event { TermEvent::Key(key) => { @@ -252,10 +266,19 @@ fn render_vdom( if let InputEvent::UserInput(evt) = evt.unwrap() { register_event(evt); } + }, + Some(template) = hot_reload_wait => { + new_templete = Some(template); } } } + // if we have a new template, replace the old one + if let Some(template) = new_templete { + // println!("reloading template"); + vdom.replace_template(template); + } + { let evts = { let mut rdom = rdom.borrow_mut(); From e5e1abbdacc2916f42e5a57498d7765918e1d94f Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 11 Jan 2023 14:41:29 -0600 Subject: [PATCH 03/29] implement hot reloading for liveview --- packages/liveview/Cargo.toml | 11 ++++++---- packages/liveview/src/hot_reload.rs | 31 +++++++++++++++++++++++++++++ packages/liveview/src/lib.rs | 2 ++ packages/liveview/src/pool.rs | 18 +++++++++++++++++ 4 files changed, 58 insertions(+), 4 deletions(-) create mode 100644 packages/liveview/src/hot_reload.rs diff --git a/packages/liveview/Cargo.toml b/packages/liveview/Cargo.toml index 0fc26674c..53df88759 100644 --- a/packages/liveview/Cargo.toml +++ b/packages/liveview/Cargo.toml @@ -13,6 +13,10 @@ license = "MIT/Apache-2.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +dioxus-html = { path = "../html", features = ["serialize"], version = "^0.3.0" } +dioxus-core = { path = "../core", features = ["serialize"], version = "^0.3.0" } +dioxus-interpreter-js = { path = "../interpreter", version = "0.3.0" } + tokio = { version = "1.23.0", features = ["full"] } futures-util = { version = "0.3.25", default-features = false, features = [ "sink", @@ -25,9 +29,7 @@ serde = { version = "1.0.151", features = ["derive"] } serde_json = "1.0.91" tokio-util = { version = "0.7.4", features = ["full"] } -dioxus-html = { path = "../html", features = ["serialize"], version = "^0.3.0" } -dioxus-core = { path = "../core", features = ["serialize"], version = "^0.3.0" } -dioxus-interpreter-js = { path = "../interpreter", version = "0.3.0" } +interprocess = { version = "1.2.1", optional = true } # warp warp = { version = "0.3.3", optional = true } @@ -56,8 +58,9 @@ salvo = { version = "0.37.7", features = ["affix", "ws"] } tower = "0.4.13" [features] -default = [] +default = ["hot-reload"] # actix = ["actix-files", "actix-web", "actix-ws"] +hot-reload = ["interprocess"] [[example]] name = "axum" diff --git a/packages/liveview/src/hot_reload.rs b/packages/liveview/src/hot_reload.rs new file mode 100644 index 000000000..8385879e0 --- /dev/null +++ b/packages/liveview/src/hot_reload.rs @@ -0,0 +1,31 @@ +#![allow(dead_code)] + +use dioxus_core::Template; + +use interprocess::local_socket::LocalSocketStream; +use std::io::{BufRead, BufReader}; +use tokio::sync::mpsc::UnboundedSender; + +pub(crate) fn init(proxy: UnboundedSender>) { + std::thread::spawn(move || { + let temp_file = std::env::temp_dir().join("@dioxusin"); + if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) { + let mut buf_reader = BufReader::new(socket); + loop { + let mut buf = String::new(); + match buf_reader.read_line(&mut buf) { + Ok(_) => { + let template: Template<'static> = + serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); + proxy.send(template).unwrap(); + } + Err(err) => { + if err.kind() != std::io::ErrorKind::WouldBlock { + break; + } + } + } + } + } + }); +} diff --git a/packages/liveview/src/lib.rs b/packages/liveview/src/lib.rs index ffddf0272..6c4428c3c 100644 --- a/packages/liveview/src/lib.rs +++ b/packages/liveview/src/lib.rs @@ -18,6 +18,8 @@ pub mod adapters { pub use adapters::*; +#[cfg(all(feature = "hot-reload", debug_assertions))] +mod hot_reload; pub mod pool; use futures_util::{SinkExt, StreamExt}; pub use pool::*; diff --git a/packages/liveview/src/pool.rs b/packages/liveview/src/pool.rs index a25673d84..0f7598333 100644 --- a/packages/liveview/src/pool.rs +++ b/packages/liveview/src/pool.rs @@ -103,6 +103,13 @@ pub async fn run( where T: Send + 'static, { + #[cfg(all(feature = "hot-reload", debug_assertions))] + let mut hot_reload_rx = { + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + crate::hot_reload::init(tx); + rx + }; + let mut vdom = VirtualDom::new_with_props(app, props); // todo: use an efficient binary packed format for this @@ -122,6 +129,11 @@ where } loop { + #[cfg(all(feature = "hot-reload", debug_assertions))] + let hot_reload_wait = hot_reload_rx.recv(); + #[cfg(not(all(feature = "hot-reload", debug_assertions)))] + let hot_reload_wait = std::future::pending(); + tokio::select! { // poll any futures or suspense _ = vdom.wait_for_work() => {} @@ -138,6 +150,12 @@ where None => return Ok(()), } } + + new_template = hot_reload_wait => { + if let Some(new_template) = new_template { + vdom.replace_template(new_template); + } + } } let edits = vdom From 1b53d4585e0bf86c463199e5522d65917cc53eb2 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 11 Jan 2023 14:59:00 -0600 Subject: [PATCH 04/29] handle liveview sockets disconnecting --- packages/hot-reload/src/lib.rs | 53 +++++++++++++++++++++++++---- packages/liveview/src/hot_reload.rs | 4 ++- 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 4918b0c03..40438fe62 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -5,6 +5,7 @@ use std::{ sync::{Arc, Mutex}, }; +use dioxus_core::Template; pub use dioxus_hot_reload_macro::hot_reload; use dioxus_html::HtmlCtx; use dioxus_rsx::hot_reload::{FileMap, UpdateResult}; @@ -15,13 +16,30 @@ pub fn init(path: &'static str) { if let Ok(crate_dir) = PathBuf::from_str(path) { let temp_file = std::env::temp_dir().join("@dioxusin"); let channels = Arc::new(Mutex::new(Vec::new())); + let file_map = Arc::new(Mutex::new(FileMap::::new(crate_dir.clone()))); if let Ok(local_socket_stream) = LocalSocketListener::bind(temp_file.as_path()) { // listen for connections std::thread::spawn({ + let file_map = file_map.clone(); let channels = channels.clone(); move || { for connection in local_socket_stream.incoming() { - if let Ok(connection) = connection { + if let Ok(mut connection) = connection { + // send any templates than have changed before the socket connected + let templates: Vec<_> = { + file_map + .lock() + .unwrap() + .map + .values() + .filter_map(|(_, template_slot)| *template_slot) + .collect() + }; + for template in templates { + if !send_template(template, &mut connection) { + continue; + } + } channels.lock().unwrap().push(connection); println!("Connected to hot reloading 🚀"); } @@ -32,7 +50,6 @@ pub fn init(path: &'static str) { // watch for changes std::thread::spawn(move || { let mut last_update_time = chrono::Local::now().timestamp(); - let mut file_map = FileMap::::new(crate_dir.clone()); let (tx, rx) = std::sync::mpsc::channel(); @@ -58,13 +75,21 @@ pub fn init(path: &'static str) { } // find changes to the rsx in the file - match file_map.update_rsx(&path, crate_dir.as_path()) { + match file_map + .lock() + .unwrap() + .update_rsx(&path, crate_dir.as_path()) + { UpdateResult::UpdatedRsx(msgs) => { for msg in msgs { - for channel in channels.iter_mut() { - let msg = serde_json::to_string(&msg).unwrap(); - channel.write_all(msg.as_bytes()).unwrap(); - channel.write_all(&[b'\n']).unwrap(); + let mut i = 0; + while i < channels.len() { + let channel = &mut channels[i]; + if send_template(msg, channel) { + i += 1; + } else { + channels.remove(i); + } } } } @@ -82,3 +107,17 @@ pub fn init(path: &'static str) { } } } + +fn send_template(template: Template<'static>, channel: &mut impl Write) -> bool { + if let Ok(msg) = serde_json::to_string(&template) { + if channel.write_all(msg.as_bytes()).is_err() { + return false; + } + if channel.write_all(&[b'\n']).is_err() { + return false; + } + true + } else { + false + } +} diff --git a/packages/liveview/src/hot_reload.rs b/packages/liveview/src/hot_reload.rs index 8385879e0..17a8142c4 100644 --- a/packages/liveview/src/hot_reload.rs +++ b/packages/liveview/src/hot_reload.rs @@ -17,7 +17,9 @@ pub(crate) fn init(proxy: UnboundedSender>) { Ok(_) => { let template: Template<'static> = serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); - proxy.send(template).unwrap(); + if proxy.send(template).is_err() { + return; + } } Err(err) => { if err.kind() != std::io::ErrorKind::WouldBlock { From 042b67b61b901fb75a648c1726e91eac4392771a Mon Sep 17 00:00:00 2001 From: = Date: Wed, 11 Jan 2023 16:43:41 -0600 Subject: [PATCH 05/29] factor out a hot reloading connect function --- packages/desktop/Cargo.toml | 1 + packages/desktop/src/hot_reload.rs | 38 ----------------------------- packages/desktop/src/lib.rs | 13 +++++++--- packages/hot-reload/src/lib.rs | 31 +++++++++++++++++++++-- packages/liveview/Cargo.toml | 1 + packages/liveview/src/hot_reload.rs | 31 ----------------------- packages/liveview/src/lib.rs | 2 -- packages/liveview/src/pool.rs | 4 ++- packages/tui/Cargo.toml | 1 + packages/tui/src/hot_reload.rs | 31 ----------------------- packages/tui/src/lib.rs | 6 ++--- 11 files changed, 47 insertions(+), 112 deletions(-) delete mode 100644 packages/desktop/src/hot_reload.rs delete mode 100644 packages/liveview/src/hot_reload.rs delete mode 100644 packages/tui/src/hot_reload.rs diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index 16cc622c6..eb2f88fc9 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -15,6 +15,7 @@ keywords = ["dom", "ui", "gui", "react", "wasm"] dioxus-core = { path = "../core", version = "^0.3.0", features = ["serialize"] } dioxus-html = { path = "../html", features = ["serialize"], version = "^0.3.0" } dioxus-interpreter-js = { path = "../interpreter", version = "^0.3.0" } +dioxus-hot-reload = { path = "../hot-reload" } serde = "1.0.136" serde_json = "1.0.79" diff --git a/packages/desktop/src/hot_reload.rs b/packages/desktop/src/hot_reload.rs deleted file mode 100644 index 20907f59d..000000000 --- a/packages/desktop/src/hot_reload.rs +++ /dev/null @@ -1,38 +0,0 @@ -#![allow(dead_code)] - -use dioxus_core::Template; - -use interprocess::local_socket::LocalSocketStream; -use std::io::{BufRead, BufReader}; -use wry::application::{event_loop::EventLoopProxy, window::WindowId}; - -use crate::desktop_context::{EventData, UserWindowEvent}; - -pub(crate) fn init(proxy: EventLoopProxy) { - std::thread::spawn(move || { - let temp_file = std::env::temp_dir().join("@dioxusin"); - if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) { - let mut buf_reader = BufReader::new(socket); - loop { - let mut buf = String::new(); - match buf_reader.read_line(&mut buf) { - Ok(_) => { - let template: Template<'static> = - serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); - proxy - .send_event(UserWindowEvent( - EventData::TemplateUpdated(template), - unsafe { WindowId::dummy() }, - )) - .unwrap(); - } - Err(err) => { - if err.kind() != std::io::ErrorKind::WouldBlock { - break; - } - } - } - } - } - }); -} diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 7072f1dd0..0ec1f922c 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -12,9 +12,6 @@ mod protocol; mod waker; mod webview; -#[cfg(all(feature = "hot-reload", debug_assertions))] -mod hot_reload; - pub use cfg::Config; pub use desktop_context::{use_window, DesktopContext}; use desktop_context::{EventData, UserWindowEvent, WebviewQueue}; @@ -111,7 +108,15 @@ pub fn launch_with_props(root: Component

, props: P, cfg: Config) // Intialize hot reloading if it is enabled #[cfg(all(feature = "hot-reload", debug_assertions))] - hot_reload::init(proxy.clone()); + { + let proxy = proxy.clone(); + dioxus_hot_reload::connect(move |template| { + let _ = proxy.send_event(UserWindowEvent( + EventData::TemplateUpdated(template), + unsafe { WindowId::dummy() }, + )); + }); + } // We start the tokio runtime *on this thread* // Any future we poll later will use this runtime to spawn tasks and for IO diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 4918b0c03..554263c5f 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -1,16 +1,18 @@ use std::{ - io::Write, + io::{BufRead, BufReader, Write}, path::PathBuf, str::FromStr, sync::{Arc, Mutex}, }; +use dioxus_core::Template; pub use dioxus_hot_reload_macro::hot_reload; use dioxus_html::HtmlCtx; use dioxus_rsx::hot_reload::{FileMap, UpdateResult}; -use interprocess::local_socket::LocalSocketListener; +use interprocess::local_socket::{LocalSocketListener, LocalSocketStream}; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; +/// Initialize the hot reloading listener on the given path pub fn init(path: &'static str) { if let Ok(crate_dir) = PathBuf::from_str(path) { let temp_file = std::env::temp_dir().join("@dioxusin"); @@ -82,3 +84,28 @@ pub fn init(path: &'static str) { } } } + +/// Connect to the hot reloading listener. The callback provided will be called every time a template change is detected +pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { + std::thread::spawn(move || { + let temp_file = std::env::temp_dir().join("@dioxusin"); + if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) { + let mut buf_reader = BufReader::new(socket); + loop { + let mut buf = String::new(); + match buf_reader.read_line(&mut buf) { + Ok(_) => { + let template: Template<'static> = + serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); + f(template); + } + Err(err) => { + if err.kind() != std::io::ErrorKind::WouldBlock { + break; + } + } + } + } + } + }); +} diff --git a/packages/liveview/Cargo.toml b/packages/liveview/Cargo.toml index 53df88759..08a2b757c 100644 --- a/packages/liveview/Cargo.toml +++ b/packages/liveview/Cargo.toml @@ -16,6 +16,7 @@ license = "MIT/Apache-2.0" dioxus-html = { path = "../html", features = ["serialize"], version = "^0.3.0" } dioxus-core = { path = "../core", features = ["serialize"], version = "^0.3.0" } dioxus-interpreter-js = { path = "../interpreter", version = "0.3.0" } +dioxus-hot-reload = { path = "../hot-reload" } tokio = { version = "1.23.0", features = ["full"] } futures-util = { version = "0.3.25", default-features = false, features = [ diff --git a/packages/liveview/src/hot_reload.rs b/packages/liveview/src/hot_reload.rs deleted file mode 100644 index 8385879e0..000000000 --- a/packages/liveview/src/hot_reload.rs +++ /dev/null @@ -1,31 +0,0 @@ -#![allow(dead_code)] - -use dioxus_core::Template; - -use interprocess::local_socket::LocalSocketStream; -use std::io::{BufRead, BufReader}; -use tokio::sync::mpsc::UnboundedSender; - -pub(crate) fn init(proxy: UnboundedSender>) { - std::thread::spawn(move || { - let temp_file = std::env::temp_dir().join("@dioxusin"); - if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) { - let mut buf_reader = BufReader::new(socket); - loop { - let mut buf = String::new(); - match buf_reader.read_line(&mut buf) { - Ok(_) => { - let template: Template<'static> = - serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); - proxy.send(template).unwrap(); - } - Err(err) => { - if err.kind() != std::io::ErrorKind::WouldBlock { - break; - } - } - } - } - } - }); -} diff --git a/packages/liveview/src/lib.rs b/packages/liveview/src/lib.rs index 6c4428c3c..ffddf0272 100644 --- a/packages/liveview/src/lib.rs +++ b/packages/liveview/src/lib.rs @@ -18,8 +18,6 @@ pub mod adapters { pub use adapters::*; -#[cfg(all(feature = "hot-reload", debug_assertions))] -mod hot_reload; pub mod pool; use futures_util::{SinkExt, StreamExt}; pub use pool::*; diff --git a/packages/liveview/src/pool.rs b/packages/liveview/src/pool.rs index 0f7598333..3def78537 100644 --- a/packages/liveview/src/pool.rs +++ b/packages/liveview/src/pool.rs @@ -106,7 +106,9 @@ where #[cfg(all(feature = "hot-reload", debug_assertions))] let mut hot_reload_rx = { let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); - crate::hot_reload::init(tx); + dioxus_hot_reload::connect(move |template| { + let _ = tx.send(template); + }); rx }; diff --git a/packages/tui/Cargo.toml b/packages/tui/Cargo.toml index 1e35f8b3e..d6c96cfd3 100644 --- a/packages/tui/Cargo.toml +++ b/packages/tui/Cargo.toml @@ -18,6 +18,7 @@ dioxus-core = { path = "../core", version = "^0.3.0", features = ["serialize"] } dioxus-html = { path = "../html", version = "^0.3.0" } dioxus-native-core = { path = "../native-core", version = "^0.2.0" } dioxus-native-core-macro = { path = "../native-core-macro", version = "^0.2.0" } +dioxus-hot-reload = { path = "../hot-reload" } tui = "0.17.0" crossterm = "0.23.0" diff --git a/packages/tui/src/hot_reload.rs b/packages/tui/src/hot_reload.rs deleted file mode 100644 index 8385879e0..000000000 --- a/packages/tui/src/hot_reload.rs +++ /dev/null @@ -1,31 +0,0 @@ -#![allow(dead_code)] - -use dioxus_core::Template; - -use interprocess::local_socket::LocalSocketStream; -use std::io::{BufRead, BufReader}; -use tokio::sync::mpsc::UnboundedSender; - -pub(crate) fn init(proxy: UnboundedSender>) { - std::thread::spawn(move || { - let temp_file = std::env::temp_dir().join("@dioxusin"); - if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) { - let mut buf_reader = BufReader::new(socket); - loop { - let mut buf = String::new(); - match buf_reader.read_line(&mut buf) { - Ok(_) => { - let template: Template<'static> = - serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); - proxy.send(template).unwrap(); - } - Err(err) => { - if err.kind() != std::io::ErrorKind::WouldBlock { - break; - } - } - } - } - } - }); -} diff --git a/packages/tui/src/lib.rs b/packages/tui/src/lib.rs index 6af02e993..a8cd295d3 100644 --- a/packages/tui/src/lib.rs +++ b/packages/tui/src/lib.rs @@ -28,8 +28,6 @@ use tui::{backend::CrosstermBackend, layout::Rect, Terminal}; mod config; mod focus; mod hooks; -#[cfg(all(feature = "hot-reload", debug_assertions))] -mod hot_reload; mod layout; mod node; pub mod prelude; @@ -150,7 +148,9 @@ fn render_vdom( #[cfg(all(feature = "hot-reload", debug_assertions))] let mut hot_reload_rx = { let (hot_reload_tx, hot_reload_rx) = unbounded_channel::>(); - hot_reload::init(hot_reload_tx); + dioxus_hot_reload::connect(move |template| { + let _ = hot_reload_tx.send(template); + }); hot_reload_rx }; let mut terminal = (!cfg.headless).then(|| { From 9e45cbe4a779507ba2308bb86130ab86ae538f99 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 11 Jan 2023 18:51:09 -0600 Subject: [PATCH 06/29] remove the hot-reload-macro crate --- Cargo.toml | 1 - packages/hot-reload-macro/Cargo.toml | 13 ------------- packages/hot-reload-macro/src/lib.rs | 7 ------- packages/hot-reload/Cargo.toml | 1 - packages/hot-reload/src/lib.rs | 14 ++++++++++++-- 5 files changed, 12 insertions(+), 24 deletions(-) delete mode 100644 packages/hot-reload-macro/Cargo.toml delete mode 100644 packages/hot-reload-macro/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index ebfe288c5..c00f8f948 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,6 @@ members = [ "packages/rsx-rosetta", "packages/signals", "packages/hot-reload", - "packages/hot-reload-macro", "docs/guide", ] diff --git a/packages/hot-reload-macro/Cargo.toml b/packages/hot-reload-macro/Cargo.toml deleted file mode 100644 index 009c6501a..000000000 --- a/packages/hot-reload-macro/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "dioxus-hot-reload-macro" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -syn = { version = "1.0.107", features = ["full"] } -proc-macro2 = { version = "1.0" } - -[lib] -proc-macro = true \ No newline at end of file diff --git a/packages/hot-reload-macro/src/lib.rs b/packages/hot-reload-macro/src/lib.rs deleted file mode 100644 index 211be00cf..000000000 --- a/packages/hot-reload-macro/src/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -use proc_macro::TokenStream; -use syn::__private::quote::quote; - -#[proc_macro] -pub fn hot_reload(_: TokenStream) -> TokenStream { - quote!(dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"))).into() -} diff --git a/packages/hot-reload/Cargo.toml b/packages/hot-reload/Cargo.toml index 5c9f34826..d6088a109 100644 --- a/packages/hot-reload/Cargo.toml +++ b/packages/hot-reload/Cargo.toml @@ -6,7 +6,6 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -dioxus-hot-reload-macro = { path = "../hot-reload-macro" } dioxus-rsx = { path = "../rsx" } dioxus-core = { path = "../core", features = ["serialize"] } dioxus-html = { path = "../html", features = ["hot-reload-context"] } diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 554263c5f..14cc8e9c2 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -6,14 +6,13 @@ use std::{ }; use dioxus_core::Template; -pub use dioxus_hot_reload_macro::hot_reload; use dioxus_html::HtmlCtx; use dioxus_rsx::hot_reload::{FileMap, UpdateResult}; use interprocess::local_socket::{LocalSocketListener, LocalSocketStream}; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; /// Initialize the hot reloading listener on the given path -pub fn init(path: &'static str) { +pub fn init(path: &'static str, listening_paths: &'static [&'static str]) { if let Ok(crate_dir) = PathBuf::from_str(path) { let temp_file = std::env::temp_dir().join("@dioxusin"); let channels = Arc::new(Mutex::new(Vec::new())); @@ -109,3 +108,14 @@ pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { } }); } + +#[macro_export] +macro_rules! hot_reload { + () => { + dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[]) + }; + + ($($paths: literal,)*,?) => { + dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[$($path,)*]) + }; +} From 19aaa0ee5b1e68ba428d1f7dc6e295592084d023 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 11 Jan 2023 21:06:00 -0600 Subject: [PATCH 07/29] allow watching arbitrary paths --- packages/hot-reload/src/lib.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index e0c547578..586c3c95b 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -12,8 +12,8 @@ use interprocess::local_socket::{LocalSocketListener, LocalSocketStream}; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; /// Initialize the hot reloading listener on the given path -pub fn init(path: &'static str, listening_paths: &'static [&'static str]) { - if let Ok(crate_dir) = PathBuf::from_str(path) { +pub fn init(root_path: &'static str, listening_paths: &'static [&'static str]) { + if let Ok(crate_dir) = PathBuf::from_str(root_path) { let temp_file = std::env::temp_dir().join("@dioxusin"); let channels = Arc::new(Mutex::new(Vec::new())); let file_map = Arc::new(Mutex::new(FileMap::::new(crate_dir.clone()))); @@ -55,12 +55,12 @@ pub fn init(path: &'static str, listening_paths: &'static [&'static str]) { let mut watcher = RecommendedWatcher::new(tx, notify::Config::default()).unwrap(); - let mut examples_path = crate_dir.clone(); - examples_path.push("examples"); - let _ = watcher.watch(&examples_path, RecursiveMode::Recursive); - let mut src_path = crate_dir.clone(); - src_path.push("src"); - let _ = watcher.watch(&src_path, RecursiveMode::Recursive); + for path in listening_paths { + if let Ok(path) = PathBuf::from_str(path) { + let examples_path = crate_dir.join(path); + let _ = watcher.watch(&examples_path, RecursiveMode::Recursive); + } + } for evt in rx { // Give time for the change to take effect before reading the file @@ -147,13 +147,17 @@ pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { }); } +/// Start the hot reloading server +/// +/// Pass any number of paths to listen for changes on relative to the crate root as strings. +/// If no paths are passed, it will listen on the src and examples folders. #[macro_export] macro_rules! hot_reload { () => { - dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[]) + dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &["src", "examples"]) }; - ($($paths: literal,)*,?) => { - dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[$($path,)*]) + ($($paths: literal),*) => { + dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[$($paths),*]) }; } From 82048737f4a1b2fece22b92ae70b97d6dc409c7d Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 08:47:33 -0600 Subject: [PATCH 08/29] fix the macro export and WIP hot reloading docs --- docs/guide/src/en/SUMMARY.md | 2 +- .../src/en/getting_started/hot_reload.md | 49 ++++++++++++++++--- packages/dioxus/Cargo.toml | 4 +- packages/dioxus/src/lib.rs | 3 ++ packages/hot-reload/src/lib.rs | 4 +- 5 files changed, 51 insertions(+), 11 deletions(-) diff --git a/docs/guide/src/en/SUMMARY.md b/docs/guide/src/en/SUMMARY.md index 83840fe90..f9f31ed52 100644 --- a/docs/guide/src/en/SUMMARY.md +++ b/docs/guide/src/en/SUMMARY.md @@ -5,11 +5,11 @@ - [Getting Started](getting_started/index.md) - [Desktop](getting_started/desktop.md) - [Web](getting_started/web.md) - - [Hot Reload](getting_started/hot_reload.md) - [Server-Side Rendering](getting_started/ssr.md) - [Liveview](getting_started/liveview.md) - [Terminal UI](getting_started/tui.md) - [Mobile](getting_started/mobile.md) + - [Hot Reloading](getting_started/hot_reload.md) - [Describing the UI](describing_ui/index.md) - [Special Attributes](describing_ui/special_attributes.md) - [Components](describing_ui/components.md) diff --git a/docs/guide/src/en/getting_started/hot_reload.md b/docs/guide/src/en/getting_started/hot_reload.md index 823baa179..8c4d4310d 100644 --- a/docs/guide/src/en/getting_started/hot_reload.md +++ b/docs/guide/src/en/getting_started/hot_reload.md @@ -2,20 +2,53 @@ 1. Hot reloading allows much faster iteration times inside of rsx calls by interpreting them and streaming the edits. 2. It is useful when changing the styling/layout of a program, but will not help with changing the logic of a program. -3. Currently the cli only implements hot reloading for the web renderer. +3. Currently the cli only implements hot reloading for the web renderer. For TUI, desktop, and liveview you can use the hot reload macro. + +# Web + +For the web renderer, you can use the dioxus cli to serve your application with hot reloading enabled. + +## Setup -# Setup Install [dioxus-cli](https://github.com/DioxusLabs/cli). Hot reloading is automatically enabled when using the web renderer on debug builds. -# Usage -1. run: -``` +## Usage + +1. Run: +```bash dioxus serve --hot-reload ``` -2. change some code within a rsx macro -3. open your localhost in a browser -4. save and watch the style change without recompiling +2. Change some code within a rsx or render macro +3. Open your localhost in a browser +4. Save and watch the style change without recompiling + +# Desktop/Liveview/TUI + +For desktop, LiveView, and tui, you can place the hot reload macro before your app runs to enable hot reloading. + +## Setup + +Add the following to your main function: + +```rust +fn main() { + dioxus::hot_reload_init!(); + // launch your application +} +``` + +## Usage +1. Run: +```bash +cargo run +``` +2. Change some code within a rsx or render macro +3. Save and watch the style change without recompiling + +## Custom renders + +For custom renderers # Limitations 1. The interpreter can only use expressions that existed on the last full recompile. If you introduce a new variable or expression to the rsx call, it will trigger a full recompile to capture the expression. diff --git a/packages/dioxus/Cargo.toml b/packages/dioxus/Cargo.toml index ceab90a1b..0360b207f 100644 --- a/packages/dioxus/Cargo.toml +++ b/packages/dioxus/Cargo.toml @@ -17,12 +17,14 @@ dioxus-html = { path = "../html", version = "^0.3.0", optional = true } dioxus-core-macro = { path = "../core-macro", version = "^0.3.0", optional = true } dioxus-hooks = { path = "../hooks", version = "^0.3.0", optional = true } dioxus-rsx = { path = "../rsx", version = "0.0.2", optional = true } +dioxus-hot-reload = { path = "../hot-reload", version = "0.1.0", optional = true } [features] -default = ["macro", "hooks", "html"] +default = ["macro", "hooks", "html", "hot-reload"] macro = ["dioxus-core-macro", "dioxus-rsx"] html = ["dioxus-html"] hooks = ["dioxus-hooks"] +hot-reload = ["dioxus-hot-reload"] [dev-dependencies] diff --git a/packages/dioxus/src/lib.rs b/packages/dioxus/src/lib.rs index fed3d2bd5..fe181bf14 100644 --- a/packages/dioxus/src/lib.rs +++ b/packages/dioxus/src/lib.rs @@ -31,4 +31,7 @@ pub mod prelude { #[cfg(feature = "html")] pub use dioxus_elements::{prelude::*, GlobalAttributes, SvgAttributes}; + + #[cfg(feature = "hot-reload")] + pub use dioxus_hot_reload::hot_reload_init; } diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 586c3c95b..6ac5c2c35 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -152,7 +152,7 @@ pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { /// Pass any number of paths to listen for changes on relative to the crate root as strings. /// If no paths are passed, it will listen on the src and examples folders. #[macro_export] -macro_rules! hot_reload { +macro_rules! hot_reload_init_inner { () => { dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &["src", "examples"]) }; @@ -161,3 +161,5 @@ macro_rules! hot_reload { dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[$($paths),*]) }; } + +pub use hot_reload_init_inner as hot_reload_init; From 9be1df1451d2093bec76d8d099ca299eb4c1d952 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 10:32:45 -0600 Subject: [PATCH 09/29] allow disabling logging --- .../src/en/getting_started/hot_reload.md | 12 ++---- packages/hot-reload/src/lib.rs | 38 ++++++++++++++----- 2 files changed, 32 insertions(+), 18 deletions(-) diff --git a/docs/guide/src/en/getting_started/hot_reload.md b/docs/guide/src/en/getting_started/hot_reload.md index 8c4d4310d..bd0cb65ac 100644 --- a/docs/guide/src/en/getting_started/hot_reload.md +++ b/docs/guide/src/en/getting_started/hot_reload.md @@ -2,7 +2,7 @@ 1. Hot reloading allows much faster iteration times inside of rsx calls by interpreting them and streaming the edits. 2. It is useful when changing the styling/layout of a program, but will not help with changing the logic of a program. -3. Currently the cli only implements hot reloading for the web renderer. For TUI, desktop, and liveview you can use the hot reload macro. +3. Currently the cli only implements hot reloading for the web renderer. For TUI, desktop, and LiveView you can use the hot reload macro instead. # Web @@ -25,7 +25,7 @@ dioxus serve --hot-reload # Desktop/Liveview/TUI -For desktop, LiveView, and tui, you can place the hot reload macro before your app runs to enable hot reloading. +For desktop, LiveView, and tui, you can place the hot reload macro at the top of your main function to enable hot reloading. ## Setup @@ -33,7 +33,7 @@ Add the following to your main function: ```rust fn main() { - dioxus::hot_reload_init!(); + hot_reload_init!(); // launch your application } ``` @@ -46,10 +46,6 @@ cargo run 2. Change some code within a rsx or render macro 3. Save and watch the style change without recompiling -## Custom renders - -For custom renderers - # Limitations 1. The interpreter can only use expressions that existed on the last full recompile. If you introduce a new variable or expression to the rsx call, it will trigger a full recompile to capture the expression. -2. Components and Iterators can contain arbitrary rust code and will trigger a full recompile when changed. \ No newline at end of file +2. Components and Iterators can contain arbitrary rust code and will trigger a full recompile when changed. diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 6ac5c2c35..36ba0eaf9 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -12,7 +12,7 @@ use interprocess::local_socket::{LocalSocketListener, LocalSocketStream}; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; /// Initialize the hot reloading listener on the given path -pub fn init(root_path: &'static str, listening_paths: &'static [&'static str]) { +pub fn init(root_path: &'static str, listening_paths: &'static [&'static str], log: bool) { if let Ok(crate_dir) = PathBuf::from_str(root_path) { let temp_file = std::env::temp_dir().join("@dioxusin"); let channels = Arc::new(Mutex::new(Vec::new())); @@ -41,7 +41,9 @@ pub fn init(root_path: &'static str, listening_paths: &'static [&'static str]) { } } channels.lock().unwrap().push(connection); - println!("Connected to hot reloading 🚀"); + if log { + println!("Connected to hot reloading 🚀"); + } } } } @@ -94,7 +96,11 @@ pub fn init(root_path: &'static str, listening_paths: &'static [&'static str]) { } } UpdateResult::NeedsRebuild => { - println!("Rebuild needed... shutting down hot reloading"); + if log { + println!( + "Rebuild needed... shutting down hot reloading" + ); + } return; } } @@ -152,14 +158,26 @@ pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { /// Pass any number of paths to listen for changes on relative to the crate root as strings. /// If no paths are passed, it will listen on the src and examples folders. #[macro_export] -macro_rules! hot_reload_init_inner { - () => { - dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &["src", "examples"]) +macro_rules! hot_reload_init { + ($($t: ident)*) => { + #[cfg(debug_assertions)] + dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &["src", "examples"], hot_reload_init!(log: $($t)*)) }; - ($($paths: literal),*) => { - dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[$($paths),*]) + ($($paths: literal),* $(,)? $($t: ident)*) => { + #[cfg(debug_assertions)] + dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[$($paths),*], hot_reload_init!(log: $($t)*)) + }; + + (log:) => { + false + }; + + (log: enable logging) => { + true + }; + + (log: disable logging) => { + false }; } - -pub use hot_reload_init_inner as hot_reload_init; From c49c59b8b225ee1eee4e37c92b03251401877985 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 10:32:50 -0600 Subject: [PATCH 10/29] add readme --- packages/hot-reload/README.md | 142 ++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 packages/hot-reload/README.md diff --git a/packages/hot-reload/README.md b/packages/hot-reload/README.md new file mode 100644 index 000000000..fed458361 --- /dev/null +++ b/packages/hot-reload/README.md @@ -0,0 +1,142 @@ +# `dioxus-hot-reload`: Hot Reloading Utilites for Dioxus + + +[![Crates.io][crates-badge]][crates-url] +[![MIT licensed][mit-badge]][mit-url] +[![Build Status][actions-badge]][actions-url] +[![Discord chat][discord-badge]][discord-url] + +[crates-badge]: https://img.shields.io/crates/v/dioxus-hot-reload.svg +[crates-url]: https://crates.io/crates/dioxus-hot-reload + +[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg +[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE + +[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg +[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster + +[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square +[discord-url]: https://discord.gg/XgGxMSkvUM + +[Website](https://dioxuslabs.com) | +[Guides](https://dioxuslabs.com/guide/) | +[API Docs](https://docs.rs/dioxus-hot-reload/latest/dioxus_hot_reload) | +[Chat](https://discord.gg/XgGxMSkvUM) + + +## Overview + +Dioxus supports hot reloading for static parts of rsx macros. This enables changing the styling of your application without recompiling the rust code. This is useful for rapid iteration on the styling of your application. + + +Hot reloading could update the following change without recompiling: +```rust +rsx! { + div { + "Count: {count}", + } +} +``` +=> +```rust +rsx! { + div { + color: "red", + font_size: "2em", + "Count: {count}", + } +} +``` + +But it could not update the following change: +```rust +rsx! { + div { + "Count: {count}", + } +} +``` +=> +```rust +rsx! { + div { + "Count: {count*2}", + onclick: |_| println!("clicked"), + } +} +``` + +## Usage + +> For hot relaoding with the web renderer, see the [dioxus-cli](https://github.com/DioxusLabs/cli) project. + +For renderers that support hot reloading add this to your main function before you launch your app to start the hot reloading server: + +```rust +fn main(){ + hot_reload_init!(); + // launch your application +} +``` + +The dev server watches on the `src` and `examples` folders in the crate directory by default. To watch on custom paths pass the paths into the hot relaod macro: + +```rust +fn main(){ + hot_reload_init!("src", "examples", "assets"); + // launch your application +} +``` + +By default the hot reloading server will output some logs in the console, to disable these logs pass the `disable logging` flag into the macro: + +```rust +fn main(){ + hot_reload_init!("src", "examples", "assets", disable logging); + // launch your application +} +``` + +## Implementing hot reloading for a custom renderer + +To add hot reloading support to your custom renderer you can use the connect function. This will connect to the dev server you just need to provide a way to transfer `Template`s to the `VirtualDom`. Once you implement this your users can use the hot_reload_init function just like any other render. + +```rust +async fn launch(app: Component) { + let mut vdom = VirtualDom::new(app); + // ... + + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + dioxus_hot_reload::connect(move |template| { + let _ = tx.send(template); + }); + + loop { + tokio::select! { + Some(template) = rx.recv() => { + // update the template in the virtual dom + vdom.replace_template(template); + } + _ = vdom.wait_for_work() => { + // ... + } + } + let mutations = vdom.render_immediate(); + // apply the mutations to the dom + } +} +``` + +## Contributing + +- Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues). +- Join the discord and ask questions! + +## License +This project is licensed under the [MIT license]. + +[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in Dioxus by you shall be licensed as MIT without any additional +terms or conditions. From 351b9fab6f37d2bce3359ac25cabc397e4295cc7 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 10:52:24 -0600 Subject: [PATCH 11/29] allow custom namespaces --- Cargo.toml | 1 - .../src/en/getting_started/hot_reload.md | 1 + packages/dioxus/src/lib.rs | 2 +- packages/hot-reload/README.md | 11 ++++++ packages/hot-reload/src/lib.rs | 39 +++++++++++++------ 5 files changed, 41 insertions(+), 13 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c00f8f948..e32940e18 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,6 @@ publish = false dioxus = { path = "./packages/dioxus" } dioxus-desktop = { path = "./packages/desktop", features = ["transparent"] } dioxus-ssr = { path = "./packages/ssr" } -dioxus-hot-reload = { path = "./packages/hot-reload" } dioxus-router = { path = "./packages/router" } dioxus-signals = { path = "./packages/signals" } fermi = { path = "./packages/fermi" } diff --git a/docs/guide/src/en/getting_started/hot_reload.md b/docs/guide/src/en/getting_started/hot_reload.md index bd0cb65ac..f2b12c983 100644 --- a/docs/guide/src/en/getting_started/hot_reload.md +++ b/docs/guide/src/en/getting_started/hot_reload.md @@ -26,6 +26,7 @@ dioxus serve --hot-reload # Desktop/Liveview/TUI For desktop, LiveView, and tui, you can place the hot reload macro at the top of your main function to enable hot reloading. +Hot reloading is automatically enabled on debug builds. ## Setup diff --git a/packages/dioxus/src/lib.rs b/packages/dioxus/src/lib.rs index fe181bf14..4a7d41ea6 100644 --- a/packages/dioxus/src/lib.rs +++ b/packages/dioxus/src/lib.rs @@ -33,5 +33,5 @@ pub mod prelude { pub use dioxus_elements::{prelude::*, GlobalAttributes, SvgAttributes}; #[cfg(feature = "hot-reload")] - pub use dioxus_hot_reload::hot_reload_init; + pub use dioxus_hot_reload::{self, hot_reload_init}; } diff --git a/packages/hot-reload/README.md b/packages/hot-reload/README.md index fed458361..534bbbc98 100644 --- a/packages/hot-reload/README.md +++ b/packages/hot-reload/README.md @@ -97,6 +97,17 @@ fn main(){ } ``` +If you are using a namespace other than html, you can implement the [HotReloadingContext](https://docs.rs/dioxus-rsx/latest/dioxus_rsx/trait.HotReloadingContext.html) trait to provide a mapping between the rust names of your elements/attributes and the resultsing strings. + +You can then provide the Context to the macro to make hot reloading work with your custom namespace: + +```rust +fn main(){ + hot_reload_init!(@MyNamespace /*more configeration*/); + // launch your application +} +``` + ## Implementing hot reloading for a custom renderer To add hot reloading support to your custom renderer you can use the connect function. This will connect to the dev server you just need to provide a way to transfer `Template`s to the `VirtualDom`. Once you implement this your users can use the hot_reload_init function just like any other render. diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 36ba0eaf9..ef87d4d21 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -6,17 +6,26 @@ use std::{ }; use dioxus_core::Template; -use dioxus_html::HtmlCtx; -use dioxus_rsx::hot_reload::{FileMap, UpdateResult}; +use dioxus_rsx::{ + hot_reload::{FileMap, UpdateResult}, + HotReloadingContext, +}; use interprocess::local_socket::{LocalSocketListener, LocalSocketStream}; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; +#[cfg(debug_assertions)] +pub use dioxus_html::HtmlCtx; + /// Initialize the hot reloading listener on the given path -pub fn init(root_path: &'static str, listening_paths: &'static [&'static str], log: bool) { +pub fn init( + root_path: &'static str, + listening_paths: &'static [&'static str], + log: bool, +) { if let Ok(crate_dir) = PathBuf::from_str(root_path) { let temp_file = std::env::temp_dir().join("@dioxusin"); let channels = Arc::new(Mutex::new(Vec::new())); - let file_map = Arc::new(Mutex::new(FileMap::::new(crate_dir.clone()))); + let file_map = Arc::new(Mutex::new(FileMap::::new(crate_dir.clone()))); if let Ok(local_socket_stream) = LocalSocketListener::bind(temp_file.as_path()) { // listen for connections std::thread::spawn({ @@ -159,25 +168,33 @@ pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { /// If no paths are passed, it will listen on the src and examples folders. #[macro_export] macro_rules! hot_reload_init { - ($($t: ident)*) => { + ($(@ $ctx:ident)? $($t: ident)*) => { #[cfg(debug_assertions)] - dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &["src", "examples"], hot_reload_init!(log: $($t)*)) + dioxus_hot_reload::init::(core::env!("CARGO_MANIFEST_DIR"), &["src", "examples"], hot_reload_init!(@log: $($t)*)) }; - ($($paths: literal),* $(,)? $($t: ident)*) => { + ($(@ $ctx:ident)? $($paths: literal),* $(,)? $($t: ident)*) => { #[cfg(debug_assertions)] - dioxus_hot_reload::init(core::env!("CARGO_MANIFEST_DIR"), &[$($paths),*], hot_reload_init!(log: $($t)*)) + dioxus_hot_reload::init::(core::env!("CARGO_MANIFEST_DIR"), &[$($paths),*], hot_reload_init!(@log: $($t)*)) }; - (log:) => { + (@log:) => { false }; - (log: enable logging) => { + (@log: enable logging) => { true }; - (log: disable logging) => { + (@log: disable logging) => { false }; + + (@ctx: $ctx: ident) => { + $ctx + }; + + (@ctx: ) => { + dioxus_hot_reload::HtmlCtx + }; } From 6b4a300880b2ae1807949c5c6a2c4ae1a6798994 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 10:58:12 -0600 Subject: [PATCH 12/29] doc formatting and cleanup --- docs/guide/src/en/getting_started/hot_reload.md | 9 ++------- packages/hot-reload/README.md | 8 ++++---- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/docs/guide/src/en/getting_started/hot_reload.md b/docs/guide/src/en/getting_started/hot_reload.md index f2b12c983..9700752f4 100644 --- a/docs/guide/src/en/getting_started/hot_reload.md +++ b/docs/guide/src/en/getting_started/hot_reload.md @@ -5,16 +5,13 @@ 3. Currently the cli only implements hot reloading for the web renderer. For TUI, desktop, and LiveView you can use the hot reload macro instead. # Web - For the web renderer, you can use the dioxus cli to serve your application with hot reloading enabled. ## Setup - Install [dioxus-cli](https://github.com/DioxusLabs/cli). Hot reloading is automatically enabled when using the web renderer on debug builds. ## Usage - 1. Run: ```bash dioxus serve --hot-reload @@ -24,12 +21,10 @@ dioxus serve --hot-reload 4. Save and watch the style change without recompiling # Desktop/Liveview/TUI - For desktop, LiveView, and tui, you can place the hot reload macro at the top of your main function to enable hot reloading. Hot reloading is automatically enabled on debug builds. ## Setup - Add the following to your main function: ```rust @@ -48,5 +43,5 @@ cargo run 3. Save and watch the style change without recompiling # Limitations -1. The interpreter can only use expressions that existed on the last full recompile. If you introduce a new variable or expression to the rsx call, it will trigger a full recompile to capture the expression. -2. Components and Iterators can contain arbitrary rust code and will trigger a full recompile when changed. +1. The interpreter can only use expressions that existed on the last full recompile. If you introduce a new variable or expression to the rsx call, it will require a full recompile to capture the expression. +2. Components, Iterators, and some attributes can contain arbitrary rust code and will trigger a full recompile when changed. diff --git a/packages/hot-reload/README.md b/packages/hot-reload/README.md index 534bbbc98..4e8c7d880 100644 --- a/packages/hot-reload/README.md +++ b/packages/hot-reload/README.md @@ -68,9 +68,9 @@ rsx! { ## Usage -> For hot relaoding with the web renderer, see the [dioxus-cli](https://github.com/DioxusLabs/cli) project. +> This crate implements hot reloading for native compilation targets not WASM. For hot relaoding with the web renderer, see the [dioxus-cli](https://github.com/DioxusLabs/cli) project. -For renderers that support hot reloading add this to your main function before you launch your app to start the hot reloading server: +Add this to the top of your main function on any renderer that supports hot reloading to start the hot reloading server: ```rust fn main(){ @@ -79,7 +79,7 @@ fn main(){ } ``` -The dev server watches on the `src` and `examples` folders in the crate directory by default. To watch on custom paths pass the paths into the hot relaod macro: +By default the dev server watches on the `src` and `examples` folders in the root crate directory. To watch on custom paths pass the paths into the hot relaod macro: ```rust fn main(){ @@ -108,7 +108,7 @@ fn main(){ } ``` -## Implementing hot reloading for a custom renderer +## Implementing Hot Reloading for a Custom Renderer To add hot reloading support to your custom renderer you can use the connect function. This will connect to the dev server you just need to provide a way to transfer `Template`s to the `VirtualDom`. Once you implement this your users can use the hot_reload_init function just like any other render. From 4e180bd19ec9b82682ee1eaa9a00fdcef161a467 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 11:00:16 -0600 Subject: [PATCH 13/29] remmove comment --- packages/tui/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/tui/src/lib.rs b/packages/tui/src/lib.rs index a8cd295d3..8950a7245 100644 --- a/packages/tui/src/lib.rs +++ b/packages/tui/src/lib.rs @@ -275,7 +275,6 @@ fn render_vdom( // if we have a new template, replace the old one if let Some(template) = new_templete { - // println!("reloading template"); vdom.replace_template(template); } From 97b9f422e15826f5e1b538274fad06786b01f31b Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 11:10:16 -0600 Subject: [PATCH 14/29] log path errors --- packages/hot-reload/src/lib.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index ef87d4d21..8b482c2ce 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -67,9 +67,22 @@ pub fn init( let mut watcher = RecommendedWatcher::new(tx, notify::Config::default()).unwrap(); for path in listening_paths { - if let Ok(path) = PathBuf::from_str(path) { - let examples_path = crate_dir.join(path); - let _ = watcher.watch(&examples_path, RecursiveMode::Recursive); + match PathBuf::from_str(path) { + Ok(path) => { + let full_path = crate_dir.join(path); + if let Err(err) = watcher.watch(&full_path, RecursiveMode::Recursive) { + if log { + println!( + "hot reloading failed to start watching {full_path:?}:\n{err:?}", + ); + } + } + } + Err(err) => { + if log { + println!("hot reloading failed to create path:\n{:?}", err); + } + } } } From f71ab650e86f32cc8839dd289f045d0a03d17b1b Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 11:41:46 -0600 Subject: [PATCH 15/29] don't include inteprocess in wasm builds --- packages/dioxus/Cargo.toml | 2 ++ packages/dioxus/src/lib.rs | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/dioxus/Cargo.toml b/packages/dioxus/Cargo.toml index 0360b207f..afe0ea0c3 100644 --- a/packages/dioxus/Cargo.toml +++ b/packages/dioxus/Cargo.toml @@ -17,6 +17,8 @@ dioxus-html = { path = "../html", version = "^0.3.0", optional = true } dioxus-core-macro = { path = "../core-macro", version = "^0.3.0", optional = true } dioxus-hooks = { path = "../hooks", version = "^0.3.0", optional = true } dioxus-rsx = { path = "../rsx", version = "0.0.2", optional = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] dioxus-hot-reload = { path = "../hot-reload", version = "0.1.0", optional = true } [features] diff --git a/packages/dioxus/src/lib.rs b/packages/dioxus/src/lib.rs index 4a7d41ea6..5d1371f27 100644 --- a/packages/dioxus/src/lib.rs +++ b/packages/dioxus/src/lib.rs @@ -32,6 +32,6 @@ pub mod prelude { #[cfg(feature = "html")] pub use dioxus_elements::{prelude::*, GlobalAttributes, SvgAttributes}; - #[cfg(feature = "hot-reload")] + #[cfg(all(not(target_arch = "wasm32"), feature = "hot-reload"))] pub use dioxus_hot_reload::{self, hot_reload_init}; } From fc28050da629e59aabd9ae0d52e37b10a21c7768 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 12:09:43 -0600 Subject: [PATCH 16/29] pass clippy --- packages/hot-reload/src/lib.rs | 40 ++++++++++++++++------------------ 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 8b482c2ce..8c40aa2a9 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -32,28 +32,26 @@ pub fn init( let file_map = file_map.clone(); let channels = channels.clone(); move || { - for connection in local_socket_stream.incoming() { - if let Ok(mut connection) = connection { - // send any templates than have changed before the socket connected - let templates: Vec<_> = { - file_map - .lock() - .unwrap() - .map - .values() - .filter_map(|(_, template_slot)| *template_slot) - .collect() - }; - for template in templates { - if !send_template(template, &mut connection) { - continue; - } - } - channels.lock().unwrap().push(connection); - if log { - println!("Connected to hot reloading 🚀"); + for mut connection in local_socket_stream.incoming().flatten() { + // send any templates than have changed before the socket connected + let templates: Vec<_> = { + file_map + .lock() + .unwrap() + .map + .values() + .filter_map(|(_, template_slot)| *template_slot) + .collect() + }; + for template in templates { + if !send_template(template, &mut connection) { + continue; } } + channels.lock().unwrap().push(connection); + if log { + println!("Connected to hot reloading 🚀"); + } } } }); @@ -102,7 +100,7 @@ pub fn init( match file_map .lock() .unwrap() - .update_rsx(&path, crate_dir.as_path()) + .update_rsx(path, crate_dir.as_path()) { UpdateResult::UpdatedRsx(msgs) => { for msg in msgs { From 3c229b38bc0f42fa81f2c17b22b6d06c54ac9342 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 12 Jan 2023 18:51:08 -0600 Subject: [PATCH 17/29] make shutdown message more clear --- packages/hot-reload/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 8c40aa2a9..9543911b2 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -118,7 +118,7 @@ pub fn init( UpdateResult::NeedsRebuild => { if log { println!( - "Rebuild needed... shutting down hot reloading" + "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." ); } return; From b3d119b8150d862d22aeb1149f7f43780746fd8e Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 16:13:07 -0600 Subject: [PATCH 18/29] Provide option to do full rebuilds when nessisary --- packages/desktop/src/desktop_context.rs | 4 +- packages/desktop/src/lib.rs | 17 +- packages/hot-reload/Cargo.toml | 3 + packages/hot-reload/src/lib.rs | 251 +++++++++++++++++------- packages/liveview/src/pool.rs | 13 +- packages/tui/src/lib.rs | 24 ++- 6 files changed, 217 insertions(+), 95 deletions(-) diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index 720223e6c..baa658b28 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -8,8 +8,8 @@ use crate::events::IpcMessage; use crate::Config; use crate::WebviewHandler; use dioxus_core::ScopeState; -use dioxus_core::Template; use dioxus_core::VirtualDom; +use dioxus_hot_reload::HotReloadMsg; use serde_json::Value; use wry::application::event_loop::EventLoopProxy; use wry::application::event_loop::EventLoopWindowTarget; @@ -263,7 +263,7 @@ pub enum EventData { Ipc(IpcMessage), - TemplateUpdated(Template<'static>), + HotReloadEvent(HotReloadMsg), NewWindow, diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 0ec1f922c..9e1bf79db 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -112,7 +112,7 @@ pub fn launch_with_props(root: Component

, props: P, cfg: Config) let proxy = proxy.clone(); dioxus_hot_reload::connect(move |template| { let _ = proxy.send_event(UserWindowEvent( - EventData::TemplateUpdated(template), + EventData::HotReloadEvent(template), unsafe { WindowId::dummy() }, )); }); @@ -177,13 +177,18 @@ pub fn launch_with_props(root: Component

, props: P, cfg: Config) } Event::UserEvent(event) => match event.0 { - EventData::TemplateUpdated(template) => { - for webview in webviews.values_mut() { - webview.dom.replace_template(template); + EventData::HotReloadEvent(msg) => match msg { + dioxus_hot_reload::HotReloadMsg::UpdateTemplate(template) => { + for webview in webviews.values_mut() { + webview.dom.replace_template(template); - poll_vdom(webview); + poll_vdom(webview); + } } - } + dioxus_hot_reload::HotReloadMsg::Shutdown => { + *control_flow = ControlFlow::Exit; + } + }, EventData::CloseWindow => { webviews.remove(&event.1); diff --git a/packages/hot-reload/Cargo.toml b/packages/hot-reload/Cargo.toml index d6088a109..7dda13a5d 100644 --- a/packages/hot-reload/Cargo.toml +++ b/packages/hot-reload/Cargo.toml @@ -14,3 +14,6 @@ interprocess = { version = "1.2.1" } notify = "5.0.0" chrono = "0.4.23" serde_json = "1.0.91" +serde = { version = "1", features = ["derive"] } +execute = "0.2.11" +once_cell = "1.17.0" \ No newline at end of file diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 9543911b2..face5edc1 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -15,42 +15,141 @@ use notify::{RecommendedWatcher, RecursiveMode, Watcher}; #[cfg(debug_assertions)] pub use dioxus_html::HtmlCtx; +use serde::{Deserialize, Serialize}; -/// Initialize the hot reloading listener on the given path -pub fn init( +/// A message the hot reloading server sends to the client +#[derive(Debug, Serialize, Deserialize, Clone, Copy)] +pub enum HotReloadMsg { + /// A template has been updated + #[serde(borrow = "'static")] + UpdateTemplate(Template<'static>), + /// The program needs to be recompiled, and the client should shut down + Shutdown, +} + +#[derive(Debug, Clone, Copy)] +pub struct Config { root_path: &'static str, listening_paths: &'static [&'static str], + excluded_paths: &'static [&'static str], log: bool, -) { + rebuild_with: Option<&'static str>, + phantom: std::marker::PhantomData, +} + +impl Default for Config { + fn default() -> Self { + Self { + root_path: "", + listening_paths: &[""], + excluded_paths: &["./target"], + log: true, + rebuild_with: None, + phantom: std::marker::PhantomData, + } + } +} + +impl Config { + pub const fn new() -> Self { + Self { + root_path: "", + listening_paths: &[""], + excluded_paths: &["./target"], + log: true, + rebuild_with: None, + phantom: std::marker::PhantomData, + } + } +} + +impl Config { + pub const fn root(self, path: &'static str) -> Self { + Self { + root_path: path, + ..self + } + } + + pub const fn listening_paths(self, paths: &'static [&'static str]) -> Self { + Self { + listening_paths: paths, + ..self + } + } + + pub const fn log(self, log: bool) -> Self { + Self { log, ..self } + } + + pub const fn rebuild_with(self, rebuild_with: &'static str) -> Self { + Self { + rebuild_with: Some(rebuild_with), + ..self + } + } + + pub const fn excluded_paths(self, paths: &'static [&'static str]) -> Self { + Self { + excluded_paths: paths, + ..self + } + } +} + +/// Initialize the hot reloading listener +pub fn init(cfg: Config) { + let Config { + root_path, + listening_paths, + log, + rebuild_with, + excluded_paths, + phantom: _, + } = cfg; + if let Ok(crate_dir) = PathBuf::from_str(root_path) { let temp_file = std::env::temp_dir().join("@dioxusin"); let channels = Arc::new(Mutex::new(Vec::new())); let file_map = Arc::new(Mutex::new(FileMap::::new(crate_dir.clone()))); if let Ok(local_socket_stream) = LocalSocketListener::bind(temp_file.as_path()) { + let aborted = Arc::new(Mutex::new(false)); + // listen for connections std::thread::spawn({ let file_map = file_map.clone(); let channels = channels.clone(); + let aborted = aborted.clone(); + let _ = local_socket_stream.set_nonblocking(true); move || { - for mut connection in local_socket_stream.incoming().flatten() { - // send any templates than have changed before the socket connected - let templates: Vec<_> = { - file_map - .lock() - .unwrap() - .map - .values() - .filter_map(|(_, template_slot)| *template_slot) - .collect() - }; - for template in templates { - if !send_template(template, &mut connection) { - continue; + loop { + if let Ok(mut connection) = local_socket_stream.accept() { + // send any templates than have changed before the socket connected + let templates: Vec<_> = { + file_map + .lock() + .unwrap() + .map + .values() + .filter_map(|(_, template_slot)| *template_slot) + .collect() + }; + for template in templates { + if !send_msg( + HotReloadMsg::UpdateTemplate(template), + &mut connection, + ) { + continue; + } + } + channels.lock().unwrap().push(connection); + if log { + println!("Connected to hot reloading 🚀"); } } - channels.lock().unwrap().push(connection); - if log { - println!("Connected to hot reloading 🚀"); + std::thread::sleep(std::time::Duration::from_millis(10)); + if aborted.lock().unwrap().clone() { + break; } } } @@ -65,37 +164,42 @@ pub fn init( let mut watcher = RecommendedWatcher::new(tx, notify::Config::default()).unwrap(); for path in listening_paths { - match PathBuf::from_str(path) { - Ok(path) => { - let full_path = crate_dir.join(path); - if let Err(err) = watcher.watch(&full_path, RecursiveMode::Recursive) { - if log { - println!( - "hot reloading failed to start watching {full_path:?}:\n{err:?}", - ); - } - } - } - Err(err) => { - if log { - println!("hot reloading failed to create path:\n{:?}", err); - } + let full_path = crate_dir.join(path); + if let Err(err) = watcher.watch(&full_path, RecursiveMode::Recursive) { + if log { + println!( + "hot reloading failed to start watching {full_path:?}:\n{err:?}", + ); } } } + let excluded_paths = excluded_paths + .iter() + .map(|path| crate_dir.join(PathBuf::from(path))) + .collect::>(); + for evt in rx { - // Give time for the change to take effect before reading the file - std::thread::sleep(std::time::Duration::from_millis(100)); if chrono::Local::now().timestamp() > last_update_time { if let Ok(evt) = evt { - let mut channels = channels.lock().unwrap(); - for path in &evt.paths { - // skip non rust files - if path.extension().and_then(|p| p.to_str()) != Some("rs") { - continue; - } + let real_paths = evt + .paths + .iter() + .filter(|path| { + // skip non rust files + path.extension().and_then(|p| p.to_str()) == Some("rs") && + // skip excluded paths + !excluded_paths.iter().any(|p| path.starts_with(p)) + }) + .collect::>(); + // Give time for the change to take effect before reading the file + if !real_paths.is_empty() { + std::thread::sleep(std::time::Duration::from_millis(100)); + } + + let mut channels = channels.lock().unwrap(); + for path in real_paths { // find changes to the rsx in the file match file_map .lock() @@ -107,7 +211,10 @@ pub fn init( let mut i = 0; while i < channels.len() { let channel = &mut channels[i]; - if send_template(msg, channel) { + if send_msg( + HotReloadMsg::UpdateTemplate(msg), + channel, + ) { i += 1; } else { channels.remove(i); @@ -116,11 +223,23 @@ pub fn init( } } UpdateResult::NeedsRebuild => { - if log { - println!( - "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." - ); + if let Some(rebuild_command) = rebuild_with { + *aborted.lock().unwrap() = true; + if log { + println!("Rebuilding the application..."); + } + execute::shell(rebuild_command).spawn().expect("Failed to rebuild the application. Is cargo installed?"); + for channel in &mut *channels { + send_msg(HotReloadMsg::Shutdown, channel); + } + } else { + if log { + println!( + "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." + ); + } } + return; } } @@ -134,8 +253,8 @@ pub fn init( } } -fn send_template(template: Template<'static>, channel: &mut impl Write) -> bool { - if let Ok(msg) = serde_json::to_string(&template) { +fn send_msg(msg: HotReloadMsg, channel: &mut impl Write) -> bool { + if let Ok(msg) = serde_json::to_string(&msg) { if channel.write_all(msg.as_bytes()).is_err() { return false; } @@ -149,7 +268,7 @@ fn send_template(template: Template<'static>, channel: &mut impl Write) -> bool } /// Connect to the hot reloading listener. The callback provided will be called every time a template change is detected -pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { +pub fn connect(mut f: impl FnMut(HotReloadMsg) + Send + 'static) { std::thread::spawn(move || { let temp_file = std::env::temp_dir().join("@dioxusin"); if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) { @@ -158,7 +277,7 @@ pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { let mut buf = String::new(); match buf_reader.read_line(&mut buf) { Ok(_) => { - let template: Template<'static> = + let template: HotReloadMsg = serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap(); f(template); } @@ -179,33 +298,13 @@ pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) { /// If no paths are passed, it will listen on the src and examples folders. #[macro_export] macro_rules! hot_reload_init { - ($(@ $ctx:ident)? $($t: ident)*) => { + () => { #[cfg(debug_assertions)] - dioxus_hot_reload::init::(core::env!("CARGO_MANIFEST_DIR"), &["src", "examples"], hot_reload_init!(@log: $($t)*)) + dioxus_hot_reload::init(dioxus_hot_reload::Config::new().root(env!("CARGO_MANIFEST_DIR"))); }; - ($(@ $ctx:ident)? $($paths: literal),* $(,)? $($t: ident)*) => { + ($cfg: expr) => { #[cfg(debug_assertions)] - dioxus_hot_reload::init::(core::env!("CARGO_MANIFEST_DIR"), &[$($paths),*], hot_reload_init!(@log: $($t)*)) - }; - - (@log:) => { - false - }; - - (@log: enable logging) => { - true - }; - - (@log: disable logging) => { - false - }; - - (@ctx: $ctx: ident) => { - $ctx - }; - - (@ctx: ) => { - dioxus_hot_reload::HtmlCtx + dioxus_hot_reload::init($cfg.root(env!("CARGO_MANIFEST_DIR"))); }; } diff --git a/packages/liveview/src/pool.rs b/packages/liveview/src/pool.rs index 281ada480..b3ed6bef5 100644 --- a/packages/liveview/src/pool.rs +++ b/packages/liveview/src/pool.rs @@ -157,9 +157,16 @@ where } } - new_template = hot_reload_wait => { - if let Some(new_template) = new_template { - vdom.replace_template(new_template); + msg = hot_reload_wait => { + if let Some(msg) = msg { + match msg{ + dioxus_hot_reload::HotReloadMsg::UpdateTemplate(new_template) => { + vdom.replace_template(new_template); + } + dioxus_hot_reload::HotReloadMsg::Shutdown => { + std::process::exit(0); + }, + } } } } diff --git a/packages/tui/src/lib.rs b/packages/tui/src/lib.rs index 8950a7245..6961aa6d6 100644 --- a/packages/tui/src/lib.rs +++ b/packages/tui/src/lib.rs @@ -6,6 +6,7 @@ use crossterm::{ terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use dioxus_core::*; +use dioxus_hot_reload::HotReloadMsg; use dioxus_native_core::{real_dom::RealDom, FxDashSet, NodeId, NodeMask, SendAnyMap}; use focus::FocusState; use futures::{ @@ -147,9 +148,9 @@ fn render_vdom( .block_on(async { #[cfg(all(feature = "hot-reload", debug_assertions))] let mut hot_reload_rx = { - let (hot_reload_tx, hot_reload_rx) = unbounded_channel::>(); - dioxus_hot_reload::connect(move |template| { - let _ = hot_reload_tx.send(template); + let (hot_reload_tx, hot_reload_rx) = unbounded_channel::(); + dioxus_hot_reload::connect(move |msg| { + let _ = hot_reload_tx.send(msg); }); hot_reload_rx }; @@ -232,7 +233,7 @@ fn render_vdom( } } - let mut new_templete = None; + let mut hot_reload_msg = None; { let wait = vdom.wait_for_work(); #[cfg(all(feature = "hot-reload", debug_assertions))] @@ -267,15 +268,22 @@ fn render_vdom( register_event(evt); } }, - Some(template) = hot_reload_wait => { - new_templete = Some(template); + Some(msg) = hot_reload_wait => { + hot_reload_msg = Some(msg); } } } // if we have a new template, replace the old one - if let Some(template) = new_templete { - vdom.replace_template(template); + if let Some(msg) = hot_reload_msg { + match msg { + HotReloadMsg::UpdateTemplate(template) => { + vdom.replace_template(template); + } + HotReloadMsg::Shutdown => { + break; + } + } } { From cc983dc09173ef84a4116ec22bf3ced01f5bca3e Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 16:17:25 -0600 Subject: [PATCH 19/29] rebuild when the cargo.toml changes --- packages/hot-reload/src/lib.rs | 45 +++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index face5edc1..89d08465f 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -179,6 +179,27 @@ pub fn init(cfg: Config) { .map(|path| crate_dir.join(PathBuf::from(path))) .collect::>(); + let rebuild = || { + if let Some(rebuild_command) = rebuild_with { + *aborted.lock().unwrap() = true; + if log { + println!("Rebuilding the application..."); + } + execute::shell(rebuild_command) + .spawn() + .expect("Failed to rebuild the application. Is cargo installed?"); + for channel in &mut *channels.lock().unwrap() { + send_msg(HotReloadMsg::Shutdown, channel); + } + } else { + if log { + println!( + "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." + ); + } + } + }; + for evt in rx { if chrono::Local::now().timestamp() > last_update_time { if let Ok(evt) = evt { @@ -187,7 +208,7 @@ pub fn init(cfg: Config) { .iter() .filter(|path| { // skip non rust files - path.extension().and_then(|p| p.to_str()) == Some("rs") && + matches!(path.extension().and_then(|p| p.to_str()), Some("rs" | "toml" | "css" | "html" | "js")) && // skip excluded paths !excluded_paths.iter().any(|p| path.starts_with(p)) }) @@ -200,6 +221,10 @@ pub fn init(cfg: Config) { let mut channels = channels.lock().unwrap(); for path in real_paths { + // if this file type cannot be hot reloaded, rebuild the application + if path.extension().and_then(|p| p.to_str()) != Some("rs") { + rebuild(); + } // find changes to the rsx in the file match file_map .lock() @@ -223,22 +248,8 @@ pub fn init(cfg: Config) { } } UpdateResult::NeedsRebuild => { - if let Some(rebuild_command) = rebuild_with { - *aborted.lock().unwrap() = true; - if log { - println!("Rebuilding the application..."); - } - execute::shell(rebuild_command).spawn().expect("Failed to rebuild the application. Is cargo installed?"); - for channel in &mut *channels { - send_msg(HotReloadMsg::Shutdown, channel); - } - } else { - if log { - println!( - "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." - ); - } - } + drop(channels); + rebuild(); return; } From d642e53a2bdedb1e6408a5abc6efa6ea6a36de57 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 16:25:03 -0600 Subject: [PATCH 20/29] intigrate with .gitignore --- packages/hot-reload/Cargo.toml | 3 ++- packages/hot-reload/src/lib.rs | 12 +++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/hot-reload/Cargo.toml b/packages/hot-reload/Cargo.toml index 7dda13a5d..034e819fc 100644 --- a/packages/hot-reload/Cargo.toml +++ b/packages/hot-reload/Cargo.toml @@ -16,4 +16,5 @@ chrono = "0.4.23" serde_json = "1.0.91" serde = { version = "1", features = ["derive"] } execute = "0.2.11" -once_cell = "1.17.0" \ No newline at end of file +once_cell = "1.17.0" +gitignore = "1.0.7" \ No newline at end of file diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 89d08465f..e6bebde27 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -157,6 +157,10 @@ pub fn init(cfg: Config) { // watch for changes std::thread::spawn(move || { + // try to find the gitingore file + let gitignore_file_path = crate_dir.join(".gitignore"); + let gitignore_file = gitignore::File::new(&gitignore_file_path.as_path()); + let mut last_update_time = chrono::Local::now().timestamp(); let (tx, rx) = std::sync::mpsc::channel(); @@ -210,7 +214,13 @@ pub fn init(cfg: Config) { // skip non rust files matches!(path.extension().and_then(|p| p.to_str()), Some("rs" | "toml" | "css" | "html" | "js")) && // skip excluded paths - !excluded_paths.iter().any(|p| path.starts_with(p)) + !excluded_paths.iter().any(|p| path.starts_with(p)) && match &gitignore_file{ + Ok(file) => match file.is_excluded(path){ + Ok(excluded) => !excluded, + Err(_) => true, + }, + Err(_) => true, + } }) .collect::>(); From 22f86ed464d2f9612f52da2f9e0387b5154209ed Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 16:57:27 -0600 Subject: [PATCH 21/29] update docs --- .../src/en/getting_started/hot_reload.md | 2 ++ packages/hot-reload/Cargo.toml | 6 ++++ packages/hot-reload/README.md | 32 ++++++++++++------- packages/hot-reload/src/lib.rs | 30 +++++++++-------- 4 files changed, 45 insertions(+), 25 deletions(-) diff --git a/docs/guide/src/en/getting_started/hot_reload.md b/docs/guide/src/en/getting_started/hot_reload.md index 9700752f4..599ce57da 100644 --- a/docs/guide/src/en/getting_started/hot_reload.md +++ b/docs/guide/src/en/getting_started/hot_reload.md @@ -24,6 +24,8 @@ dioxus serve --hot-reload For desktop, LiveView, and tui, you can place the hot reload macro at the top of your main function to enable hot reloading. Hot reloading is automatically enabled on debug builds. +For more information about hot reloading on native platforms and configuration options see the [dioxus-hot-reload](https://crates.io/crates/dioxus-hot-reload) crate. + ## Setup Add the following to your main function: diff --git a/packages/hot-reload/Cargo.toml b/packages/hot-reload/Cargo.toml index 034e819fc..7f1759f03 100644 --- a/packages/hot-reload/Cargo.toml +++ b/packages/hot-reload/Cargo.toml @@ -2,6 +2,12 @@ name = "dioxus-hot-reload" version = "0.1.0" edition = "2021" +license = "MIT/Apache-2.0" +repository = "https://github.com/DioxusLabs/dioxus/" +homepage = "https://dioxuslabs.com" +description = "Hot reloading utilites for Dioxus" +documentation = "https://dioxuslabs.com" +keywords = ["dom", "ui", "gui", "react", "hot-reloading", "watch"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/packages/hot-reload/README.md b/packages/hot-reload/README.md index 4e8c7d880..3ae091179 100644 --- a/packages/hot-reload/README.md +++ b/packages/hot-reload/README.md @@ -79,31 +79,32 @@ fn main(){ } ``` -By default the dev server watches on the `src` and `examples` folders in the root crate directory. To watch on custom paths pass the paths into the hot relaod macro: +By default the dev server watches on the root of the crate the macro is called in and ignores changes in the `/target` directory and any directories set in the `.gitignore` file in the root directory. To watch on custom paths pass call the `with_paths` function on the config builder: ```rust fn main(){ - hot_reload_init!("src", "examples", "assets"); + hot_reload_init!(Config::new().with_paths(&["src", "examples", "assets"])); // launch your application } ``` -By default the hot reloading server will output some logs in the console, to disable these logs pass the `disable logging` flag into the macro: +By default the hot reloading server will output some logs in the console, to disable these logs call the `with_logging` function on the config builder: ```rust fn main(){ - hot_reload_init!("src", "examples", "assets", disable logging); + hot_reload_init!(Config::new().with_logging(false)); // launch your application } ``` -If you are using a namespace other than html, you can implement the [HotReloadingContext](https://docs.rs/dioxus-rsx/latest/dioxus_rsx/trait.HotReloadingContext.html) trait to provide a mapping between the rust names of your elements/attributes and the resultsing strings. +If you are using a namespace other than html, you can implement the [HotReloadingContext](https://docs.rs/dioxus-rsx/latest/dioxus_rsx/trait.HotReloadingContext.html) trait to provide a mapping between the rust names of your elements/attributes and the resulting strings. -You can then provide the Context to the macro to make hot reloading work with your custom namespace: +You can then provide the Context to the builder to make hot reloading work with your custom namespace: ```rust fn main(){ - hot_reload_init!(@MyNamespace /*more configeration*/); + // Note: Use default instead of new if you are using a custom namespace + hot_reload_init!(Config::::default()); // launch your application } ``` @@ -118,15 +119,22 @@ async fn launch(app: Component) { // ... let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); - dioxus_hot_reload::connect(move |template| { - let _ = tx.send(template); + dioxus_hot_reload::connect(move |msg| { + let _ = tx.send(msg); }); loop { tokio::select! { - Some(template) = rx.recv() => { - // update the template in the virtual dom - vdom.replace_template(template); + Some(msg) = rx.recv() => { + match msg{ + HotReloadMsg::Shutdown => { + // ... shutdown the application + } + HotReloadMsg::UpdateTemplate(template) => { + // update the template in the virtual dom + vdom.replace_template(template); + } + } } _ = vdom.wait_for_work() => { // ... diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index e6bebde27..fc57b0e56 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -64,6 +64,7 @@ impl Config { } impl Config { + /// Set the root path of the project (where the Cargo.toml file is). This is automatically set by the [`hot_reload_init`] macro. pub const fn root(self, path: &'static str) -> Self { Self { root_path: path, @@ -71,24 +72,30 @@ impl Config { } } - pub const fn listening_paths(self, paths: &'static [&'static str]) -> Self { - Self { - listening_paths: paths, - ..self - } - } - - pub const fn log(self, log: bool) -> Self { + /// Set whether to enable logs + pub const fn with_logging(self, log: bool) -> Self { Self { log, ..self } } - pub const fn rebuild_with(self, rebuild_with: &'static str) -> Self { + /// Set the command to run to rebuild the project + /// + /// For example to restart the application after a change is made, you could use `cargo run` + pub const fn with_rebuild_handler(self, rebuild_with: &'static str) -> Self { Self { rebuild_with: Some(rebuild_with), ..self } } + /// Set the paths to listen for changes in to trigger hot reloading. If this is a directory it will listen for changes in all files in that directory recursively. + pub const fn with_paths(self, paths: &'static [&'static str]) -> Self { + Self { + listening_paths: paths, + ..self + } + } + + /// Sets paths to ignore changes on. This will override any paths set in the [`Config::with_paths`] method in the case of conflicts. pub const fn excluded_paths(self, paths: &'static [&'static str]) -> Self { Self { excluded_paths: paths, @@ -313,10 +320,7 @@ pub fn connect(mut f: impl FnMut(HotReloadMsg) + Send + 'static) { }); } -/// Start the hot reloading server -/// -/// Pass any number of paths to listen for changes on relative to the crate root as strings. -/// If no paths are passed, it will listen on the src and examples folders. +/// Start the hot reloading server with the current directory as the root #[macro_export] macro_rules! hot_reload_init { () => { From 31e21aaa79df57fd9457a2e34e4ee2e45785caf4 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 17:15:06 -0600 Subject: [PATCH 22/29] change rebuild_handler to rebuild_command --- packages/hot-reload/README.md | 9 +++++++++ packages/hot-reload/src/lib.rs | 8 +++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/hot-reload/README.md b/packages/hot-reload/README.md index 3ae091179..126c42103 100644 --- a/packages/hot-reload/README.md +++ b/packages/hot-reload/README.md @@ -97,6 +97,15 @@ fn main(){ } ``` +To rebuild the application when the logic changes, you can use the `with_rebuild_command` function on the config builder. This command will be called when hot reloading fails to quickly update the rsx: + +```rust +fn main(){ + hot_reload_init!(Config::new().with_rebuild_command("cargo run")); + // launch your application +} +``` + If you are using a namespace other than html, you can implement the [HotReloadingContext](https://docs.rs/dioxus-rsx/latest/dioxus_rsx/trait.HotReloadingContext.html) trait to provide a mapping between the rust names of your elements/attributes and the resulting strings. You can then provide the Context to the builder to make hot reloading work with your custom namespace: diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index fc57b0e56..4e3f56ed7 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -80,7 +80,7 @@ impl Config { /// Set the command to run to rebuild the project /// /// For example to restart the application after a change is made, you could use `cargo run` - pub const fn with_rebuild_handler(self, rebuild_with: &'static str) -> Self { + pub const fn with_rebuild_command(self, rebuild_with: &'static str) -> Self { Self { rebuild_with: Some(rebuild_with), ..self @@ -198,7 +198,8 @@ pub fn init(cfg: Config) { } execute::shell(rebuild_command) .spawn() - .expect("Failed to rebuild the application. Is cargo installed?"); + .expect("Failed to spawn the rebuild command"); + for channel in &mut *channels.lock().unwrap() { send_msg(HotReloadMsg::Shutdown, channel); } @@ -233,11 +234,12 @@ pub fn init(cfg: Config) { // Give time for the change to take effect before reading the file if !real_paths.is_empty() { - std::thread::sleep(std::time::Duration::from_millis(100)); + std::thread::sleep(std::time::Duration::from_millis(10)); } let mut channels = channels.lock().unwrap(); for path in real_paths { + println!("File changed: {:?}", path); // if this file type cannot be hot reloaded, rebuild the application if path.extension().and_then(|p| p.to_str()) != Some("rs") { rebuild(); From 34c8ad884975e9d9d0a85573cf48200282ab1ad5 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 17:31:55 -0600 Subject: [PATCH 23/29] fix gitignore performance issues --- packages/hot-reload/Cargo.toml | 2 +- packages/hot-reload/src/lib.rs | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/packages/hot-reload/Cargo.toml b/packages/hot-reload/Cargo.toml index 7f1759f03..99d5cb00d 100644 --- a/packages/hot-reload/Cargo.toml +++ b/packages/hot-reload/Cargo.toml @@ -23,4 +23,4 @@ serde_json = "1.0.91" serde = { version = "1", features = ["derive"] } execute = "0.2.11" once_cell = "1.17.0" -gitignore = "1.0.7" \ No newline at end of file +ignore = "0.4.19" \ No newline at end of file diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 4e3f56ed7..da443df49 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -166,7 +166,7 @@ pub fn init(cfg: Config) { std::thread::spawn(move || { // try to find the gitingore file let gitignore_file_path = crate_dir.join(".gitignore"); - let gitignore_file = gitignore::File::new(&gitignore_file_path.as_path()); + let (gitignore, _) = ignore::gitignore::Gitignore::new(gitignore_file_path); let mut last_update_time = chrono::Local::now().timestamp(); @@ -220,15 +220,16 @@ pub fn init(cfg: Config) { .iter() .filter(|path| { // skip non rust files - matches!(path.extension().and_then(|p| p.to_str()), Some("rs" | "toml" | "css" | "html" | "js")) && + matches!( + path.extension().and_then(|p| p.to_str()), + Some("rs" | "toml" | "css" | "html" | "js") + )&& // skip excluded paths - !excluded_paths.iter().any(|p| path.starts_with(p)) && match &gitignore_file{ - Ok(file) => match file.is_excluded(path){ - Ok(excluded) => !excluded, - Err(_) => true, - }, - Err(_) => true, - } + !excluded_paths.iter().any(|p| path.starts_with(p)) && + // respect .gitignore + !gitignore + .matched_path_or_any_parents(path, false) + .is_ignore() }) .collect::>(); From 80755e1d557007a8b11ffb97fd18be7fcbb3ba79 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 17:32:31 -0600 Subject: [PATCH 24/29] remove debug log --- packages/hot-reload/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index da443df49..52769f6d3 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -240,7 +240,6 @@ pub fn init(cfg: Config) { let mut channels = channels.lock().unwrap(); for path in real_paths { - println!("File changed: {:?}", path); // if this file type cannot be hot reloaded, rebuild the application if path.extension().and_then(|p| p.to_str()) != Some("rs") { rebuild(); From 0c6750d1771704f7797c0c61e05c6d3d5612696d Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 17:50:32 -0600 Subject: [PATCH 25/29] fix dependancies --- packages/desktop/Cargo.toml | 5 ++--- packages/liveview/Cargo.toml | 4 ++-- packages/tui/Cargo.toml | 7 ++----- packages/tui/src/lib.rs | 8 ++++---- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index bb53eec4d..7a59790ba 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -15,7 +15,7 @@ keywords = ["dom", "ui", "gui", "react"] dioxus-core = { path = "../core", version = "^0.3.0", features = ["serialize"] } dioxus-html = { path = "../html", features = ["serialize"], version = "^0.3.0" } dioxus-interpreter-js = { path = "../interpreter", version = "^0.3.0" } -dioxus-hot-reload = { path = "../hot-reload" } +dioxus-hot-reload = { path = "../hot-reload", optional = true } serde = "1.0.136" serde_json = "1.0.79" @@ -34,7 +34,6 @@ webbrowser = "0.8.0" infer = "0.11.0" dunce = "1.0.2" -interprocess = { version = "1.2.1", optional = true } futures-util = "0.3.25" [target.'cfg(target_os = "ios")'.dependencies] @@ -50,7 +49,7 @@ tokio_runtime = ["tokio"] fullscreen = ["wry/fullscreen"] transparent = ["wry/transparent"] tray = ["wry/tray"] -hot-reload = ["interprocess"] +hot-reload = ["dioxus-hot-reload"] [dev-dependencies] dioxus-core-macro = { path = "../core-macro" } diff --git a/packages/liveview/Cargo.toml b/packages/liveview/Cargo.toml index f5cd988b3..fa097be5a 100644 --- a/packages/liveview/Cargo.toml +++ b/packages/liveview/Cargo.toml @@ -26,7 +26,7 @@ serde_json = "1.0.91" dioxus-html = { path = "../html", features = ["serialize"], version = "^0.3.0" } dioxus-core = { path = "../core", features = ["serialize"], version = "^0.3.0" } dioxus-interpreter-js = { path = "../interpreter", version = "0.3.0" } -dioxus-hot-reload = { path = "../hot-reload" } +dioxus-hot-reload = { path = "../hot-reload", optional = true } # warp warp = { version = "0.3.3", optional = true } @@ -54,7 +54,7 @@ tower = "0.4.13" [features] default = ["hot-reload"] # actix = ["actix-files", "actix-web", "actix-ws"] -hot-reload = ["interprocess"] +hot-reload = ["dioxus-hot-reload"] [[example]] name = "axum" diff --git a/packages/tui/Cargo.toml b/packages/tui/Cargo.toml index d6c96cfd3..bbf939d1a 100644 --- a/packages/tui/Cargo.toml +++ b/packages/tui/Cargo.toml @@ -18,7 +18,7 @@ dioxus-core = { path = "../core", version = "^0.3.0", features = ["serialize"] } dioxus-html = { path = "../html", version = "^0.3.0" } dioxus-native-core = { path = "../native-core", version = "^0.2.0" } dioxus-native-core-macro = { path = "../native-core-macro", version = "^0.2.0" } -dioxus-hot-reload = { path = "../hot-reload" } +dioxus-hot-reload = { path = "../hot-reload", optional = true } tui = "0.17.0" crossterm = "0.23.0" @@ -30,9 +30,6 @@ smallvec = "1.6" rustc-hash = "1.1.0" anymap = "1.0.0-beta.2" futures-channel = "0.3.25" -interprocess = { version = "1.2.1", optional = true } -serde = { version = "1.0.136", optional = true } -serde_json = { version = "1.0.79", optional = true } [dev-dependencies] dioxus = { path = "../dioxus" } @@ -45,4 +42,4 @@ harness = false [features] default = ["hot-reload"] -hot-reload = ["interprocess", "serde", "serde_json"] +hot-reload = ["dioxus-hot-reload"] diff --git a/packages/tui/src/lib.rs b/packages/tui/src/lib.rs index 6961aa6d6..c7f1dcc79 100644 --- a/packages/tui/src/lib.rs +++ b/packages/tui/src/lib.rs @@ -6,7 +6,6 @@ use crossterm::{ terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use dioxus_core::*; -use dioxus_hot_reload::HotReloadMsg; use dioxus_native_core::{real_dom::RealDom, FxDashSet, NodeId, NodeMask, SendAnyMap}; use focus::FocusState; use futures::{ @@ -148,7 +147,8 @@ fn render_vdom( .block_on(async { #[cfg(all(feature = "hot-reload", debug_assertions))] let mut hot_reload_rx = { - let (hot_reload_tx, hot_reload_rx) = unbounded_channel::(); + let (hot_reload_tx, hot_reload_rx) = + unbounded_channel::(); dioxus_hot_reload::connect(move |msg| { let _ = hot_reload_tx.send(msg); }); @@ -277,10 +277,10 @@ fn render_vdom( // if we have a new template, replace the old one if let Some(msg) = hot_reload_msg { match msg { - HotReloadMsg::UpdateTemplate(template) => { + dioxus_hot_reload::HotReloadMsg::UpdateTemplate(template) => { vdom.replace_template(template); } - HotReloadMsg::Shutdown => { + dioxus_hot_reload::HotReloadMsg::Shutdown => { break; } } From 63840bcca415c94c4872e0d67039fe2eb25e198b Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 13 Jan 2023 17:55:11 -0600 Subject: [PATCH 26/29] pass clippy --- packages/hot-reload/src/lib.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 52769f6d3..7038dffdb 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -155,7 +155,7 @@ pub fn init(cfg: Config) { } } std::thread::sleep(std::time::Duration::from_millis(10)); - if aborted.lock().unwrap().clone() { + if *aborted.lock().unwrap() { break; } } @@ -203,12 +203,10 @@ pub fn init(cfg: Config) { for channel in &mut *channels.lock().unwrap() { send_msg(HotReloadMsg::Shutdown, channel); } - } else { - if log { - println!( - "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." - ); - } + } else if log { + println!( + "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." + ); } }; From 893d0be1a6a0b8d47e3c7e568e4f2f81695b3253 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 15 Jan 2023 11:29:51 -0600 Subject: [PATCH 27/29] add option to specify a callback to make using hot-reloading in a CLI easier --- packages/hot-reload/src/lib.rs | 81 ++++++++++++++++++++++------------ 1 file changed, 53 insertions(+), 28 deletions(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 7038dffdb..c6e48082a 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -27,13 +27,12 @@ pub enum HotReloadMsg { Shutdown, } -#[derive(Debug, Clone, Copy)] pub struct Config { root_path: &'static str, listening_paths: &'static [&'static str], excluded_paths: &'static [&'static str], log: bool, - rebuild_with: Option<&'static str>, + rebuild_with: Option bool + Send + 'static>>, phantom: std::marker::PhantomData, } @@ -65,7 +64,7 @@ impl Config { impl Config { /// Set the root path of the project (where the Cargo.toml file is). This is automatically set by the [`hot_reload_init`] macro. - pub const fn root(self, path: &'static str) -> Self { + pub fn root(self, path: &'static str) -> Self { Self { root_path: path, ..self @@ -73,22 +72,37 @@ impl Config { } /// Set whether to enable logs - pub const fn with_logging(self, log: bool) -> Self { + pub fn with_logging(self, log: bool) -> Self { Self { log, ..self } } /// Set the command to run to rebuild the project /// /// For example to restart the application after a change is made, you could use `cargo run` - pub const fn with_rebuild_command(self, rebuild_with: &'static str) -> Self { + pub fn with_rebuild_command(self, rebuild_command: &'static str) -> Self { + self.with_rebuild_callback(move || { + execute::shell(rebuild_command) + .spawn() + .expect("Failed to spawn the rebuild command"); + true + }) + } + + /// Set a callback to run to when the project needs to be rebuilt and returns if the server should shut down + /// + /// For example a CLI application could rebuild the application when a change is made + pub fn with_rebuild_callback( + self, + rebuild_callback: impl FnMut() -> bool + Send + 'static, + ) -> Self { Self { - rebuild_with: Some(rebuild_with), + rebuild_with: Some(Box::new(rebuild_callback)), ..self } } /// Set the paths to listen for changes in to trigger hot reloading. If this is a directory it will listen for changes in all files in that directory recursively. - pub const fn with_paths(self, paths: &'static [&'static str]) -> Self { + pub fn with_paths(self, paths: &'static [&'static str]) -> Self { Self { listening_paths: paths, ..self @@ -96,7 +110,7 @@ impl Config { } /// Sets paths to ignore changes on. This will override any paths set in the [`Config::with_paths`] method in the case of conflicts. - pub const fn excluded_paths(self, paths: &'static [&'static str]) -> Self { + pub fn excluded_paths(self, paths: &'static [&'static str]) -> Self { Self { excluded_paths: paths, ..self @@ -110,7 +124,7 @@ pub fn init(cfg: Config) { root_path, listening_paths, log, - rebuild_with, + mut rebuild_with, excluded_paths, phantom: _, } = cfg; @@ -190,23 +204,31 @@ pub fn init(cfg: Config) { .map(|path| crate_dir.join(PathBuf::from(path))) .collect::>(); - let rebuild = || { - if let Some(rebuild_command) = rebuild_with { - *aborted.lock().unwrap() = true; - if log { - println!("Rebuilding the application..."); - } - execute::shell(rebuild_command) - .spawn() - .expect("Failed to spawn the rebuild command"); + let mut rebuild = { + let aborted = aborted.clone(); + let channels = channels.clone(); + move || { + if let Some(rebuild_callback) = &mut rebuild_with { + if log { + println!("Rebuilding the application..."); + } + let shutdown = rebuild_callback(); - for channel in &mut *channels.lock().unwrap() { - send_msg(HotReloadMsg::Shutdown, channel); + if shutdown { + *aborted.lock().unwrap() = true; + } + + for channel in &mut *channels.lock().unwrap() { + send_msg(HotReloadMsg::Shutdown, channel); + } + + return shutdown; + } else if log { + println!( + "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." + ); } - } else if log { - println!( - "Rebuild needed... shutting down hot reloading.\nManually rebuild the application to view futher changes." - ); + true } }; @@ -240,7 +262,9 @@ pub fn init(cfg: Config) { for path in real_paths { // if this file type cannot be hot reloaded, rebuild the application if path.extension().and_then(|p| p.to_str()) != Some("rs") { - rebuild(); + if rebuild() { + return; + } } // find changes to the rsx in the file match file_map @@ -266,9 +290,10 @@ pub fn init(cfg: Config) { } UpdateResult::NeedsRebuild => { drop(channels); - rebuild(); - - return; + if rebuild() { + return; + } + break; } } } From 418d8b1c3064302a157ee14ac2aca33fd7d93efb Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 15 Jan 2023 11:51:17 -0600 Subject: [PATCH 28/29] clippy --- packages/hot-reload/src/lib.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index c6e48082a..1f6ba7e21 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -261,10 +261,8 @@ pub fn init(cfg: Config) { let mut channels = channels.lock().unwrap(); for path in real_paths { // if this file type cannot be hot reloaded, rebuild the application - if path.extension().and_then(|p| p.to_str()) != Some("rs") { - if rebuild() { - return; - } + if path.extension().and_then(|p| p.to_str()) != Some("rs") && rebuild() { + return; } // find changes to the rsx in the file match file_map From 60219d3f6556b9d7214112b0102d39f04004f837 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 15 Jan 2023 12:01:12 -0600 Subject: [PATCH 29/29] formatting --- packages/hot-reload/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 1f6ba7e21..739cbfc55 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -261,7 +261,9 @@ pub fn init(cfg: Config) { let mut channels = channels.lock().unwrap(); for path in real_paths { // if this file type cannot be hot reloaded, rebuild the application - if path.extension().and_then(|p| p.to_str()) != Some("rs") && rebuild() { + if path.extension().and_then(|p| p.to_str()) != Some("rs") + && rebuild() + { return; } // find changes to the rsx in the file