FormContext.js
2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.FormProvider = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _objectSpread3 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var React = _interopRequireWildcard(require("react"));
var FormContext = /*#__PURE__*/React.createContext({
triggerFormChange: function triggerFormChange() {},
triggerFormFinish: function triggerFormFinish() {},
registerForm: function registerForm() {},
unregisterForm: function unregisterForm() {}
});
var FormProvider = function FormProvider(_ref) {
var validateMessages = _ref.validateMessages,
onFormChange = _ref.onFormChange,
onFormFinish = _ref.onFormFinish,
children = _ref.children;
var formContext = React.useContext(FormContext);
var formsRef = React.useRef({});
return /*#__PURE__*/React.createElement(FormContext.Provider, {
value: (0, _objectSpread3.default)((0, _objectSpread3.default)({}, formContext), {}, {
validateMessages: (0, _objectSpread3.default)((0, _objectSpread3.default)({}, formContext.validateMessages), validateMessages),
// =========================================================
// = Global Form Control =
// =========================================================
triggerFormChange: function triggerFormChange(name, changedFields) {
if (onFormChange) {
onFormChange(name, {
changedFields: changedFields,
forms: formsRef.current
});
}
formContext.triggerFormChange(name, changedFields);
},
triggerFormFinish: function triggerFormFinish(name, values) {
if (onFormFinish) {
onFormFinish(name, {
values: values,
forms: formsRef.current
});
}
formContext.triggerFormFinish(name, values);
},
registerForm: function registerForm(name, form) {
if (name) {
formsRef.current = (0, _objectSpread3.default)((0, _objectSpread3.default)({}, formsRef.current), {}, (0, _defineProperty2.default)({}, name, form));
}
formContext.registerForm(name, form);
},
unregisterForm: function unregisterForm(name) {
var newForms = (0, _objectSpread3.default)({}, formsRef.current);
delete newForms[name];
formsRef.current = newForms;
formContext.unregisterForm(name);
}
})
}, children);
};
exports.FormProvider = FormProvider;
var _default = FormContext;
exports.default = _default;