import * as React from 'react';
import uuid from 'uuid';
import PropTypes from 'prop-types';
class Collection extends React.Component {
static propTypes = {
components: PropTypes.array,
name: PropTypes.string.isRequired
}
static defaultProps = {
components: [],
initialValue: []
}
_value = []
_controls = {}
_controlIDs = []
static contextTypes = {
onControlMount: PropTypes.func,
onControlUnmount: PropTypes.func,
onControlChange: PropTypes.func,
}
static childContextTypes = {
onControlMount: PropTypes.func,
onControlUnmount: PropTypes.func,
onControlChange: PropTypes.func,
onControlChangeID: PropTypes.func,
}
getChildContext() {
return {
onControlMount: ::this.handleControlMount,
onControlUnmount: ::this.handleControlUnmount,
onControlChange: ::this.handleControlChange,
onControlChangeID: ::this.handleControlChangeID
};
}
handleControlMount(id, control) {
this._controls[id] = control;
control.setForm(this._form);
}
handleControlUnmount(id) {
delete this._controls[id];
}
handleControlChangeID(prevId, newId, control) {
delete this._controlIDs[prevId];
this._controlIDs[newId] = control;
}
componentDidMount() {
this._id = uuid.v4();
this.setValue(this.props.initialValue);
this.context.onControlMount(this._id, this, this.value);
}
componentWillUnmount() {
this.context.onControlUnmount(this._id, this);
}
setForm(form) {
this._form = form;
}
get name() {
return this.props.name;
}
get value() {
return this._value;
}
setValue(val) {
this._value = val;
return new Promise(resolve => {
this.forceUpdate(() => resolve());
});
}
addValue(val) {
this.setValue([...this.value, val]);
}
handleControlChange(id, val) {
let i = this._controlIDs.findIndex(cid => cid == id);
let value = [...this._value];
value[i] = val;
this.setValue(value);
Eif (this.props.onChange) {
this.props.onChange(this.value);
}
}
showErrors() {
Object.entries(this._controls).forEach(c => c[1].showErrors());
}
validate() {
return Object.entries(this._controls).map(
(c, cIndex) => c[1].validate().map(res => ({ ...res, index: cIndex }))
).reduce((a, b) => a.concat(b));
}
render() {
this._controlIDs = [];
return this.value.map((v, i) => {
let el = this.props.component({value: v}), cid;
cid = uuid.v4();
this._controlIDs.push(cid);
el = React.cloneElement(el, {
key: i,
value: this.value[i],
cid
});
return el;
});
}
}
export default Collection; |