diff --git a/app/(navigation)/(code)/util/formatCode.ts b/app/(navigation)/(code)/util/formatCode.ts index 8de71fc..241ecf3 100644 --- a/app/(navigation)/(code)/util/formatCode.ts +++ b/app/(navigation)/(code)/util/formatCode.ts @@ -9,6 +9,7 @@ const parsers = { CSS: { import: () => import("prettier/plugins/postcss"), name: "css" }, SCSS: { import: () => import("prettier/plugins/postcss"), name: "css" }, YAML: { import: () => import("prettier/plugins/yaml"), name: "yaml" }, + Python: { import: () => Promise.resolve({ default: {} }), name: "python" }, }; export const formatterSupportedLanguages: Language["name"][] = Object.keys(parsers); @@ -22,6 +23,16 @@ const formatCode = async (code: string, language: Language | null) => { if (!language || !formatterSupportedLanguages.includes(language.name)) { return code; } + + if (language.name === "Python") { + const { default: initRuff, Workspace } = await import("@astral-sh/ruff-wasm-web"); + await initRuff(); + + const workspace = new Workspace(Workspace.defaultSettings()); + const formatted = workspace.format(code); + return formatted.replace(/\n$/, ""); + } + const prettier = await import("prettier/standalone"); const parser = parsers[language.name as keyof typeof parsers]; diff --git a/package-lock.json b/package-lock.json index ff2d48a..bfa6b97 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "ray.so", "version": "0.1.0", "dependencies": { + "@astral-sh/ruff-wasm-web": "^0.9.6", "@next/bundle-analyzer": "^14.2.4", "@radix-ui/react-collapsible": "^1.0.3", "@radix-ui/react-context-menu": "^2.1.5", @@ -106,6 +107,12 @@ "node": ">=6.0.0" } }, + "node_modules/@astral-sh/ruff-wasm-web": { + "version": "0.9.6", + "resolved": "https://registry.npmjs.org/@astral-sh/ruff-wasm-web/-/ruff-wasm-web-0.9.6.tgz", + "integrity": "sha512-rR28EcWvx92mplU6pid11sbKiaCWN+5cNPTPN6OgP0MfOF/ScJQBAaul7SMqt2rgok6QYrz50+OXBRg1DQ0W1A==", + "license": "MIT" + }, "node_modules/@babel/code-frame": { "version": "7.24.6", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.6.tgz", diff --git a/package.json b/package.json index bdfc47e..ebb13a4 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "node": "^18" }, "dependencies": { + "@astral-sh/ruff-wasm-web": "^0.9.6", "@next/bundle-analyzer": "^14.2.4", "@radix-ui/react-collapsible": "^1.0.3", "@radix-ui/react-context-menu": "^2.1.5",