UNPKG

@edirect/form-engine

Version:

Achieve form logic reusage with forms expressed in json format.

88 lines (87 loc) 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = require("react"); var _index = require("../../core/index.js"); var _constants = require("../../core/constants.js"); /** * This hooks lets you connect to your form/s in anywherer in your application. Even if you are outside the <FormProvider /> * * You can connect to: * - A specific form * - Several forms identified by their id's * - A group of forms * */ const useForm = ({ onValid, onData, onSubmit, id = _constants.DEFAULT_FORM_HOOK_ID, ids }) => { /** * Subscribe to some event. * * If the hook has more than one formId, will run subscription for all of them * * @param event The event name * @param cb The callback to run on subscription */ const subscribe = (event, cb) => { if (!cb) return; if (ids) { ids.map(formId => (0, _index.getFormInstance)(formId).subscribe(event, ({ data }) => cb((0, _index.getFormInstance)(formId).formData, { field: data.field }))); return; } (0, _index.getFormInstance)(id).subscribe(event, cb); }; /** * Get all the available form data * * Will return to a given form, or data to multiple form in the same data structure * * @returns form data */ const extractFormsData = () => { if (!ids) return (0, _index.getFormInstance)(id).formData; return ids.reduce((acc, formId) => Object.keys(acc).reduce((innerAcc, key) => Object.assign(Object.assign({}, innerAcc), { [key]: Object.assign(Object.assign({}, acc[key]), (0, _index.getFormInstance)(formId).formData[key]) }), {}), { formatted: {}, erroredFields: {}, fields: {}, form: {}, predictableErroredFields: {}, filteredFields: {} }); }; const onDataChange = (0, _react.useCallback)(() => { let data = (0, _index.getFormInstance)(id).formData; if (ids) { data = ids.reduce((acc, formId) => Object.assign(Object.assign({}, acc), { [formId]: (0, _index.getFormInstance)(formId).formData }), {}); } onData && onData(data); }, [onData, onValid]); (0, _react.useEffect)(() => subscribe("ON_FIELD_VALIDATION_TOGGLE" /* EEVents.ON_FIELD_VALIDATION_TOGGLE */, onValid), [onValid]); (0, _react.useEffect)(() => subscribe((0, _index.ALL_NAMESPACE_EVENTS)(_index.CoreEvents.ON_FIELD_CHANGE), onDataChange), [onData, onValid]); (0, _react.useEffect)(() => subscribe((0, _index.ALL_NAMESPACE_EVENTS)(_index.CoreEvents.ON_FIELD_REHYDRATE), onDataChange), [onData, onValid]); (0, _react.useEffect)(() => subscribe(_index.CoreEvents.ON_FORM_SUBMIT, () => { onSubmit && onSubmit(extractFormsData()); }), [onSubmit]); const submitForm = () => (0, _index.getFormInstance)(ids ? ids[0] : id).publish(_index.CoreEvents.ON_FORM_SUBMIT); return { submitForm, formData: extractFormsData }; }; var _default = useForm; exports.default = _default;