@undermuz/react-json-form
Version:
Generate JSON-based forms with react
95 lines (94 loc) • 2.33 kB
JavaScript
// src/flat-form/FlatForm.tsx
import {
useEffect,
createContext,
forwardRef,
useRef,
useCallback
} from "react";
import useForm, { FormContext } from "@undermuz/use-form";
import { EnumSchemeItemType } from "../types.mjs";
import { getDefValueForItem, useFieldsScheme, useSchemeToForm } from "../utils.mjs";
import {
useFlatRef
} from "./useFlatRef.mjs";
import { FieldsBlock } from "./FieldsBlock.mjs";
import { jsx } from "react/jsx-runtime";
var FlatFormContext = createContext({
scheme: [],
isShow: true,
isFormPrimary: true,
isLoading: false,
level: 1
});
var FlatForm = forwardRef(
(props, ref) => {
const {
id,
scheme,
value,
level,
children,
isShow = true,
isLoading = false,
primary = false,
tests,
onChange,
onError
} = props;
const fieldsScheme = useFieldsScheme(scheme);
const formConfig = useSchemeToForm({
scheme: fieldsScheme,
value,
tests,
onChange,
onError
});
const form = useForm(formConfig);
const childFormsRef = useRef({});
const onChildRef = useCallback(
(params) => {
if (!params.ref) {
delete childFormsRef.current[params.id];
return;
}
childFormsRef.current[params.id] = params.ref;
},
[]
);
useEffect(() => {
let shouldUpdate = false;
const new_value = {};
for (const schemeItem of fieldsScheme) {
const { name, type = EnumSchemeItemType.Text } = schemeItem;
const def_value = getDefValueForItem(schemeItem);
if (value[name] !== void 0 || type === EnumSchemeItemType.Checkbox) {
continue;
}
new_value[name] = def_value;
shouldUpdate = true;
}
if (shouldUpdate)
onChange({ ...value, ...new_value });
}, []);
useFlatRef(id, ref, form, childFormsRef);
return /* @__PURE__ */ jsx(FormContext.Provider, { value: form, children: /* @__PURE__ */ jsx(
FieldsBlock,
{
level,
isShow,
isLoading,
scheme,
isFormPrimary: primary,
onFormsRef: onChildRef,
children
}
) });
}
);
FlatForm.displayName = "FlatForm";
var FlatForm_default = FlatForm;
export {
FlatFormContext,
FlatForm_default as default
};