"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.formFromFields = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var Yup = _interopRequireWildcard(require("yup"));

var _lodash = _interopRequireDefault(require("lodash"));

var _formik = require("formik");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }

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 _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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, 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; }

var formFromFields = function formFromFields(fields, formikProps, dynamicRequire) {
  return Object.keys(fields).map(function (id) {
    return _react["default"].createElement(fields[id].component, {
      key: id,
      id: id,
      label: fields[id].label,
      options: _objectSpread({}, fields[id].options),
      formik: formikProps,
      isRequired: !!(dynamicRequire[id] || _lodash["default"].get(fields[id], "validation._exclusive.required"))
    });
  });
};

exports.formFromFields = formFromFields;

var Form = function (_React$Component) {
  _inherits(Form, _React$Component);

  function Form() {
    _classCallCheck(this, Form);

    return _possibleConstructorReturn(this, _getPrototypeOf(Form).apply(this, arguments));
  }

  _createClass(Form, [{
    key: "render",
    value: function render() {
      var _this = this;

      var _this$props = this.props,
          fields = _this$props.fields,
          initialValues = _this$props.initialValues,
          sections = _this$props.sections,
          children = _this$props.children,
          validate = _this$props.validate,
          handleReset = _this$props.handleReset;
      var fieldIds = Object.keys(fields);
      var validations = Object.fromEntries(fieldIds.map(function (id) {
        return [id, fields[id].validation];
      }));
      var validationSchema = Yup.object(validations);
      return _react["default"].createElement(_formik.Formik, {
        validate: validate,
        initialValues: initialValues,
        enableReinitialize: true,
        validationSchema: validationSchema,
        handleReset: handleReset,
        onSubmit: function onSubmit(values, formikBag) {
          var addHandlers = function addHandlers(promise) {
            return promise.then(function (result) {
              formikBag.resetForm();
              formikBag.setSubmitting(false);
              return result;
            }, function (error) {
              formikBag.setSubmitting(false);
              formikBag.setErrors(error.validationErrors);
              throw error;
            });
          };

          return _this.props.onSubmit(values, addHandlers);
        },
        render: function render(formikProps) {
          var dynamicRequire = validate ? validate(formikProps.values) : {};
          var visibleIf = formikProps.values._visibleIf ? formikProps.values._visibleIf : {};

          var form = _react["default"].createElement(_react.Fragment, null, formFromFields(fields, formikProps, dynamicRequire));

          var formSections = sections && sections.length > 0 ? Object.fromEntries(sections.map(function (section) {
            return [section, _react["default"].createElement(_react.Fragment, null, formFromFields(_lodash["default"].pickBy(fields, function (field) {
              return field.section === section;
            }), formikProps, dynamicRequire))];
          })) : {};
          var formFields = fieldIds && fieldIds.length > 0 ? Object.fromEntries(fieldIds.map(function (id) {
            return [id, _react["default"].createElement(_react.Fragment, null, formFromFields(_lodash["default"].pick(fields, id), formikProps, dynamicRequire))];
          })) : {};
          return _react["default"].createElement("div", null, children({
            form: form,
            formSections: formSections,
            formFields: formFields,
            isValid: formikProps.isValid,
            isDirty: formikProps.dirty,
            isSubmitting: formikProps.isSubmitting,
            handleSubmit: formikProps.handleSubmit,
            handleCancel: formikProps.handleReset,
            resetForm: formikProps.resetForm,
            values: formikProps.values,
            visibleIf: visibleIf,
            formErrors: formikProps.errors,
            initialValues: formikProps.initialValues
          }));
        }
      });
    }
  }]);

  return Form;
}(_react["default"].Component);

Form.propTypes = {
  fields: _propTypes["default"].objectOf(_propTypes["default"].shape({
    label: _propTypes["default"].string,
    component: _propTypes["default"].component,
    validation: _propTypes["default"].shape({})
  })).isRequired,
  initialValues: _propTypes["default"].shape({}),
  onSubmit: _propTypes["default"].func.isRequired,
  children: _propTypes["default"].func.isRequired,
  validate: _propTypes["default"].func,
  handleReset: _propTypes["default"].func,
  sections: _propTypes["default"].oneOfType([_propTypes["default"].array])
};
var _default = Form;
exports["default"] = _default;