@trendmicro/react-validation
Version:
299 lines (253 loc) • 14.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _ensureArray = require('./utils/ensure-array');
var _ensureArray2 = _interopRequireDefault(_ensureArray);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var noop = function noop() {};
var createForm = function createForm(options) {
return function (WrappedComponent) {
var _class, _temp2;
return _temp2 = _class = function (_PureComponent) {
_inherits(Form, _PureComponent);
function Form() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Form);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Form.__proto__ || Object.getPrototypeOf(Form)).call.apply(_ref, [this].concat(args))), _this), _this.state = _this.getInitialState(), _this.options = _extends({}, options), _this.register = function (component) {
if (!(component && component.props)) {
return;
}
var hasCheckedProperty = component.props.type === 'radio' || component.props.type === 'checkbox';
_this.setState(function (state) {
return {
components: [].concat(_toConsumableArray(state.components), [{
component: component,
props: _extends({}, component.props, {
value: component.props.value || ''
}, hasCheckedProperty ? { checked: !!component.props.checked } : {})
}])
};
}, function () {
_this.invalidate();
});
}, _this.unregister = function (component) {
_this.setState(function (state) {
return {
components: state.components.reduce(function (components, c) {
if (c.component === component) {
return components;
}
components.push(c);
return components;
}, [])
};
}, function () {
_this.invalidate();
});
}, _this.setProps = function (component, props) {
_this.setState(function (state) {
return {
components: state.components.map(function (c) {
// Update component props
if (c.component === component) {
return _extends({}, c, {
props: _extends({}, c.props, props)
});
}
// Uncheck other radio buttons in the same group
if (c.props.type === 'radio' && c.component.props.name === component.props.name) {
return _extends({}, c, {
props: _extends({}, c.props, {
checked: false
})
});
}
// Other components
return c;
})
};
}, function () {
_this.invalidate();
});
}, _this.getProps = function (component) {
for (var i = 0; i < _this.state.components.length; ++i) {
if (component === _this.state.components[i].component) {
return _this.state.components[i].props;
}
}
return null;
}, _this.invalidate = function () {
var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop;
if (typeof callback !== 'function') {
callback = noop;
}
var errors = [];
_this.setState(function (state) {
var components = state.components.reduce(function (acc, c) {
var name = c.props.name;
if (!acc[name]) {
acc[name] = [];
}
acc[name].push(c.props);
return acc;
}, {});
return {
components: state.components.map(function (c) {
var validations = (0, _ensureArray2.default)(c.props.validations);
var error = null;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = validations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var validation = _step.value;
error = validation(c.props.value, c.props, components);
if (error) {
errors.push(_extends({}, c.props, {
error: error
}));
break;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return _extends({}, c, {
props: _extends({}, c.props, {
error: error
})
});
})
};
}, function () {
if (typeof _this.options.onValidate === 'function') {
_this.options.onValidate.call(_this, _this.props, errors);
}
if (errors.length > 0) {
callback(errors);
} else {
callback();
}
});
}, _this.validate = function () {
var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
if (typeof name === 'function') {
callback = name;
name = '';
}
if (typeof callback !== 'function') {
callback = noop;
}
_this.setState(function (state) {
return {
components: state.components.map(function (c) {
if (!name || name === c.props.name) {
return _extends({}, c, {
props: _extends({}, c.props, {
blurred: true,
changed: true
})
});
}
return c;
})
};
}, function () {
_this.invalidate(callback);
});
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Form, [{
key: 'getChildContext',
value: function getChildContext() {
return {
$validation: {
register: this.register,
unregister: this.unregister,
setProps: this.setProps,
getProps: this.getProps
}
};
}
}, {
key: 'getInitialState',
value: function getInitialState() {
return {
components: []
};
}
}, {
key: 'getValues',
value: function getValues() {
return this.state.components.reduce(function (values, c) {
var _c$props = c.props,
type = _c$props.type,
name = _c$props.name,
value = _c$props.value,
checked = _c$props.checked;
if ((type === 'radio' || type === 'checkbox') && !checked) {
values[name] = values[name] || '';
return values;
}
if (!Object.prototype.hasOwnProperty.call(values, name)) {
values[name] = value;
} else {
values[name] = !!('' + values[name]) ? (0, _ensureArray2.default)(values[name]).concat(value) : value;
}
return values;
}, {});
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(WrappedComponent, this.props);
}
}, {
key: 'errors',
get: function get() {
return this.state.components.filter(function (c) {
return !!c.props.error;
}).map(function (c) {
return c.props;
});
}
}]);
return Form;
}(_react.PureComponent), _class.displayName = 'Form(' + WrappedComponent.name + ')', _class.childContextTypes = {
$validation: _propTypes2.default.shape({
register: _propTypes2.default.func.isRequired,
unregister: _propTypes2.default.func.isRequired,
setProps: _propTypes2.default.func.isRequired,
getProps: _propTypes2.default.func.isRequired
})
}, _temp2;
};
};
exports.default = createForm;