浏览代码

feat: basic autofmt

Jonathan Kelley 3 年之前
父节点
当前提交
84f0245f6c
共有 9 个文件被更改,包括 127 次插入38 次删除
  1. 3 0
      Cargo.toml
  2. 10 0
      extension/DEV.md
  3. 0 10
      extension/README.md
  4. 10 4
      extension/package.json
  5. 62 24
      extension/src/extension.ts
  6. 二进制
      extension/static/icon.png
  7. 25 0
      src/cli/autoformat/mod.rs
  8. 11 0
      src/cli/mod.rs
  9. 6 0
      src/main.rs

+ 3 - 0
Cargo.toml

@@ -46,6 +46,9 @@ flate2 = "1.0.22"
 tar = "0.4.38"
 tower = "0.4.12"
 
+dioxus-rsx = { git = "https://github.com/dioxuslabs/dioxus.git", branch = "jk/rsx-refactor" }
+dioxus-autofmt = { git = "https://github.com/dioxuslabs/dioxus.git", branch = "jk/rsx-refactor" }
+
 [[bin]]
 path = "src/main.rs"
 name = "dioxus"

+ 10 - 0
extension/DEV.md

@@ -0,0 +1,10 @@
+
+## packaging
+
+```
+$ cd myExtension
+$ vsce package
+# myExtension.vsix generated
+$ vsce publish
+# <publisherID>.myExtension published to VS Code Marketplace
+```

+ 0 - 10
extension/README.md

@@ -12,13 +12,3 @@ Converts a selection of html to valid rsx.
 ### Convert HTML to Dioxus Component
 
 Converts a selection of html to a valid Dioxus component with all SVGs factored out into their own module.
-
-## packaging
-
-```
-$ cd myExtension
-$ vsce package
-# myExtension.vsix generated
-$ vsce publish
-# <publisherID>.myExtension published to VS Code Marketplace
-```

+ 10 - 4
extension/package.json

@@ -1,14 +1,15 @@
 {
-    "name": "dioxusstudio",
+    "name": "dioxus",
     "displayName": "Dioxus",
     "description": "Useful tools for working with Dioxus",
     "version": "0.0.1",
-    "publisher": "jkelleyrtp",
+    "publisher": "DioxusLabs",
     "private": true,
     "license": "MIT",
+    "icon": "static/icon.png",
     "repository": {
         "type": "git",
-        "url": "https://github.com/Microsoft/vscode-extension-samples"
+        "url": "https://github.com/DioxusLabs/cli"
     },
     "engines": {
         "vscode": "^1.32.0"
@@ -18,7 +19,8 @@
     ],
     "activationEvents": [
         "onCommand:extension.htmlToDioxusRsx",
-        "onCommand:extension.htmlToDioxusComponent"
+        "onCommand:extension.htmlToDioxusComponent",
+        "onCommand:extension.formatRsx"
     ],
     "main": "./out/extension",
     "contributes": {
@@ -30,6 +32,10 @@
             {
                 "command": "extension.htmlToDioxusComponent",
                 "title": "Dioxus: Convert HTML to Component"
+            },
+            {
+                "command": "extension.formatRsx",
+                "title": "Dioxus: Format RSX"
             }
         ]
     },

+ 62 - 24
extension/src/extension.ts

