mrxiaozhuox преди 3 години
родител
ревизия
d18a93f129
променени са 11 файла, в които са добавени 43 реда и са изтрити 44 реда
  1. 11 13
      src/builder.rs
  2. 1 3
      src/cli/build/mod.rs
  3. 1 4
      src/cli/cfg.rs
  4. 0 3
      src/cli/clean/mod.rs
  5. 0 2
      src/cli/mod.rs
  6. 0 2
      src/cli/serve/mod.rs
  7. 1 0
      src/cli/translate/to_component.rs
  8. 1 1
      src/config.rs
  9. 3 3
      src/main.rs
  10. 6 5
      src/server/mod.rs
  11. 19 8
      src/server/serve.html

+ 11 - 13
src/builder.rs

@@ -3,7 +3,7 @@ use crate::{
     error::{Error, Result},
 };
 use std::{
-    io::{Read, Write},
+    io::Write,
     process::Command,
 };
 use wasm_bindgen_cli_support::Bindgen;
@@ -29,14 +29,15 @@ pub fn build(config: &CrateConfig) -> Result<()> {
     let t_start = std::time::Instant::now();
 
     // [1] Build the .wasm module
-    log::info!("Running build commands...");
+    log::info!("🚅 Running build commands...");
     let mut cmd = Command::new("cargo");
     cmd.current_dir(&crate_dir)
         .arg("build")
         .arg("--target")
         .arg("wasm32-unknown-unknown")
-        .stdout(std::process::Stdio::piped())
-        .stderr(std::process::Stdio::piped());
+        .stdout(std::process::Stdio::inherit())
+        .stderr(std::process::Stdio::inherit())
+    ;
 
     if config.release {
         cmd.arg("--release");
@@ -48,16 +49,13 @@ pub fn build(config: &CrateConfig) -> Result<()> {
         ExecutableType::Example(name) => cmd.arg("--example").arg(name),
     };
 
-    let mut child = cmd.spawn()?;
+    let output = cmd.output()?;
 
-    let output = child.wait()?;
-
-    if output.success() {
-        log::info!("Build complete!");
+    if output.status.success() {
+        std::io::stdout().write_all(&output.stdout).unwrap();
     } else {
         log::error!("Build failed!");
-        let mut reason = String::new();
-        child.stderr.unwrap().read_to_string(&mut reason)?;
+        let reason = String::from_utf8_lossy(&output.stderr).to_string();
         return Err(Error::BuildFailed(reason));
     }
 
@@ -98,8 +96,8 @@ pub fn build(config: &CrateConfig) -> Result<()> {
 
     // [5] Generate the html file with the module name
     // TODO: support names via options
-    log::info!("Writing to '{:#?}' directory...", out_dir);
 
+    // log::info!("Writing to '{:#?}' directory...", out_dir);
     let copy_options = fs_extra::dir::CopyOptions::new();
     if static_dir.is_dir() {
         match fs_extra::dir::copy(static_dir, out_dir, &copy_options) {
@@ -111,7 +109,7 @@ pub fn build(config: &CrateConfig) -> Result<()> {
     }
 
     let t_end = std::time::Instant::now();
-    log::info!("Done in {}ms! 🎉", (t_end - t_start).as_millis());
+    log::info!("🏁 Done in {}ms!", (t_end - t_start).as_millis());
     Ok(())
 }
 

+ 1 - 3
src/cli/build/mod.rs

@@ -1,6 +1,4 @@
 use crate::cfg::ConfigOptsBuild;
-use anyhow::Result;
-use std::path::PathBuf;
 use structopt::StructOpt;
 
 /// Build the Rust WASM app and all of its assets.
@@ -18,7 +16,7 @@ impl Build {
         // change the relase state.
         crate_config.with_release(self.build.release);
 
-        crate::builder::build(&crate_config);
+        crate::builder::build(&crate_config)?;
 
         Ok(())
     }

+ 1 - 4
src/cli/cfg.rs

@@ -1,11 +1,8 @@
-use anyhow::Result;
 use std::path::PathBuf;
 use structopt::StructOpt;
 
-use serde::{Deserialize, Serialize};
+use serde::Deserialize;
 use std::collections::HashMap;
-use std::str::FromStr;
-use std::sync::Arc;
 
 /// Config options for the build system.
 #[derive(Clone, Debug, Default, Deserialize, StructOpt)]

+ 0 - 3
src/cli/clean/mod.rs

@@ -1,6 +1,3 @@
-use crate::cfg::ConfigOptsBuild;
-use anyhow::Result;
-use std::path::PathBuf;
 use structopt::StructOpt;
 
 /// Build the Rust WASM app and all of its assets.

+ 0 - 2
src/cli/mod.rs

@@ -1,5 +1,3 @@
-use anyhow::{Context, Result};
-use std::path::PathBuf;
 use structopt::StructOpt;
 
 pub mod build;

+ 0 - 2
src/cli/serve/mod.rs

@@ -1,6 +1,4 @@
 use crate::{cfg::ConfigOptsServe, server};
-use anyhow::Result;
-use std::path::PathBuf;
 use std::io::Write;
 use structopt::StructOpt;
 

+ 1 - 0
src/cli/translate/to_component.rs

@@ -20,6 +20,7 @@ pub fn convert_html_to_component(html: &str) -> Result<ComponentRenderer> {
     })
 }
 
+#[allow(dead_code)]
 pub struct ComponentRenderer {
     dom: Dom,
     icon_index: usize,

+ 1 - 1
src/config.rs

@@ -1,5 +1,5 @@
 use crate::error::Result;
-use std::{io::Write, path::PathBuf, process::Command};
+use std::path::PathBuf;
 
 #[derive(Debug, Clone)]
 pub struct CrateConfig {

+ 3 - 3
src/main.rs

@@ -8,11 +8,11 @@ async fn main() -> Result<()> {
 
     match args.action {
         Commands::Translate(opts) => {
-            opts.translate();
+            opts.translate()?;
         }
 
         Commands::Build(opts) => {
-            opts.build();
+            opts.build()?;
         }
 
         // Commands::Clean(_) => {
@@ -23,7 +23,7 @@ async fn main() -> Result<()> {
         //     //
         // }
         Commands::Serve(opts) => {
-            opts.serve().await;
+            opts.serve().await?;
         }
     }
 

+ 6 - 5
src/server/mod.rs

@@ -1,6 +1,6 @@
 use axum::{
     extract::{
-        ws::{Message, WebSocket},
+        ws::Message,
         Extension, TypedHeader, WebSocketUpgrade,
     },
     http::StatusCode,
@@ -19,11 +19,11 @@ struct WsRelodState {
     update: bool,
 }
 
-impl WsRelodState { fn change(&mut self) { self.update = !self.update } }
+impl WsRelodState { fn change(&mut self) { self.update = !self.update; } }
 
 pub async fn startup(config: CrateConfig) -> anyhow::Result<()> {
 
-    log::info!("Starting development server 🚀");
+    log::info!("🚀 Starting development server...");
         
     let (tx, rx) = channel();
 
@@ -40,8 +40,9 @@ pub async fn startup(config: CrateConfig) -> anyhow::Result<()> {
                 match v {
                     DebouncedEvent::Create(_) | DebouncedEvent::Write(_) |
                     DebouncedEvent::Remove(_) | DebouncedEvent::Rename(_, _) => {
-                        builder::build(&watcher_conf).unwrap();
-                        watcher_ws_state.lock().unwrap().change();
+                        if let Ok(_) = builder::build(&watcher_conf) {
+                            watcher_ws_state.lock().unwrap().change();
+                        }
                     },
                     _ => {}
                 }

+ 19 - 8
src/server/serve.html

@@ -14,15 +14,26 @@
     </script>
 
     <script>
-      const socket = new WebSocket("ws://localhost:8080/ws");
-
-      socket.addEventListener("message", function (event) {
-        console.log(event);
-        if (event.data === "reload") {
-          window.location.reload();
-        }
-      });
+      (function () {
+        var protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+        var url = protocol + "//" + window.location.host + "/ws";
+        var poll_interval = 2000;
+        var reload_upon_connect = () => {
+          window.setTimeout(() => {
+            var ws = new WebSocket(url);
+            ws.onopen = () => window.location.reload();
+            ws.onclose = reload_upon_connect;
+          }, poll_interval);
+        };
 
+        var ws = new WebSocket(url);
+        ws.onmessage = (ev) => {
+          if (ev.data == "reload") {
+            window.location.reload();
+          }
+        };
+        ws.onclose = reload_upon_connect;
+      })();
     </script>
   </body>
 </html>