diff --git a/package.json b/package.json index f58a40a9..a29a980e 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "isomorphic-dompurify": "^2.7.0", "json-loader": "^0.5.7", "marked": "^12.0.1", + "prettier": "^2.7.1", "process": "^0.11.10", "react": "^17.0.2", "react-dom": "^17.0.2", @@ -62,7 +63,6 @@ "jest": "^29.6.2", "langchain": "^0.0.179", "langsmith": "^0.0.47", - "prettier": "^2.7.1", "supabase": "^1.148.6", "ts-jest": "^29.1.1", "typedoc": "^0.24.4", diff --git a/src/components/InstructionsWithCode.js b/src/components/InstructionsWithCode.js index 66f70e4c..3fd499a1 100644 --- a/src/components/InstructionsWithCode.js +++ b/src/components/InstructionsWithCode.js @@ -4,6 +4,8 @@ import TabItem from "@theme/TabItem"; import CodeBlock from "@theme/CodeBlock"; import { marked } from "marked"; import DOMPurify from "isomorphic-dompurify"; +import prettier from "prettier"; +import parserTypeScript from "prettier/parser-typescript"; export function LangChainPyBlock(content) { return { @@ -61,6 +63,33 @@ export function ShellBlock(content, value = "shell", label = "Shell") { }; } +/** + * @param {string} code + * @param {"typescript" | "python"} language + * @returns {string} The formatted code + */ +function formatCode(code, language) { + const languageLower = language.toLowerCase(); + if (languageLower === "python") { + // no-op - Do not format Python code at this time + return code; + } + + try { + const formattedCode = prettier.format(code, { + parser: languageLower, + plugins: [parserTypeScript], + }); + + return formattedCode; + } catch (_) { + // no-op + } + + // If formatting fails, return as is + return code; +} + export function CodeTabs({ tabs, groupId }) { return ( @@ -79,7 +108,7 @@ export function CodeTabs({ tabs, groupId }) { className={tab.value} language={tab.language ?? tab.value} > - {tab.content} + {formatCode(tab.content, tab.language ?? tab.value)} );