Skip to content

Commit

Permalink
Fix formatCode function
Browse files Browse the repository at this point in the history
  • Loading branch information
victortrinh2 committed Nov 12, 2024
1 parent 20c9429 commit ad9b730
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions .storybook/components/snippet/useFormattedCode.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { isNil } from "@components/shared/index.ts";
import { useMemo } from "react";
import prettier from "prettier/standalone";
import prettierBabel from "prettier/parser-babel";
import prettierPostCss from "prettier/parser-postcss";
import * as prettier from "prettier/standalone";
import prettierBabel from "prettier/plugins/babel";
import prettierPostCss from "prettier/plugins/postcss";
import prettierEstree from "prettier/plugins/estree";

const PrettierParser = {
"javascript": "babel",
Expand All @@ -11,28 +11,27 @@ const PrettierParser = {
"css": "css"
};


export function useFormattedCode(code: string, language: string) {
return useMemo(async () => {
await formatCode(code, language);
}, [code, language]);
}

export async function formatCode(code: string, language: string) {
export function formatCode(code: string, language: string) {
const parser = PrettierParser[language];

if (!isNil(parser)) {
const prettyCode = (await prettier
let prettyCode = code;

prettier
.format(code, {
parser: parser,
plugins: [prettierBabel, prettierPostCss],
plugins: [prettierBabel, prettierPostCss, prettierEstree],
tabWidth: 4,
arrowParens: "avoid",
printWidth: 100,
trailingComma: "none"
}))
.replace(">;", ">")
.trim();
})
.then(result => {
prettyCode = result.replace(">;", ">").trim();
})
.catch(() => {
prettyCode = code.trim();
});

return prettyCode;
}
Expand Down

0 comments on commit ad9b730

Please sign in to comment.