@lyra/form-builder
Version:
Lyra form builder
98 lines (76 loc) • 3.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _debounce2 = require('lodash/debounce');
var _debounce3 = _interopRequireDefault(_debounce2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _class, _temp;
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _why = require('is-equal/why');
var _why2 = _interopRequireDefault(_why);
var _withPatchSubscriber = require('./withPatchSubscriber');
var _withPatchSubscriber2 = _interopRequireDefault(_withPatchSubscriber);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*:: import type {Patch} from '../utils/patches'*/
/*:: declare var __DEV__: boolean*/
/*:: type Deserialized = any*/
/*:: type ChildProps = {value: Deserialized}*/
/*:: type Props = {
value: Object,
subscribe: Function,
serialize: (value: Deserialized) => Object,
deserialize: (value: Object) => Deserialized,
applyPatch: (patch: Patch) => Deserialized,
children: ChildProps => ?React$Element<any>
}*/
exports.default = (0, _withPatchSubscriber2.default)((_temp = _class = class ValueSync extends _react2.default.Component {
constructor(props /*: Props*/) {
super();
this.checkDiff = (0, _debounce3.default)(() => {
const propsVal = this.props.value;
const stateVal = this.state.value ? this.props.serialize(this.state.value) : this.state.value;
const notEqual = (0, _why2.default)(propsVal, stateVal);
if (notEqual) {
// eslint-disable-next-line no-console
console.warn('Serialized local input value (%o) out of sync with actual value (%o): %s', propsVal, stateVal, notEqual);
}
}, 5000);
this.state = {
value: props.deserialize(props.value)
};
this.unsubscribe = props.subscribe(({ snapshot, patches, shouldReset }) => {
if (shouldReset) {
// eslint-disable-next-line no-console
console.warn('Serialized local input value was reset due to a patch that targeted an ancestor');
this.setState({ value: props.deserialize(snapshot) });
}
this.receivePatches(patches);
});
}
componentWillUnmount() {
this.unsubscribe();
this.checkDiff.cancel();
}
receivePatches(patches /*: Array<Patch>*/) {
const applyPatch = this.props.applyPatch;
this.setState(prevState => ({
value: patches.reduce(applyPatch, prevState.value)
}));
}
componentDidUpdate() {
if (__DEV__) {
this.checkDiff();
}
}
render() {
const value = this.state.value;
return this.props.children(_extends({}, this.props, { value }));
}
}, _class.contextTypes = {
getValuePath: _propTypes2.default.func,
formBuilder: _propTypes2.default.any
}, _temp));