refactor: JsonEditor

This commit is contained in:
cgoing
2025-03-28 15:16:17 +09:00
parent 18ca6e28a7
commit 8180b0bd6f
2 changed files with 24 additions and 29 deletions

View File

@@ -3,7 +3,6 @@ import Editor from "react-simple-code-editor";
import Prism from "prismjs";
import "prismjs/components/prism-json";
import "prismjs/themes/prism.css";
import { Button } from "@/components/ui/button";
interface JsonEditorProps {
value: string;
@@ -16,49 +15,25 @@ const JsonEditor = ({
onChange,
error: externalError,
}: JsonEditorProps) => {
const [editorContent, setEditorContent] = useState(value);
const [editorContent, setEditorContent] = useState(value || "");
const [internalError, setInternalError] = useState<string | undefined>(
undefined,
);
useEffect(() => {
setEditorContent(value);
setEditorContent(value || "");
}, [value]);
const formatJson = (json: string): string => {
try {
return JSON.stringify(JSON.parse(json), null, 2);
} catch {
return json;
}
};
const handleEditorChange = (newContent: string) => {
setEditorContent(newContent);
setInternalError(undefined);
onChange(newContent);
};
const handleFormatJson = () => {
try {
const formatted = formatJson(editorContent);
setEditorContent(formatted);
onChange(formatted);
setInternalError(undefined);
} catch (err) {
setInternalError(err instanceof Error ? err.message : "Invalid JSON");
}
};
const displayError = internalError || externalError;
return (
<div className="relative space-y-2">
<div className="flex justify-end">
<Button variant="outline" size="sm" onClick={handleFormatJson}>
Format JSON
</Button>
</div>
<div className="relative">
<div
className={`border rounded-md ${
displayError