Browse Source

Merge branch 'master' into reword-docs

Jon Kelley 2 years ago
parent
commit
ab7d95852f

+ 10 - 6
docs/src/configure.md

@@ -1,12 +1,15 @@
 # Configure Project
 
+
 This chapter will introduce you to how to configure the CLI with your `Dioxus.toml` file
 
+Be aware that if the config file is present in the folder, some fields must be filled out, or the CLI tool will abort. The mandatory [table headers](https://toml.io/en/v1.0.0#table) and keys will have a '✍' sign beside it.
+
 ## Structure
 
 The CLI uses a `Dioxus.toml` file in the root of your crate to define some configuration for your `dioxus` project.
 
-### Application
+### Application
 
 General application confiration:
 
@@ -14,8 +17,9 @@ General application confiration:
 [application]
 # configuration
 ```
+1. ***name*** ✍ - project name & title
+2. ***default_platform*** ✍ - which platform target for this project.
 
-1. ***name*** - Project name
    ```
    name = "my-project"
    ```
@@ -39,7 +43,7 @@ General application confiration:
    sub_package = "my-crate"
    ```
 
-### Web.App
+### Web.App
 
 Configeration specific to web applications:
 
@@ -59,7 +63,7 @@ Configeration specific to web applications:
    base_path = "my_application"
    ```
 
-### Web.Watcher
+### Web.Watcher
 
 Configeration related to the development server:
 
@@ -81,7 +85,7 @@ Configeration related to the development server:
    index_on_404 = true
    ```
 
-### Web.Resource
+### Web.Resource
 
 Configeration related to static resources your application uses:
 ```
@@ -108,7 +112,7 @@ Configeration related to static resources your application uses:
     ]
    ```
 
-### Web.Resource.Dev
+### Web.Resource.Dev
 
 Configeration related to static resources your application uses in development:
 ```

+ 1 - 1
docs/src/plugin/interface/command.md

@@ -4,7 +4,7 @@
 
 Type Define:
 ```
-Stdio: "Inhert" | "Piped" | "Null"
+Stdio: "Inherit" | "Piped" | "Null"
 ```
 
 ### `exec(commands: [string], stdout: Stdio, stderr: Stdio)`

+ 7 - 7
extension/src/main.ts

@@ -136,28 +136,26 @@ function fmtDocument(document: vscode.TextDocument) {
 		const [editor,] = vscode.window.visibleTextEditors.filter(editor => editor.document.fileName === document.fileName);
 		if (!editor) return; // Need an editor to apply text edits.
 
-		const text = document.getText();
 		const fileDir = document.fileName.slice(0, document.fileName.lastIndexOf('\\'));
-
-		const child_proc = spawn(serverPath, ["fmt", "--file", text], {
+		const child_proc = spawn(serverPath, ["fmt", "--file", document.fileName], {
 			cwd: fileDir ? fileDir : undefined,
 		});
 
 		let result = '';
 		child_proc.stdout?.on('data', data => result += data);
 
-		type RsxEdit = {
+		/*type RsxEdit = {
 			formatted: string,
 			start: number,
 			end: number
-		}
+		}*/
 
 		child_proc.on('close', () => {
 			if (child_proc.exitCode !== 0) {
 				vscode.window.showWarningMessage(`Errors occurred while formatting. Make sure you have the most recent Dioxus-CLI installed!\nDioxus-CLI exited with exit code ${child_proc.exitCode}\n\nData from Dioxus-CLI:\n${result}`);
 				return;
 			}
-			if (result.length === 0) return;
+			/*if (result.length === 0) return;
 
 			// Used for error message:
 			const originalResult = result;
@@ -245,9 +243,10 @@ function fmtDocument(document: vscode.TextDocument) {
 					undoStopAfter: false,
 					undoStopBefore: false
 				});
+		
 			} catch (err) {
 				vscode.window.showWarningMessage(`Errors occurred while formatting. Make sure you have the most recent Dioxus-CLI installed!\n${err}\n\nData from Dioxus-CLI:\n${originalResult}`);
-			}
+			}*/
 		});
 
 		child_proc.on('error', (err) => {
@@ -259,6 +258,7 @@ function fmtDocument(document: vscode.TextDocument) {
 }
 
 
+
 // I'm using the approach defined in rust-analyzer here
 //
 // We ship the server as part of the extension, but we need to handle external paths and such

+ 61 - 13
src/builder.rs

@@ -380,7 +380,17 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
     );
     pb.set_message("💼 Waiting to start build the project...");
 
-    let stdout = cmd.stream_stdout()?;
+    struct StopSpinOnDrop(ProgressBar);
+
+    impl Drop for StopSpinOnDrop {
+        fn drop(&mut self) {
+            self.0.finish_and_clear();
+        }
+    }
+
+    StopSpinOnDrop(pb.clone());
+
+    let stdout = cmd.detached().stream_stdout()?;
     let reader = std::io::BufReader::new(stdout);
     for message in cargo_metadata::Message::parse_stream(reader) {
         match message.unwrap() {
@@ -388,9 +398,11 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
                 let message = msg.message;
                 match message.level {
                     cargo_metadata::diagnostic::DiagnosticLevel::Error => {
-                        return Err(anyhow::anyhow!(message
-                            .rendered
-                            .unwrap_or("Unknown".into())));
+                        return {
+                            Err(anyhow::anyhow!(message
+                                .rendered
+                                .unwrap_or("Unknown".into())))
+                        };
                     }
                     cargo_metadata::diagnostic::DiagnosticLevel::Warning => {
                         warning_messages.push(message.clone());
@@ -407,7 +419,6 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
             }
             Message::BuildFinished(finished) => {
                 if finished.success {
-                    pb.finish_and_clear();
                     log::info!("👑 Build done.");
                 } else {
                     std::process::exit(1);
@@ -462,7 +473,8 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
     {
         style_str.push_str("<link rel=\"stylesheet\" href=\"tailwind.css\">\n");
     }
-    html = html.replace("{style_include}", &style_str);
+
+    replace_or_insert_before("{style_include}", &style_str, "</head", &mut html);
 
     let mut script_str = String::new();
     for script in script_list {
@@ -472,7 +484,7 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
         ))
     }
 
-    html = html.replace("{script_include}", &script_str);
+    replace_or_insert_before("{script_include}", &script_str, "</body", &mut html);
 
     if serve {
         html += &format!(
@@ -481,12 +493,33 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
         );
     }
 
-    html = html.replace("{app_name}", &config.application.name);
-
-    html = match &config.web.app.base_path {
-        Some(path) => html.replace("{base_path}", path),
-        None => html.replace("{base_path}", "."),
+    let base_path = match &config.web.app.base_path {
+        Some(path) => path,
+        None => ".",
     };
+    let app_name = &config.application.name;
+    // Check if a script already exists
+    if html.contains("{app_name}") && html.contains("{base_path}") {
+        html = html.replace("{app_name}", app_name);
+
+        html = html.replace("{base_path}", base_path);
+    } else {
+        // If not, insert the script
+        html = html.replace(
+            "</body",
+            &format!(
+                r#"<script type="module">
+    import init from "/{base_path}/assets/dioxus/{app_name}.js";
+    init("/{base_path}/assets/dioxus/{app_name}_bg.wasm").then(wasm => {{
+      if (wasm.__wbindgen_start == undefined) {{
+        wasm.main();
+      }}
+    }});
+    </script>
+    </body"#
+            ),
+        );
+    }
 
     let title = config
         .web
@@ -495,7 +528,22 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
         .clone()
         .unwrap_or_else(|| "dioxus | ⛺".into());
 
-    html.replace("{app_title}", &title)
+    replace_or_insert_before("{app_title}", &title, "</title", &mut html);
+
+    html
+}
+
+fn replace_or_insert_before(
+    replace: &str,
+    with: &str,
+    or_insert_before: &str,
+    content: &mut String,
+) {
+    if content.contains(replace) {
+        *content = content.replace(replace, with);
+    } else {
+        *content = content.replace(or_insert_before, &format!("{}{}", with, or_insert_before));
+    }
 }
 
 // this function will build some assets file

+ 22 - 4
src/cli/autoformat/mod.rs

@@ -1,5 +1,5 @@
 use futures::{stream::FuturesUnordered, StreamExt};
-use std::process::exit;
+use std::{fs, process::exit};
 
 use super::*;
 
@@ -44,10 +44,28 @@ impl Autoformat {
             }
         }
 
+        // Format single file
         if let Some(file) = self.file {
-            let edits = dioxus_autofmt::fmt_file(&file);
-            let as_json = serde_json::to_string(&edits).unwrap();
-            println!("{}", as_json);
+            let file_content = fs::read_to_string(&file);
+
+            match file_content {
+                Ok(s) => {
+                    let edits = dioxus_autofmt::fmt_file(&s);
+                    let out = dioxus_autofmt::apply_formats(&s, edits);
+                    match fs::write(&file, out) {
+                        Ok(_) => {
+                            println!("formatted {}", file);
+                        }
+                        Err(e) => {
+                            eprintln!("failed to write formatted content to file: {}", e);
+                        }
+                    }
+                }
+                Err(e) => {
+                    eprintln!("failed to open file: {}", e);
+                    exit(1);
+                }
+            }
         }
 
         Ok(())

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

@@ -36,6 +36,9 @@ impl Serve {
             crate_config.set_features(self.serve.features.unwrap());
         }
 
+        // Subdirectories don't work with the server
+        crate_config.dioxus_config.web.app.base_path = None;
+
         let platform = self.serve.platform.unwrap_or_else(|| {
             crate_config
                 .dioxus_config

+ 15 - 9
src/config.rs

@@ -186,15 +186,21 @@ impl CrateConfig {
 
         let manifest = cargo_toml::Manifest::from_path(&cargo_def).unwrap();
 
-        // We just assume they're using a 'main.rs'
-        // Anyway, we've already parsed the manifest, so it should be easy to change the type
-        let output_filename = manifest
-            .bin
-            .first()
-            .or(manifest.lib.as_ref())
-            .and_then(|product| product.name.clone())
-            .or_else(|| manifest.package.as_ref().map(|pkg| pkg.name.clone()))
-            .expect("No lib found from cargo metadata");
+        let output_filename = {
+            match &manifest.package.as_ref().unwrap().default_run {
+                Some(default_run_target) => {
+                    default_run_target.to_owned()
+                },
+                None => {
+                    manifest.bin.iter().find(|b| b.name == manifest.package.as_ref().map(|pkg| pkg.name.clone()))
+                        .or(manifest.bin.iter().find(|b| b.path == Some("src/main.rs".to_owned())))
+                        .or(manifest.bin.first())
+                        .or(manifest.lib.as_ref())
+                        .and_then(|prod| prod.name.clone())
+                        .expect("No executable or library found from cargo metadata.")
+                }
+            }
+        };
         let executable = ExecutableType::Binary(output_filename);
 
         let release = false;

+ 5 - 5
src/plugin/interface/command.rs

@@ -3,7 +3,7 @@ use std::process::{Command, Stdio};
 use mlua::{FromLua, UserData};
 
 enum StdioFromString {
-    Inhert,
+    Inherit,
     Piped,
     Null,
 }
@@ -12,19 +12,19 @@ impl<'lua> FromLua<'lua> for StdioFromString {
         if let mlua::Value::String(v) = lua_value {
             let v = v.to_str().unwrap();
             return Ok(match v.to_lowercase().as_str() {
-                "inhert" => Self::Inhert,
+                "inherit" => Self::Inherit,
                 "piped" => Self::Piped,
                 "null" => Self::Null,
-                _ => Self::Inhert,
+                _ => Self::Inherit,
             });
         }
-        Ok(Self::Inhert)
+        Ok(Self::Inherit)
     }
 }
 impl StdioFromString {
     pub fn to_stdio(self) -> Stdio {
         match self {
-            StdioFromString::Inhert => Stdio::inherit(),
+            StdioFromString::Inherit => Stdio::inherit(),
             StdioFromString::Piped => Stdio::piped(),
             StdioFromString::Null => Stdio::null(),
         }