UNPKG

@age/quantum

Version:
265 lines (199 loc) 10.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _Input = _interopRequireDefault(require("../Input")); var _InputTypes = _interopRequireDefault(require("../Input/InputTypes")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _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; }; return _extends.apply(this, arguments); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function execValidate(validate, props) { if (typeof validate === 'function') { return validate(props); } var fn = validate.validate, error = validate.error; var msg = fn(props); return msg ? error || msg : ''; } var typeNames = Object.values(_InputTypes.default).map(function (InputType) { return InputType.displayName; }); var Form = /*#__PURE__*/ function (_React$Component) { _inherits(Form, _React$Component); function Form(props) { var _this; _classCallCheck(this, Form); _this = _possibleConstructorReturn(this, _getPrototypeOf(Form).call(this, props)); _initialiseProps.call(_assertThisInitialized(_this)); _this.state = { values: {}, errors: {}, valid: false }; var children = _this.props.children; var values = _this.state.values; _react.default.Children.map(children, function (child) { if (!Form._isValidElement(child)) return; var _child$props = child.props, name = _child$props.name, value = _child$props.value; if (value) values[name] = value; }); return _this; } _createClass(Form, [{ key: "render", value: function render() { // Removing invalid form props, to avoid warnings var _props = _objectSpread({}, this.props); var children = _props.children; delete _props.onValidSubmit; return _react.default.createElement("form", _extends({}, _props, { onSubmit: this.handleSubmit }), this._createClones(children)); } }]); return Form; }(_react.default.Component); Form._isValidElement = function (element) { return _react.default.isValidElement(element) && [_Input.default.displayName].concat(_toConsumableArray(typeNames)).includes(element.type.displayName); }; var _initialiseProps = function _initialiseProps() { var _this2 = this; this._createClones = function (children) { var _this2$state = _this2.state, values = _this2$state.values, errors = _this2$state.errors; return _react.default.Children.map(children, function (child) { if (!Form._isValidElement(child)) { return child; } var _child$props2 = child.props, name = _child$props2.name, error = _child$props2.error, _child$props2$onChang = _child$props2.onChange, _onChange = _child$props2$onChang === void 0 ? function () {} : _child$props2$onChang; return _react.default.cloneElement(child, { value: values[name], error: errors[name] || error, onChange: function onChange(e) { _this2._handleChange(e); _onChange(e); } }); }); }; this._findError = function (child) { var props = child.props; var values = _this2.state.values; var _props$validate = props.validate, validate = _props$validate === void 0 ? function () {} : _props$validate; var invalid; var _props = _objectSpread({}, props, { value: values[props.name] }); if (Array.isArray(validate)) { for (var i = 0; i < validate.length; i += 1) { invalid = execValidate(validate[i], _props); // Stop validation when the first occurs if (invalid) break; } } else { invalid = execValidate(validate, _props); } if (invalid) { _this2.setState({ valid: false }); } return invalid; }; this._validateError = function (children) { var errors = _this2.state.errors; return _react.default.Children.map(children, function (child) { var name = child.props.name; var _error = _this2._findError(child); var newError = errors; newError[name] = _error; _this2.setState({ errors: newError }); }); }; this._handleChange = function (_ref) { var _ref$target = _ref.target, name = _ref$target.name, value = _ref$target.value; var _this2$state2 = _this2.state, values = _this2$state2.values, errors = _this2$state2.errors; var newValues = _objectSpread({}, values, _defineProperty({}, name, value)); var newErrors = errors; newErrors[name] = ''; _this2.setState({ errors: newErrors }); _this2.setState({ values: newValues }); }; this.handleSubmit = function (event) { event.preventDefault(); var _this2$props = _this2.props, onSubmit = _this2$props.onSubmit, onValidSubmit = _this2$props.onValidSubmit, children = _this2$props.children; var _this2$state3 = _this2.state, errors = _this2$state3.errors, values = _this2$state3.values; _this2._validateError(children); var isValid = !Object.values(errors).find(function (e) { return e; }); _this2.setState({ valid: isValid }, function () { var updatedValid = _this2.state.valid; onSubmit({ valid: updatedValid }); if (isValid) onValidSubmit(values); }); }; }; Form.defaultProps = { onSubmit: function onSubmit() {}, onValidSubmit: function onValidSubmit() {}, noValidate: true }; Form.propTypes = { children: _propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.node), _propTypes.default.node]).isRequired, /** A callback triggered every submit trial, with a flag that indicates that it is valid */ onSubmit: _propTypes.default.func, /** A callback triggered every valid submit, with a object with input values */ onValidSubmit: _propTypes.default.func, /** Default html attribute, that prevents default browser validations */ noValidate: _propTypes.default.bool }; var _default = Form; exports.default = _default;