瀏覽代碼

fix: auto-reload

mrxiaozhuox 3 年之前
父節點
當前提交
b617299860
共有 3 個文件被更改,包括 73 次插入62 次删除
  1. 2 1
      Cargo.toml
  2. 1 0
      src/assets/autoreload.js
  3. 70 61
      src/server/mod.rs

+ 2 - 1
Cargo.toml

@@ -20,7 +20,8 @@ toml = "0.5.8"
 fs_extra = "1.2.0"
 cargo_toml = "0.10.0"
 futures = "0.3.12"
-notify = "4.0.17"
+# notify = "4.0.17"
+notify = { version = "5.0.0-pre.13", features = ["serde"] }
 html_parser = "0.6.2"
 binary-install = "0.0.2"
 convert_case = "0.5.0"

+ 1 - 0
src/assets/autoreload.js

@@ -15,6 +15,7 @@
   var ws = new WebSocket(url);
   ws.onmessage = (ev) => {
       if (ev.data == "reload") {
+        //   alert("reload!!!");
           window.location.reload();
       }
   };

+ 70 - 61
src/server/mod.rs

@@ -5,12 +5,9 @@ use axum::{
     routing::{get, get_service},
     AddExtensionLayer, Router,
 };
-use notify::{watcher, DebouncedEvent, Watcher};
-use std::time::Duration;
-use std::{
-    path::PathBuf,
-    sync::{mpsc::channel, Arc},
-};
+use notify::{RecommendedWatcher, Watcher};
+
+use std::{path::PathBuf, sync::Arc};
 use tower_http::services::ServeDir;
 
 use crate::{builder, serve::Serve, CrateConfig};
@@ -23,12 +20,33 @@ struct WsRelodState {
 pub async fn startup(config: CrateConfig) -> anyhow::Result<()> {
     log::info!("🚀 Starting development server...");
 
-    let (watcher_tx, watcher_rx) = channel();
-
     let dist_path = config.out_dir.clone();
 
+    let (reload_tx, _) = broadcast::channel(100);
+
+    let ws_reload_state = Arc::new(WsRelodState {
+        update: reload_tx.clone(),
+    });
+
     // file watcher: check file change
-    let mut watcher = watcher(watcher_tx, Duration::from_secs(1)).unwrap();
+    let watcher_conf = config.clone();
+    let mut watcher = RecommendedWatcher::new(move |_| {
+        if builder::build(&watcher_conf).is_ok() {
+            // change the websocket reload state to true;
+            // the page will auto-reload.
+            if watcher_conf
+                .dioxus_config
+                .web
+                .watcher
+                .reload_html
+                .unwrap_or(false)
+            {
+                let _ = Serve::regen_dev_page(&watcher_conf);
+            }
+            reload_tx.send("reload".into()).unwrap();
+        }
+    })
+    .unwrap();
     let allow_watch_path = config
         .dioxus_config
         .web
@@ -40,46 +58,38 @@ pub async fn startup(config: CrateConfig) -> anyhow::Result<()> {
     for sub_path in allow_watch_path {
         watcher
             .watch(
-                config.crate_dir.join(sub_path),
+                &config.crate_dir.join(sub_path),
                 notify::RecursiveMode::Recursive,
             )
             .unwrap();
     }
 
-    let (reload_tx, _) = broadcast::channel(100);
-
-    let ws_reload_state = Arc::new(WsRelodState {
-        update: reload_tx.clone(),
-    });
-
-    let watcher_conf = config.clone();
-
-    tokio::spawn(async move {
-        while let Ok(v) = watcher_rx.recv() {
-            match v {
-                DebouncedEvent::Create(_)
-                | DebouncedEvent::Write(_)
-                | DebouncedEvent::Remove(_)
-                | DebouncedEvent::Rename(_, _) => {
-                    if builder::build(&watcher_conf).is_ok() {
-                        // change the websocket reload state to true;
-                        // the page will auto-reload.
-                        if watcher_conf
-                            .dioxus_config
-                            .web
-                            .watcher
-                            .reload_html
-                            .unwrap_or(false)
-                        {
-                            let _ = Serve::regen_dev_page(&watcher_conf);
-                        }
-                        reload_tx.send("reload".into()).unwrap();
-                    }
-                }
-                _ => {}
-            }
-        }
-    });
+    // tokio::spawn(async move {
+    // while let Ok(v) = watcher_rx.recv() {
+    //     match v {
+    //         DebouncedEvent::Create(_)
+    //         | DebouncedEvent::Write(_)
+    //         | DebouncedEvent::Remove(_)
+    //         | DebouncedEvent::Rename(_, _) => {
+    //             if builder::build(&watcher_conf).is_ok() {
+    //                 // change the websocket reload state to true;
+    //                 // the page will auto-reload.
+    //                 if watcher_conf
+    //                     .dioxus_config
+    //                     .web
+    //                     .watcher
+    //                     .reload_html
+    //                     .unwrap_or(false)
+    //                 {
+    //                     let _ = Serve::regen_dev_page(&watcher_conf);
+    //                 }
+    //                 reload_tx.send("reload".into()).unwrap();
+    //             }
+    //         }
+    //         _ => {}
+    //     }
+    // }
+    // });
 
     // start serve dev-server at 0.0.0.0:8080
     let port = "8080";
@@ -113,25 +123,24 @@ async fn ws_handler(
     Extension(state): Extension<Arc<WsRelodState>>,
 ) -> impl IntoResponse {
     ws.on_upgrade(|mut socket| async move {
-
-        log::info!("New websocket conenct.");
-
         let mut rx = state.update.subscribe();
-
-        loop {
-            let v = rx.recv().await.unwrap();
-            println!("trigger recv: {}", v);
-            if v == "reload" {
-                // ignore the error
-                if socket
-                    .send(Message::Text(String::from("reload")))
-                    .await
-                    .is_err()
-                {
-                    println!("send failed");
-                    return;
+        let reload_watcher = tokio::spawn(async move {
+            loop {
+                let v = rx.recv().await.unwrap();
+                println!("trigger recv: {}", v);
+                if v == "reload" {
+                    // ignore the error
+                    if socket
+                        .send(Message::Text(String::from("reload")))
+                        .await
+                        .is_err()
+                    {
+                        break;
+                    }
                 }
             }
-        }
+        });
+
+        reload_watcher.await.unwrap();
     })
 }