UNPKG

@catho/quantum

Version:
215 lines (213 loc) 11.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = require("react"); var _propTypes = _interopRequireDefault(require("prop-types")); var _Input = _interopRequireDefault(require("../Input")); var _InputTypes = _interopRequireDefault(require("../Input/InputTypes")); var _jsxRuntime = require("react/jsx-runtime"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } 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 (_Component) { function Form(_props2) { var _this; _classCallCheck(this, Form); _this = _callSuper(this, Form, [_props2]); _defineProperty(_this, "_createClones", function (children) { var _this$state = _this.state, values = _this$state.values, errors = _this$state.errors; var generatedClones = _this._recursiveMap(children, function (child) { if (!Form._isValidElement(child)) { return child; } var _child$props = child.props, name = _child$props.name, error = _child$props.error, _child$props$onChange = _child$props.onChange, _onChange = _child$props$onChange === void 0 ? function () {} : _child$props$onChange; return /*#__PURE__*/(0, _react.cloneElement)(child, { value: values[name], error: errors[name] || error, onChange: function onChange(e) { _this._handleChange(e); _onChange(e); } }); }); return generatedClones; }); _defineProperty(_this, "_recursiveMap", function (children, fn) { return _react.Children.map(children, function (child) { if (! /*#__PURE__*/(0, _react.isValidElement)(child)) { return child; } if (child.props.children) { return fn( /*#__PURE__*/(0, _react.cloneElement)(child, { children: _this._recursiveMap(child.props.children, fn) })); } return fn(child); }); }); _defineProperty(_this, "_findError", function (child) { var props = child.props; var values = _this.state.values; var _props$validate = props.validate, validate = _props$validate === void 0 ? function () {} : _props$validate; var invalid; var _props = _objectSpread(_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) { _this.setState({ valid: false }); } return invalid; }); _defineProperty(_this, "_validateError", function (children) { var errors = _this.state.errors; return _this._recursiveMap(children, function (child) { var name = child.props.name; var _error = _this._findError(child); var newError = errors; newError[name] = _error; _this.setState({ errors: newError }); }); }); _defineProperty(_this, "_handleChange", function (_ref) { var _ref$target = _ref.target, name = _ref$target.name, value = _ref$target.value; var _this$state2 = _this.state, values = _this$state2.values, errors = _this$state2.errors; var newValues = _objectSpread(_objectSpread({}, values), {}, _defineProperty({}, name, value)); var newErrors = errors; newErrors[name] = ''; _this.setState({ errors: newErrors }); _this.setState({ values: newValues }); }); _defineProperty(_this, "handleSubmit", function (event) { event.preventDefault(); var _this$props = _this.props, onSubmit = _this$props.onSubmit, onValidSubmit = _this$props.onValidSubmit, children = _this$props.children; var _this$state3 = _this.state, errors = _this$state3.errors, values = _this$state3.values; _this._validateError(children); var isValid = !Object.values(errors).find(function (e) { return e; }); _this.setState({ valid: isValid }, function () { var updatedValid = _this.state.valid; onSubmit({ valid: updatedValid }); if (isValid) onValidSubmit(values); }); }); _this.state = { values: {}, errors: {}, valid: false }; var _children = _this.props.children; var _values = _this.state.values; _this._recursiveMap(_children, function (child) { if (!Form._isValidElement(child)) return; var _child$props2 = child.props, name = _child$props2.name, value = _child$props2.value; if (value) _values[name] = value; }); return _this; } _inherits(Form, _Component); return _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 /*#__PURE__*/(0, _jsxRuntime.jsx)("form", _objectSpread(_objectSpread({}, _props), {}, { onSubmit: this.handleSubmit, children: this._createClones(children) })); } }]); }(_react.Component); _defineProperty(Form, "_isValidElement", function (element) { return /*#__PURE__*/(0, _react.isValidElement)(element) && [_Input["default"].displayName].concat(_toConsumableArray(typeNames)).includes(element.type.displayName); }); 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 = exports["default"] = Form;