"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

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

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

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

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

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

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

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

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

var _classnames = _interopRequireDefault(require("classnames"));

var _rcFieldForm = require("rc-field-form");

var _omit = _interopRequireDefault(require("omit.js"));

var _row = _interopRequireDefault(require("../grid/row"));

var _configProvider = require("../config-provider");

var _type = require("../_util/type");

var _warning = _interopRequireDefault(require("../_util/warning"));

var _FormItemLabel = _interopRequireDefault(require("./FormItemLabel"));

var _FormItemInput = _interopRequireDefault(require("./FormItemInput"));

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

var _util = require("./util");

var __rest = void 0 && (void 0).__rest || function (s, e) {
  var t = {};

  for (var p in s) {
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  }

  if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};

var ValidateStatuses = (0, _type.tuple)('success', 'warning', 'error', 'validating', '');
var MemoInput = /*#__PURE__*/React.memo(function (_ref) {
  var children = _ref.children;
  return children;
}, function (prev, next) {
  return prev.value === next.value && prev.update === next.update;
});

function hasValidName(name) {
  if (name === null) {
    (0, _warning["default"])(false, 'Form.Item', '`null` is passed as `name` property');
  }

  return !(name === undefined || name === null);
}

function FormItem(props) {
  var name = props.name,
      fieldKey = props.fieldKey,
      noStyle = props.noStyle,
      dependencies = props.dependencies,
      customizePrefixCls = props.prefixCls,
      style = props.style,
      className = props.className,
      shouldUpdate = props.shouldUpdate,
      hasFeedback = props.hasFeedback,
      help = props.help,
      rules = props.rules,
      validateStatus = props.validateStatus,
      children = props.children,
      required = props.required,
      label = props.label,
      _props$trigger = props.trigger,
      trigger = _props$trigger === void 0 ? 'onChange' : _props$trigger,
      _props$validateTrigge = props.validateTrigger,
      validateTrigger = _props$validateTrigge === void 0 ? 'onChange' : _props$validateTrigge,
      restProps = __rest(props, ["name", "fieldKey", "noStyle", "dependencies", "prefixCls", "style", "className", "shouldUpdate", "hasFeedback", "help", "rules", "validateStatus", "children", "required", "label", "trigger", "validateTrigger"]);

  var destroyRef = React.useRef(false);

  var _React$useContext = React.useContext(_configProvider.ConfigContext),
      getPrefixCls = _React$useContext.getPrefixCls;

  var formContext = React.useContext(_context.FormContext);

  var _React$useContext2 = React.useContext(_context.FormItemContext),
      updateItemErrors = _React$useContext2.updateItemErrors;

  var _React$useState = React.useState(!!help),
      _React$useState2 = (0, _slicedToArray2["default"])(_React$useState, 2),
      domErrorVisible = _React$useState2[0],
      innerSetDomErrorVisible = _React$useState2[1];

  var prevValidateStatusRef = React.useRef(validateStatus);

  var _useFrameState = (0, _util.useFrameState)({}),
      _useFrameState2 = (0, _slicedToArray2["default"])(_useFrameState, 2),
      inlineErrors = _useFrameState2[0],
      setInlineErrors = _useFrameState2[1];

  function setDomErrorVisible(visible) {
    if (!destroyRef.current) {
      innerSetDomErrorVisible(visible);
    }
  }

  var formName = formContext.name;
  var hasName = hasValidName(name); // Cache Field NamePath

  var nameRef = React.useRef([]); // Should clean up if Field removed

  React.useEffect(function () {
    return function () {
      destroyRef.current = true;
      updateItemErrors(nameRef.current.join('__SPLIT__'), []);
    };
  }, []);
  var prefixCls = getPrefixCls('form', customizePrefixCls); // ======================== Errors ========================
  // Collect noStyle Field error to the top FormItem

  var updateChildItemErrors = noStyle ? updateItemErrors : function (subName, subErrors) {
    if (!(0, _isEqual["default"])(inlineErrors[subName], subErrors)) {
      setInlineErrors(function (prevInlineErrors) {
        return (0, _extends3["default"])((0, _extends3["default"])({}, prevInlineErrors), (0, _defineProperty2["default"])({}, subName, subErrors));
      });
    }
  };

  function renderLayout(baseChildren, fieldId, meta, isRequired) {
    var _itemClassName;

    if (noStyle) {
      return baseChildren;
    } // ======================== Errors ========================


    var mergedErrors;

    if (help !== undefined && help !== null) {
      mergedErrors = (0, _util.toArray)(help);
    } else {
      mergedErrors = meta ? meta.errors : [];
      Object.keys(inlineErrors).forEach(function (subName) {
        var subErrors = inlineErrors[subName] || [];

        if (subErrors.length) {
          mergedErrors = [].concat((0, _toConsumableArray2["default"])(mergedErrors), (0, _toConsumableArray2["default"])(subErrors));
        }
      });
    } // ======================== Status ========================


    var mergedValidateStatus = '';

    if (validateStatus !== undefined) {
      mergedValidateStatus = validateStatus;
    } else if (meta && meta.validating) {
      mergedValidateStatus = 'validating';
    } else if (!help && mergedErrors.length) {
      mergedValidateStatus = 'error';
    } else if (meta && meta.touched) {
      mergedValidateStatus = 'success';
    }

    if (domErrorVisible && help) {
      prevValidateStatusRef.current = mergedValidateStatus;
    }

    var itemClassName = (_itemClassName = {}, (0, _defineProperty2["default"])(_itemClassName, "".concat(prefixCls, "-item"), true), (0, _defineProperty2["default"])(_itemClassName, "".concat(prefixCls, "-item-with-help"), domErrorVisible || help), (0, _defineProperty2["default"])(_itemClassName, "".concat(className), !!className), (0, _defineProperty2["default"])(_itemClassName, "".concat(prefixCls, "-item-has-feedback"), mergedValidateStatus && hasFeedback), (0, _defineProperty2["default"])(_itemClassName, "".concat(prefixCls, "-item-has-success"), mergedValidateStatus === 'success'), (0, _defineProperty2["default"])(_itemClassName, "".concat(prefixCls, "-item-has-warning"), mergedValidateStatus === 'warning'), (0, _defineProperty2["default"])(_itemClassName, "".concat(prefixCls, "-item-has-error"), mergedValidateStatus === 'error'), (0, _defineProperty2["default"])(_itemClassName, "".concat(prefixCls, "-item-has-error-leave"), !help && domErrorVisible && prevValidateStatusRef.current === 'error'), (0, _defineProperty2["default"])(_itemClassName, "".concat(prefixCls, "-item-is-validating"), mergedValidateStatus === 'validating'), _itemClassName); // ======================= Children =======================

    return /*#__PURE__*/React.createElement(_row["default"], (0, _extends3["default"])({
      className: (0, _classnames["default"])(itemClassName),
      style: style,
      key: "row"
    }, (0, _omit["default"])(restProps, ['extra', 'getValueFromEvent', 'getValueProps', 'hasFeedback', 'help', 'htmlFor', 'id', 'initialValue', 'label', 'labelAlign', 'labelCol', 'normalize', 'required', 'validateFirst', 'validateStatus', 'valuePropName', 'wrapperCol'])), /*#__PURE__*/React.createElement(_FormItemLabel["default"], (0, _extends3["default"])({
      htmlFor: fieldId,
      required: isRequired
    }, props, {
      prefixCls: prefixCls
    })), /*#__PURE__*/React.createElement(_FormItemInput["default"], (0, _extends3["default"])({}, props, meta, {
      errors: mergedErrors,
      prefixCls: prefixCls,
      onDomErrorVisibleChange: setDomErrorVisible,
      validateStatus: mergedValidateStatus
    }), /*#__PURE__*/React.createElement(_context.FormItemContext.Provider, {
      value: {
        updateItemErrors: updateChildItemErrors
      }
    }, baseChildren)));
  }

  var isRenderProps = typeof children === 'function'; // Record for real component render

  var updateRef = React.useRef(0);
  updateRef.current += 1;

  if (!hasName && !isRenderProps && !dependencies) {
    return renderLayout(children);
  }

  var variables = {};

  if (typeof label === 'string') {
    variables.label = label;
  }

  return /*#__PURE__*/React.createElement(_rcFieldForm.Field, (0, _extends3["default"])({}, props, {
    messageVariables: variables,
    trigger: trigger,
    validateTrigger: validateTrigger,
    onReset: function onReset() {
      setDomErrorVisible(false);
    }
  }), function (control, meta, context) {
    var errors = meta.errors;
    var mergedName = (0, _util.toArray)(name).length && meta ? meta.name : [];
    var fieldId = (0, _util.getFieldId)(mergedName, formName);

    if (noStyle) {
      nameRef.current = (0, _toConsumableArray2["default"])(mergedName);

      if (fieldKey) {
        nameRef.current[nameRef.current.length - 1] = fieldKey;
      }

      updateItemErrors(nameRef.current.join('__SPLIT__'), errors);
    }

    var isRequired = required !== undefined ? required : !!(rules && rules.some(function (rule) {
      if (rule && (0, _typeof2["default"])(rule) === 'object' && rule.required) {
        return true;
      }

      if (typeof rule === 'function') {
        var ruleEntity = rule(context);
        return ruleEntity && ruleEntity.required;
      }

      return false;
    })); // ======================= Children =======================

    var mergedControl = (0, _extends3["default"])((0, _extends3["default"])({}, control), {
      id: fieldId
    });
    var childNode = null;

    if (Array.isArray(children) && hasName) {
      (0, _warning["default"])(false, 'Form.Item', '`children` is array of render props cannot have `name`.');
      childNode = children;
    } else if (isRenderProps && (!shouldUpdate || hasName)) {
      (0, _warning["default"])(!!shouldUpdate, 'Form.Item', '`children` of render props only work with `shouldUpdate`.');
      (0, _warning["default"])(!hasName, 'Form.Item', "Do not use `name` with `children` of render props since it's not a field.");
    } else if (dependencies && !isRenderProps && !hasName) {
      (0, _warning["default"])(false, 'Form.Item', 'Must set `name` or use render props when `dependencies` is set.');
    } else if ( /*#__PURE__*/React.isValidElement(children)) {
      (0, _warning["default"])(children.props.defaultValue === undefined, 'Form.Item', '`defaultValue` will not work on controlled Field. You should use `initialValues` of Form instead.');
      var childProps = (0, _extends3["default"])((0, _extends3["default"])({}, children.props), mergedControl); // We should keep user origin event handler

      var triggers = new Set([].concat((0, _toConsumableArray2["default"])((0, _util.toArray)(trigger)), (0, _toConsumableArray2["default"])((0, _util.toArray)(validateTrigger))));
      triggers.forEach(function (eventName) {
        childProps[eventName] = function () {
          var _a2, _c2;

          var _a, _b, _c;

          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }

          (_a = mergedControl[eventName]) === null || _a === void 0 ? void 0 : (_a2 = _a).call.apply(_a2, [mergedControl].concat(args));
          (_c = (_b = children.props)[eventName]) === null || _c === void 0 ? void 0 : (_c2 = _c).call.apply(_c2, [_b].concat(args));
        };
      });
      childNode = /*#__PURE__*/React.createElement(MemoInput, {
        value: mergedControl[props.valuePropName || 'value'],
        update: updateRef.current
      }, /*#__PURE__*/React.cloneElement(children, childProps));
    } else if (isRenderProps && shouldUpdate && !hasName) {
      childNode = children(context);
    } else {
      (0, _warning["default"])(!mergedName.length, 'Form.Item', '`name` is only used for validate React element. If you are using Form.Item as layout display, please remove `name` instead.');
      childNode = children;
    }

    return renderLayout(childNode, fieldId, meta, isRequired);
  });
}

var _default = FormItem;
exports["default"] = _default;