import * as React from 'react';
import PropTypes from 'prop-types';
class Form extends React.Component {
_controls = {};
_values = {};
_errors = {};
static propTypes = {
onSubmit: PropTypes.func,
onSubmitFailed: PropTypes.func,
onChange: PropTypes.func,
}
static childContextTypes = {
onControlMount: PropTypes.func,
onControlUnmount: PropTypes.func,
onControlChange: PropTypes.func,
onErrorMount: PropTypes.func,
onErrorUnmount: PropTypes.func,
}
getChildContext() {
return {
onControlMount: ::this.handleControlMount,
onControlUnmount: ::this.handleControlUnmount,
onControlChange: ::this.handleControlChange,
onErrorMount: ::this.handleErrorMount,
onErrorUnmount: ::this.handleErrorUnmount,
};
}
handleControlChange(id, val) {
this._values[id] = val;
if (this.props.onChange) {
let component = this._controls[id];
this.props.onChange({[component.name]: val}, this.value);
}
for (let [id, err] of Object.entries(this._errors)) {
err.onFormChanged(this.value);
}
}
handleControlMount(id, component, initialValue) {
this._controls[id] = component;
this._values[id] = initialValue;
component.setForm(this);
}
handleControlUnmount(id) {
delete this._controls[id];
delete this._values[id];
}
handleErrorMount(id, component) {
this._errors[id] = component;
}
handleErrorUnmount(id) {
delete this._errors[id];
}
handleSubmit(e) {
e.preventDefault();
let err = false;
for (let [id, control] of Object.entries(this._controls)) {
control.showErrors();
if (!err && control.validate().length) {
err = true;
}
}
if (!err) {
if (this.props.onSubmit) {
this.props.onSubmit(this.value, e);
}
} else {
Eif (this.props.onSubmitFailed) {
this.props.onSubmitFailed(this.value, e);
}
}
}
get value() {
let data = {};
for (let [id, component] of Object.entries(this._controls)) {
data[component.name] = this._values[id];
}
return data;
}
reset() {
for (let [id, control] of Object.entries(this._controls)) {
control.reset();
}
}
setValue(data={}) {
let promises = [],
newValues = {};
for (let [name, value] of Object.entries(data)) {
for (let [id, control] of Object.entries(this._controls)) {
if (control.name == name) {
newValues[id] = value;
promises.push(control.setValue(value));
}
}
}
this._values = newValues;
return Promise.all(promises);
}
render() {
return (
<form onSubmit={::this.handleSubmit}>
{this.props.children}
</form>
);
}
}
export default Form;
|