diff --git a/website/src/components/molecules/codeBox.tsx b/website/src/components/molecules/codeBox.tsx index fc156e1e..50b758b4 100644 --- a/website/src/components/molecules/codeBox.tsx +++ b/website/src/components/molecules/codeBox.tsx @@ -3,6 +3,8 @@ import { isString, isDefined, tryCatch } from '@elbwalker/utils'; import { Highlight, themes as prismThemes } from 'prism-react-renderer'; import Editor from 'react-simple-code-editor'; import { useState } from 'react'; +import prettier from 'prettier/standalone'; +import parserBabel from 'prettier/parser-babel'; interface FormatValueProps { intent?: number; @@ -66,6 +68,7 @@ const CodeBox: React.FC = ({ }) => { const [copied, setCopied] = useState(false); const [isHovered, setIsHovered] = useState(false); + const [isFormatHovered, setIsFormatHovered] = useState(false); const handleCopy = async () => { tryCatch(async () => { @@ -75,6 +78,34 @@ const CodeBox: React.FC = ({ })(); }; + const handleFormat = tryCatch(() => { + // Check if the content is a complete statement + const isCompleteStatement = /^[a-zA-Z_$][a-zA-Z0-9_$]*\s*=/.test( + value.trim(), + ); + + // If it's not a complete statement, wrap it in a return statement + const contentToFormat = isCompleteStatement ? value : `return ${value}`; + + const formattedValue = prettier.format(contentToFormat, { + parser: 'babel', + plugins: [parserBabel], + semi: true, + singleQuote: true, + trailingComma: 'es5', + printWidth: 80, + tabWidth: 2, + useTabs: false, + }); + + // Remove the 'return ' prefix if we added it + const finalValue = isCompleteStatement + ? formattedValue + : formattedValue.replace(/^return\s+/, ''); + + onChange?.(finalValue); + }); + const highlightCode = (code: string) => ( {({ tokens, getLineProps, getTokenProps }) => ( @@ -102,32 +133,64 @@ const CodeBox: React.FC = ({
{label}
- - {(isHovered || copied) && ( -
- {copied ? 'Copied!' : 'Copy'} +
+
+ + {isFormatHovered && ( +
+ Format +
+ )}
- )} +
+ + {(isHovered || copied) && ( +
+ {copied ? 'Copied!' : 'Copy'} +
+ )} +
+
)}