diff --git a/app/src/data/fields/JsonField.ts b/app/src/data/fields/JsonField.ts index c54854b..17ee6b5 100644 --- a/app/src/data/fields/JsonField.ts +++ b/app/src/data/fields/JsonField.ts @@ -64,17 +64,20 @@ export class JsonField import("./CodeEditor")); export type JsonEditorProps = Omit & { value?: object; onChange?: (value: object) => void; - emptyAs?: "null" | "undefined"; + emptyAs?: any; + onInvalid?: (error: Error) => void; }; export function JsonEditor({ @@ -16,29 +17,45 @@ export function JsonEditor({ value, onChange, onBlur, - emptyAs = "undefined", + emptyAs = undefined, + onInvalid, ...props }: JsonEditorProps) { const [editorValue, setEditorValue] = useState( - JSON.stringify(value, null, 2), + value ? JSON.stringify(value, null, 2) : emptyAs, ); + const [error, setError] = useState(false); const handleChange = useDebouncedCallback((given: string) => { - const value = given === "" ? (emptyAs === "null" ? null : undefined) : given; try { - setEditorValue(value); - onChange?.(value ? JSON.parse(value) : value); - } catch (e) {} - }, 500); + setError(false); + onChange?.(given ? JSON.parse(given) : emptyAs); + } catch (e) { + onInvalid?.(e as Error); + setError(true); + } + }, 250); const handleBlur = (e) => { - setEditorValue(JSON.stringify(value, null, 2)); + try { + const formatted = JSON.stringify(value, null, 2); + setEditorValue(formatted); + } catch (e) {} + onBlur?.(e); }; + + useEffect(() => { + if (!editorValue) { + setEditorValue(value ? JSON.stringify(value, null, 2) : emptyAs); + } + }, [value]); + return ( (null); const handleUpdate = useEvent((value: any) => { + setError(null); fieldApi.handleChange(value); }); return ( - +