var _excluded = ["name", "fieldKey", "noStyle", "dependencies", "prefixCls", "style", "className", "shouldUpdate", "hasFeedback", "help", "rules", "validateStatus", "children", "required", "label", "messageVariables", "trigger", "validateTrigger", "hidden", "dependency"];
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
// @ts-nocheck
import * as React from 'react';
import { useContext, useRef } from 'react';
import isEqual from 'lodash/isEqual';
import classNames from 'classnames';
import { Field } from 'rc-field-form';
import FieldContext from "rc-field-form/es/FieldContext";
import { supportRef } from "rc-util/es/ref";
import omit from './omit';
import Row from "antd/es/row";
import { ConfigContext } from "antd/es/config-provider/context";
import { tuple } from './type';
import devWarning from './devWarning';
import FormItemLabel from './FormItemLabel';
import FormItemInput from './FormItemInput';
import { FormContext, FormItemContext } from './context';
import { toArray, getFieldId } from './util';
import { cloneElement, isValidElement } from './reactNode';
import useFrameState from '../hooks/useFrameState';
import useItemRef from '../hooks/useItemRef';
var ValidateStatuses = 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) {
    devWarning(false, 'Form.Item', '`null` is passed as `name` property');
  }
  return !(name === undefined || name === null);
}
function getInitItem(dependency, name) {
  var item = {
    name: name
  };
  if (dependency) {
    if (dependency.disabled) {
      item.type = 'disabled';
    }
    if (dependency.source) {
      item.type = 'source';
    }
  }
}
function FormItem(props) {
  var _children$props3;
  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,
    messageVariables = props.messageVariables,
    _props$trigger = props.trigger,
    trigger = _props$trigger === void 0 ? 'onChange' : _props$trigger,
    validateTrigger = props.validateTrigger,
    hidden = props.hidden,
    dependency = props.dependency,
    restProps = _objectWithoutProperties(props, _excluded);
  var destroyRef = useRef(false);
  // @ts-ignore
  var _useContext = useContext(ConfigContext),
    getPrefixCls = _useContext.getPrefixCls;
  var _useContext2 = useContext(FormContext),
    formName = _useContext2.name,
    requiredMark = _useContext2.requiredMark,
    allDependency = _useContext2.allDependency,
    changeHandler = _useContext2.changeHandler,
    setFieldValue = _useContext2.setFieldValue,
    dataBinding = _useContext2.dataBinding;
  var _useContext3 = useContext(FormItemContext),
    updateItemErrors = _useContext3.updateItemErrors;
  var _React$useState = React.useState(!!help),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    domErrorVisible = _React$useState2[0],
    innerSetDomErrorVisible = _React$useState2[1];
  var _React$useState3 = React.useState(getInitItem(dependency, name)),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    updateItem = _React$useState4[0],
    innerSetUpdateItem = _React$useState4[1];
  var _React$useState5 = React.useState([]),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    itemRules = _React$useState6[0],
    innerSetItemRules = _React$useState6[1];
  var _React$useState7 = React.useState(dependency && dependency.visible ? dependency.visible.defaultOutput : !hidden),
    _React$useState8 = _slicedToArray(_React$useState7, 2),
    domVisible = _React$useState8[0],
    innerSetDomVisible = _React$useState8[1];
  var _React$useState9 = React.useState(dependency && dependency.disabled ? dependency.disabled.defaultOutput : false),
    _React$useState10 = _slicedToArray(_React$useState9, 2),
    domDisabled = _React$useState10[0],
    innerSetDomDisabled = _React$useState10[1];
  var _React$useState11 = React.useState(dependency && dependency.source && Array.isArray(dependency.source.defaultOutput) ? dependency.source.defaultOutput : []),
    _React$useState12 = _slicedToArray(_React$useState11, 2),
    dataSource = _React$useState12[0],
    innerSetDataSource = _React$useState12[1];
  var _useFrameState = useFrameState({}),
    _useFrameState2 = _slicedToArray(_useFrameState, 2),
    inlineErrors = _useFrameState2[0],
    setInlineErrors = _useFrameState2[1];
  var _useContext4 = useContext(FieldContext),
    contextValidateTrigger = _useContext4.validateTrigger;
  var mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : contextValidateTrigger;
  React.useEffect(function () {
    var originRules;
    if (dependency && dependency.required) {
      originRules = rules && rules.length > 0 ? rules.concat({
        required: dependency.required.defaultOutput
      }) : [{
        required: dependency.required.defaultOutput
      }];
    } else {
      originRules = rules || [];
    }
    innerSetItemRules(originRules);
  }, [rules]);
  function setDomErrorVisible(visible) {
    if (!destroyRef.current) {
      innerSetDomErrorVisible(visible);
    }
  }
  var hasName = hasValidName(name);
  // Cache Field NamePath
  var nameRef = useRef([]);
  changeHandler[name] = function (val, item, type) {
    if (type === 'source') {
      innerSetUpdateItem({
        name: item,
        type: type
      });
      innerSetDataSource(val);
    }
    if (type === 'disabled') {
      innerSetUpdateItem({
        name: item,
        type: type
      });
      innerSetDomDisabled(val);
    }
    if (type === 'visible') {
      innerSetDomVisible(val);
    }
    if (type === 'required') {
      var requireItem = {
        required: val
      };
      innerSetItemRules(rules && rules.length > 0 ? rules.concat(requireItem) : [requireItem]);
    }
  };
  if (name && dependency) {
    allDependency[name] = dependency;
  }
  // Should clean up if Field removed
  React.useEffect(function () {
    return function () {
      destroyRef.current = true;
      updateItemErrors(nameRef.current.join('__SPLIT__'), []);
    };
  }, []);
  React.useEffect(function () {
    var _children$props;
    if ((children === null || children === void 0 ? void 0 : (_children$props = children.props) === null || _children$props === void 0 ? void 0 : _children$props.value) && dataBinding) {
      var _children$props2;
      setFieldValue(_defineProperty({}, name, children === null || children === void 0 ? void 0 : (_children$props2 = children.props) === null || _children$props2 === void 0 ? void 0 : _children$props2.value));
    }
  }, [children === null || children === void 0 ? void 0 : (_children$props3 = children.props) === null || _children$props3 === void 0 ? void 0 : _children$props3.value]);
  var prefixCls = getPrefixCls('form', customizePrefixCls);
  // ======================== Errors ========================
  // Collect noStyle Field error to the top FormItem
  var updateChildItemErrors = noStyle ? updateItemErrors : function (subName, subErrors) {
    setInlineErrors(function () {
      var prevInlineErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      if (!isEqual(prevInlineErrors[subName], subErrors)) {
        return _objectSpread(_objectSpread({}, prevInlineErrors), {}, _defineProperty({}, subName, subErrors));
      }
      return prevInlineErrors;
    });
  };
  // ===================== Children Ref =====================
  var getItemRef = useItemRef();
  function renderLayout(baseChildren, fieldId, meta, isRequired) {
    var _meta$errors, _itemClassName;
    if (noStyle && domVisible) {
      return baseChildren;
    }
    // ======================== Errors ========================
    // >>> collect sub errors
    var subErrorList = [];
    Object.keys(inlineErrors).forEach(function (subName) {
      subErrorList = [].concat(_toConsumableArray(subErrorList), _toConsumableArray(inlineErrors[subName] || []));
    });
    // >>> merged errors
    var mergedErrors;
    if (help !== undefined && help !== null) {
      mergedErrors = toArray(help);
    } else {
      mergedErrors = meta ? meta.errors : [];
      mergedErrors = [].concat(_toConsumableArray(mergedErrors), _toConsumableArray(subErrorList));
    }
    // ======================== Status ========================
    var mergedValidateStatus = '';
    if (validateStatus !== undefined) {
      mergedValidateStatus = validateStatus;
    } else if (meta === null || meta === void 0 ? void 0 : meta.validating) {
      mergedValidateStatus = 'validating';
    } else if ((meta === null || meta === void 0 ? void 0 : (_meta$errors = meta.errors) === null || _meta$errors === void 0 ? void 0 : _meta$errors.length) || subErrorList.length) {
      mergedValidateStatus = 'error';
    } else if (meta === null || meta === void 0 ? void 0 : meta.touched) {
      mergedValidateStatus = 'success';
    }
    var itemClassName = (_itemClassName = {}, _defineProperty(_itemClassName, "".concat(prefixCls, "-item"), true), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-with-help"), domErrorVisible || help), _defineProperty(_itemClassName, "".concat(className), !!className), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-has-feedback"), mergedValidateStatus && hasFeedback), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-has-success"), mergedValidateStatus === 'success'), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-has-warning"), mergedValidateStatus === 'warning'), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-has-error"), mergedValidateStatus === 'error'), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-is-validating"), mergedValidateStatus === 'validating'), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-hidden"), !domVisible), _itemClassName);
    // ======================= Children =======================
    return /*#__PURE__*/React.createElement(Row, _extends({
      className: classNames(itemClassName),
      style: style,
      key: "row"
    }, omit(restProps, ['colon', 'extra', 'getValueFromEvent', 'getValueProps',
    // @ts-ignore
    'hasFeedback',
    // @ts-ignore
    'help', 'htmlFor', 'id', 'initialValue', 'isListField',
    // @ts-ignore
    'label', 'labelAlign', 'labelCol', 'normalize', 'preserve',
    // @ts-ignore
    'required', 'tooltip', 'validateFirst',
    // @ts-ignore
    'validateStatus', 'valuePropName', 'wrapperCol'])), /*#__PURE__*/React.createElement(FormItemLabel, _extends({
      htmlFor: fieldId,
      required: isRequired,
      requiredMark: requiredMark
    }, props, {
      prefixCls: prefixCls
    })), /*#__PURE__*/React.createElement(FormItemInput, _extends({}, props, meta, {
      errors: mergedErrors,
      prefixCls: prefixCls,
      status: mergedValidateStatus,
      onDomErrorVisibleChange: setDomErrorVisible,
      validateStatus: mergedValidateStatus
    }), /*#__PURE__*/React.createElement(FormItemContext.Provider, {
      value: {
        updateItemErrors: updateChildItemErrors
      }
    }, baseChildren)));
  }
  var isRenderProps = typeof children === 'function';
  // Record for real component render
  var updateRef = useRef(0);
  updateRef.current += 1;
  if (!hasName && !isRenderProps && !dependencies) {
    return renderLayout(children);
  }
  var variables = {};
  if (typeof label === 'string') {
    variables.label = label;
  }
  if (messageVariables) {
    variables = _objectSpread(_objectSpread({}, variables), messageVariables);
  }
  return /*#__PURE__*/React.createElement(Field, _extends({}, props, {
    rules: itemRules,
    messageVariables: variables,
    trigger: trigger,
    validateTrigger: mergedValidateTrigger,
    onReset: function onReset() {
      setDomErrorVisible(false);
    }
  }), function (control, meta, context) {
    var errors = meta.errors;
    var mergedName = toArray(name).length && meta ? meta.name : [];
    var fieldId = getFieldId(mergedName, formName);
    if (noStyle) {
      nameRef.current = _toConsumableArray(mergedName);
      if (fieldKey) {
        var fieldKeys = Array.isArray(fieldKey) ? fieldKey : [fieldKey];
        nameRef.current = [].concat(_toConsumableArray(mergedName.slice(0, -1)), _toConsumableArray(fieldKeys));
      }
      updateItemErrors(nameRef.current.join('__SPLIT__'), errors);
    }
    var isRequired = required !== undefined ? required : !!(itemRules && itemRules.some(function (rule) {
      if (rule && _typeof(rule) === 'object' && rule.required) {
        return true;
      }
      if (typeof rule === 'function') {
        var ruleEntity = rule(context);
        return ruleEntity && ruleEntity.required;
      }
      return false;
    }));
    // ======================= Children =======================
    var mergedControl = _objectSpread({}, control);
    if (dataBinding) {
      delete mergedControl[props.valuePropName || 'value'];
    }
    var childNode = null;
    devWarning(!(shouldUpdate && dependencies), 'Form.Item', "`shouldUpdate` and `dependencies` shouldn't be used together. See https://ant.design/components/form/#dependencies.");
    if (Array.isArray(children) && hasName) {
      devWarning(false, 'Form.Item', '`children` is array of render props cannot have `name`.');
      childNode = children;
    } else if (isRenderProps && (!(shouldUpdate || dependencies) || hasName)) {
      devWarning(!!(shouldUpdate || dependencies), 'Form.Item', '`children` of render props only work with `shouldUpdate` or `dependencies`.');
      devWarning(!hasName, 'Form.Item', "Do not use `name` with `children` of render props since it's not a field.");
    } else if (dependencies && !isRenderProps && !hasName) {
      devWarning(false, 'Form.Item', 'Must set `name` or use render props when `dependencies` is set.');
    } else if (isValidElement(children)) {
      devWarning(children.props.defaultValue === undefined, 'Form.Item', '`defaultValue` will not work on controlled Field. You should use `initialValues` of Form instead.');
      var childProps = _objectSpread(_objectSpread({}, children.props), mergedControl);
      if (!childProps.id) {
        childProps.id = fieldId;
      }
      if (supportRef(children)) {
        childProps.ref = getItemRef(mergedName, children);
      }
      if (updateItem && updateItem.name === name) {
        if (updateItem.type === 'disabled') {
          childProps.disabled = domDisabled;
        }
        if (updateItem.type === 'source') {
          if (childProps.dataSource) {
            childProps.dataSource = dataSource;
          } else {
            childProps.options = dataSource;
          }
        }
      }
      // We should keep user origin event handler
      var triggers = new Set([].concat(_toConsumableArray(toArray(trigger)), _toConsumableArray(toArray(mergedValidateTrigger))));
      triggers.forEach(function (eventName) {
        childProps[eventName] = function () {
          var _mergedControl$eventN, _children$props$event, _children$props4;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          (_mergedControl$eventN = mergedControl[eventName]) === null || _mergedControl$eventN === void 0 ? void 0 : _mergedControl$eventN.call.apply(_mergedControl$eventN, [mergedControl].concat(args));
          (_children$props$event = (_children$props4 = children.props)[eventName]) === null || _children$props$event === void 0 ? void 0 : _children$props$event.call.apply(_children$props$event, [_children$props4].concat(args));
        };
      });
      childNode = /*#__PURE__*/React.createElement(MemoInput, {
        value: dataBinding ? childProps[props.valuePropName || 'value'] : mergedControl[props.valuePropName || 'value'],
        update: updateRef.current
      }, cloneElement(children, childProps));
    } else if (isRenderProps && (shouldUpdate || dependencies) && !hasName) {
      childNode = children(context);
    } else {
      devWarning(!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);
  });
}
export default FormItem;