"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Form = Form;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

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

var _context2 = require("./context");

var _formValidation = require("./formValidation");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

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

var __jsx = _react["default"].createElement;

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) { (0, _defineProperty2["default"])(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; }

/** Keep track of form fields and generate validation schema from fields */
var useFormFieldsValidator = function useFormFieldsValidator() {
  var _React$useState = _react["default"].useState({}),
      _React$useState2 = (0, _slicedToArray2["default"])(_React$useState, 2),
      fields = _React$useState2[0],
      setFields = _React$useState2[1];
  /**
   * Register a form field
   * saves it in fields state to allow using asynchronously
   */


  var registerField = _react["default"].useCallback(function (props) {
    setFields(function ($fields) {
      return _objectSpread(_objectSpread({}, $fields), {}, (0, _defineProperty2["default"])({}, props.name, props.schema));
    });
  }, []);

  return {
    fields: fields,
    registerField: registerField
  };
};

function Form(props) {
  var onSubmit = props.onSubmit,
      _props$initialValue = props.initialValue,
      initialValue = _props$initialValue === void 0 ? {} : _props$initialValue,
      onFormChange = props.onChange,
      rest = (0, _objectWithoutProperties2["default"])(props, ["onSubmit", "initialValue", "onChange"]);

  var _useFormFieldsValidat = useFormFieldsValidator(),
      fields = _useFormFieldsValidat.fields,
      registerField = _useFormFieldsValidat.registerField;

  var _useState = (0, _react.useState)(initialValue),
      value = _useState[0],
      setValue = _useState[1];

  var _useState2 = (0, _react.useState)({}),
      errors = _useState2[0],
      setErrors = _useState2[1];

  (0, _react.useEffect)(function () {
    if (props.errors !== errors) {
      setErrors(_objectSpread(_objectSpread({}, errors), props.errors));
    }
  }, [props.errors]);

  var getFormValue = function getFormValue() {
    return value;
  };

  var getFieldValue = function getFieldValue(name) {
    return value[name] || '';
  };

  var clearForm = function clearForm() {
    return setValue(initialValue);
  };

  var getFormFieldError = function getFormFieldError(name) {
    return errors ? errors[name] : null;
  };

  var deleteFormFieldError = function deleteFormFieldError(name) {
    if (errors && errors[name]) {
      setErrors(function (prevErrors) {
        var updated = prevErrors;
        delete updated[name];
        return updated;
      });
    }
  };

  var onChange = (0, _react.useCallback)(function (data) {
    // supports a single {name: value} or an array of {name: value} pairs
    var name = data.name,
        changeValue = data.value;

    if (Array.isArray(data)) {
      var newValues = {};
      data.forEach(function (item) {
        newValues[item.name] = item.value;
      });
      setValue(function (val) {
        return _objectSpread(_objectSpread({}, val), newValues);
      });
    } else {
      setValue(function (val) {
        return _objectSpread(_objectSpread({}, val), {}, (0, _defineProperty2["default"])({}, name, changeValue));
      });
    }

    if (onFormChange) {
      onFormChange(data);
    }
  }, []);

  var formOnSubmit = _react["default"].useCallback( /*#__PURE__*/function () {
    var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(e) {
      var onValidate;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              e.preventDefault();
              e.stopPropagation();

              onValidate = function onValidate(_ref2) {
                var isSubmitValid = _ref2.isValid,
                    submitErrors = _ref2.errors;

                if (isSubmitValid) {
                  if (onSubmit) {
                    onSubmit(e, {
                      getFormValue: getFormValue,
                      clearForm: clearForm
                    });
                  }
                } else {
                  setErrors(submitErrors);
                }
              };

              _context.next = 5;
              return (0, _formValidation.validate)(value, fields, onValidate);

            case 5:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }(), [value, fields]);

  return __jsx(_context2.FormContext.Provider, {
    value: {
      fields: fields,
      registerField: registerField,
      getFormValue: getFormValue,
      getFieldValue: getFieldValue,
      onChange: onChange,
      clearForm: clearForm,
      getFormFieldError: getFormFieldError,
      deleteFormFieldError: deleteFormFieldError
    }
  }, __jsx("form", (0, _extends2["default"])({
    onSubmit: formOnSubmit,
    noValidate: true
  }, rest), props.children));
}
//# sourceMappingURL=Form.js.map