- Updated `ObjectField`, `ArrayField`, and `FieldWrapper` components to improve flexibility and integration options by supporting additional props like `wrapperProps`. - Added `JsonEditor` for enhanced object editing capabilities with state management and safety checks. - Refactored utility functions and error handling for improved stability and developer experience. - Introduced new test cases to validate `JsonEditor` functionality and schema-based forms handling.
53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import { Suspense, lazy, useState } from "react";
|
|
import { twMerge } from "tailwind-merge";
|
|
import type { CodeEditorProps } from "./CodeEditor";
|
|
const CodeEditor = lazy(() => import("./CodeEditor"));
|
|
|
|
export type JsonEditorProps = Omit<CodeEditorProps, "value" | "onChange"> & {
|
|
value?: object;
|
|
onChange?: (value: object) => void;
|
|
emptyAs?: "null" | "undefined";
|
|
};
|
|
|
|
export function JsonEditor({
|
|
editable,
|
|
className,
|
|
value,
|
|
onChange,
|
|
onBlur,
|
|
emptyAs = "undefined",
|
|
...props
|
|
}: JsonEditorProps) {
|
|
const [editorValue, setEditorValue] = useState<string | null | undefined>(
|
|
JSON.stringify(value, null, 2),
|
|
);
|
|
const handleChange = (given: string) => {
|
|
const value = given === "" ? (emptyAs === "null" ? null : undefined) : given;
|
|
try {
|
|
setEditorValue(value);
|
|
onChange?.(value ? JSON.parse(value) : value);
|
|
} catch (e) {}
|
|
};
|
|
const handleBlur = (e) => {
|
|
setEditorValue(JSON.stringify(value, null, 2));
|
|
onBlur?.(e);
|
|
};
|
|
return (
|
|
<Suspense fallback={null}>
|
|
<CodeEditor
|
|
className={twMerge(
|
|
"flex w-full border border-muted",
|
|
!editable && "opacity-70",
|
|
className,
|
|
)}
|
|
editable={editable}
|
|
_extensions={{ json: true }}
|
|
value={editorValue ?? undefined}
|
|
onChange={handleChange}
|
|
onBlur={handleBlur}
|
|
{...props}
|
|
/>
|
|
</Suspense>
|
|
);
|
|
}
|