@@ -3,33 +3,71 @@ import { spawn } from "child_process";
 
 export function activate(context: vscode.ExtensionContext) {
 
-	function registerCommand(cmd: string) {
-		function convert(cmd: string) {
-			const editor = vscode.window.activeTextEditor;// Get the active text editor
-			if (editor) {
-				const html = editor.document.getText(editor.selection);
-				if (html.length > 0) {
-					let params = ["translate"];
-					if (cmd.includes("Component")) params.push("--component");
-					params.push("--raw");
-					params.push(html);
-					const child_proc = spawn("dioxus", params);
-					let result = '';
-					child_proc.stdout?.on('data', data => result += data);
-					child_proc.on('close', () => {
-						if (result.length > 0) editor.edit(editBuilder => editBuilder.replace(editor.selection, result));
-					});
-				} else {
-					vscode.window.showWarningMessage("Please select HTML fragment before invoking this command!");
-				}
-			}
+
+	function translate(component: boolean) {
+		const editor = vscode.window.activeTextEditor;// Get the active text editor
+		if (!editor) return;
+
+		const html = editor.document.getText(editor.selection);
+		if (html.length == 0) {
+			vscode.window.showWarningMessage("Please select HTML fragment before invoking this command!");
+			return;
+		}
+
+		let params = ["translate"];
+		if (component) params.push("--component");
+		params.push("--raw");
+		params.push(html);
+
+		const child_proc = spawn("dioxus", params);
+
+		let result = '';
+		child_proc.stdout?.on('data', data => result += data);
+
+		child_proc.on('close', () => {
+			if (result.length > 0) editor.edit(editBuilder => editBuilder.replace(editor.selection, result));
+		});
+
+		child_proc.on('error', (err) => {
+			vscode.window.showWarningMessage(`Errors occurred while translating. Make sure you have the most recent Dioxus-CLI installed! \n${err}`);
+		});
+	}
+
+	function autoformat() {
+		const editor = vscode.window.activeTextEditor;// Get the active text editor
+		if (!editor) return;
+
+		const unformatted = editor.document.getText(editor.selection);
+		if (unformatted.length == 0) {
+			vscode.window.showWarningMessage("Please select rsx invoking this command!");
+			return;
 		}
 
+		const params = ["fmt", "--raw", unformatted];
+
+		const child_proc = spawn("dioxus", params);
+
+		let result = '';
+		child_proc.stdout?.on('data', data => result += data);
+
+		child_proc.on('close', () => {
+			if (result.length > 0) editor.edit(editBuilder => editBuilder.replace(editor.selection, result));
+		});
 
-		const handle = vscode.commands.registerCommand(cmd, () => convert(cmd));
-		context.subscriptions.push(handle);
+		child_proc.on('error', (err) => {
+			vscode.window.showWarningMessage(`Errors occurred while translating. Make sure you have the most recent Dioxus-CLI installed! \n${err}`);
+		});
 	}
 
-	registerCommand('extension.htmlToDioxusRsx');
-	registerCommand('extension.htmlToDioxusComponent');
+
+
+
+	const handles =
+		[
+			vscode.commands.registerCommand('extension.htmlToDioxusRsx', () => translate(false)),
+			vscode.commands.registerCommand('extension.htmlToDioxusComponent', () => translate(true)),
+			vscode.commands.registerCommand('extension.formatRsx', () => autoformat())
+		];
+
+	context.subscriptions.push(...handles);
 }

二进制
extension/static/icon.png


+ 25 - 0
src/cli/autoformat/mod.rs

@@ -0,0 +1,25 @@
+use super::*;
+
+/// Build the Rust WASM app and all of its assets.
+#[derive(Clone, Debug, Parser)]
+pub struct Autoformat {
+    /// Input file
+    #[clap(short, long)]
+    pub raw: Option<String>,
+}
+
+impl Autoformat {
+    pub fn autoformat(self) -> Result<()> {
+        if let Some(raw) = self.raw {
+            if let Some(inner) = dioxus_autofmt::fmt_block(&raw) {
+                println!("{}", inner);
+            } else {
+                // exit process with error
+                eprintln!("error formatting codeblock");
+                exit(1);
+            }
+        }
+
+        Ok(())
+    }
+}

+ 11 - 0
src/cli/mod.rs

@@ -1,3 +1,4 @@
+pub mod autoformat;
 pub mod build;
 pub mod cfg;
 pub mod clean;
@@ -45,17 +46,27 @@ pub struct Cli {
 pub enum Commands {
     /// Build the Rust WASM app and all of its assets.
     Build(build::Build),
+
     /// Translate some source file into Dioxus code.
     Translate(translate::Translate),
+
     /// Build, watch & serve the Rust WASM app and all of its assets.
     Serve(serve::Serve),
+
     /// Init a new project for Dioxus.
     Create(create::Create),
+
     /// Clean output artifacts.
     Clean(clean::Clean),
+
+    /// Format some rsx
+    #[clap(name = "fmt")]
+    Autoformat(autoformat::Autoformat),
+
     /// Dioxus config file controls.
     #[clap(subcommand)]
     Config(config::Config),
+
     /// Install  & Manage tools for Dioxus-cli.
     #[clap(subcommand)]
     Tool(tool::Tool),

+ 6 - 0
src/main.rs

@@ -48,6 +48,12 @@ async fn main() -> Result<()> {
                 log::error!("tool error: {}", e);
             }
         }
+
+        Commands::Autoformat(opts) => {
+            if let Err(e) = opts.autoformat() {
+                log::error!("format error: {}", e);
+            }
+        }
     }
 
     Ok(())