Start adding changes to address json fields

This commit is contained in:
Ola Hungerford
2025-02-26 09:50:47 -07:00
parent 717c394d3b
commit 592dacad39
2 changed files with 81 additions and 15 deletions

View File

@@ -1,3 +1,4 @@
import { useState, useEffect } from "react";
import Editor from "react-simple-code-editor";
import Prism from "prismjs";
import "prismjs/components/prism-json";
@@ -10,34 +11,63 @@ interface JsonEditorProps {
error?: string;
}
const JsonEditor = ({ value, onChange, error }: JsonEditorProps) => {
const JsonEditor = ({ value, onChange, error: externalError }: JsonEditorProps) => {
const [editorContent, setEditorContent] = useState(value);
const [internalError, setInternalError] = useState<string | undefined>(undefined);
useEffect(() => {
setEditorContent(value);
}, [value]);
const formatJson = (json: string): string => {
try {
// Handle empty arrays and objects specifically
if (json.trim() === '[]') return '[]';
if (json.trim() === '{}') return '{}';
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={() => onChange(formatJson(value))}
onClick={handleFormatJson}
>
Format JSON
</Button>
</div>
<div
className={`border rounded-md ${
error ? "border-red-500" : "border-gray-200 dark:border-gray-800"
displayError ? "border-red-500" : "border-gray-200 dark:border-gray-800"
}`}
>
<Editor
value={value}
onValueChange={onChange}
value={editorContent}
onValueChange={handleEditorChange}
highlight={(code) =>
Prism.highlight(code, Prism.languages.json, "json")
}
@@ -51,7 +81,7 @@ const JsonEditor = ({ value, onChange, error }: JsonEditorProps) => {
className="w-full"
/>
</div>
{error && <p className="text-sm text-red-500 mt-1">{error}</p>}
{displayError && <p className="text-sm text-red-500 mt-1">{displayError}</p>}
</div>
);
};