Skip to content

Commit

Permalink
[minor]: Run prettier on all JS code blocks (#187)
Browse files Browse the repository at this point in the history
Runs prettier inline on all `CodeBlock` components.

Skips formatting PY at this time, will require a more complex solution
since prettier does not support programatic formatting for PY code.
  • Loading branch information
agola11 authored Apr 23, 2024
2 parents d39f149 + c5a5ed9 commit f78d205
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down
31 changes: 30 additions & 1 deletion src/components/InstructionsWithCode.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 (
<Tabs groupId={groupId}>
Expand All @@ -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)}
</CodeBlock>
</TabItem>
);
Expand Down

0 comments on commit f78d205

Please sign in to comment.