@undermuz/react-json-form
Version:
Generate JSON-based forms with react
86 lines (85 loc) • 2.17 kB
JavaScript
// src/JsonForm.tsx
import {
useEffect,
useState,
useRef,
forwardRef
} from "react";
import { ErrorBoundary } from "react-error-boundary";
import ErrorFallback from "./components/ErrorFallback.mjs";
import { useDefSchemeValue, useSafeValue } from "./utils.mjs";
import { useJsonFormComponents } from "./contexts/ui.mjs";
import ValueContext from "./contexts/value.mjs";
import Form from "./Form.mjs";
import ContextId from "./contexts/id.mjs";
import { jsx } from "react/jsx-runtime";
var ContextIdForward = ({
level = 1,
children
}) => {
const contextId = useRef({ lastId: 0 });
if (level > 1) {
return children || null;
}
return /* @__PURE__ */ jsx(ContextId.Provider, { value: contextId.current, children: children || null });
};
var JsonForm = forwardRef((props, ref) => {
const {
multiple = false,
scheme,
level = 1,
fillArrayDefault = true,
onError
} = props;
const isMount = useRef(false);
const [errors, setErrors] = useState(
multiple ? [] : {}
);
const Components = useJsonFormComponents();
const defValue = useDefSchemeValue(scheme);
const value = useSafeValue(
props.value,
defValue,
multiple,
fillArrayDefault
);
const onErrorRef = useRef(onError);
onErrorRef.current = onError;
useEffect(() => {
if (!isMount.current) {
return;
}
onErrorRef.current?.(errors);
}, [errors]);
useEffect(() => {
isMount.current = true;
return () => {
isMount.current = false;
};
}, []);
return /* @__PURE__ */ jsx(
ErrorBoundary,
{
FallbackComponent: ErrorFallback,
onReset: () => {
},
children: /* @__PURE__ */ jsx(ContextIdForward, { level, children: /* @__PURE__ */ jsx(ValueContext.Provider, { value, children: /* @__PURE__ */ jsx(Components.JsonForm, { ...props, children: /* @__PURE__ */ jsx(
Form,
{
...props,
ref,
level,
errors,
value,
def: defValue,
onError: setErrors
}
) }) }) })
}
);
});
JsonForm.displayName = "JsonForm";
var JsonForm_default = JsonForm;
export {
JsonForm_default as default
};