"use strict";

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

function _tslib() {
  const data = require("tslib");

  _tslib = function () {
    return data;
  };

  return data;
}

function _jsxRuntime() {
  const data = require("react/jsx-runtime");

  _jsxRuntime = function () {
    return data;
  };

  return data;
}

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function () {
    return data;
  };

  return data;
}

function _clsx() {
  const data = _interopRequireDefault(require("clsx"));

  _clsx = function () {
    return data;
  };

  return data;
}

function _rcFieldForm() {
  const data = require("rc-field-form");

  _rcFieldForm = function () {
    return data;
  };

  return data;
}

var _field = _interopRequireDefault(require("../field"));

var _utils = require("../uploader/utils");

var _Field = require("../field/Field");

var _constant = require("../utils/constant");

var _FormContext = require("./FormContext");

var _ConfigProviderContext = _interopRequireDefault(require("../config-provider/ConfigProviderContext"));

var _devLog = require("../utils/dev-log");

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

/* eslint-disable no-console */
const MemoInput = _react().default.memo(_a => {
  var {
    children
  } = _a,
      props = (0, _tslib().__rest)(_a, ["children"]);
  return _react().default.cloneElement(children, props);
}, (prev, next) => prev.value === next.value && prev.update === next.update);

const FormItemLayout = props => {
  const {
    className,
    meta,
    children,
    isFieldChildren,
    showValidateMessage,
    colon,
    layout,
    labelAlign,
    inputAlign,
    border
  } = props,
        fieldProps = (0, _tslib().__rest)(props, ["className", "meta", "children", "isFieldChildren", "showValidateMessage", "colon", "layout", "labelAlign", "inputAlign", "border"]);

  const {
    prefixCls,
    createNamespace
  } = _react().default.useContext(_ConfigProviderContext.default);

  const [bem] = createNamespace('form', prefixCls);

  const context = _react().default.useContext(_FormContext.FormContext);

  const itemLayout = layout !== null && layout !== void 0 ? layout : context.layout;
  const itemBorder = border !== null && border !== void 0 ? border : context.border;
  const itemColon = colon !== null && colon !== void 0 ? colon : context.colon;
  const itemShowValidateMessage = showValidateMessage !== null && showValidateMessage !== void 0 ? showValidateMessage : context.showValidateMessage;
  const itemLabelAlign = labelAlign !== null && labelAlign !== void 0 ? labelAlign : context.labelAlign;
  const itemInputAlign = inputAlign !== null && inputAlign !== void 0 ? inputAlign : context.inputAlign;
  const error = meta && meta.errors.length > 0;
  const errorMessage = itemShowValidateMessage && error ? meta.errors[0] : null;
  const attrs = Object.assign(Object.assign({}, fieldProps), {
    className: (0, _clsx().default)(bem({
      vertical: itemLayout === 'vertical'
    }), className),
    colon: itemColon,
    error,
    errorMessage,
    labelAlign: itemLabelAlign,
    inputAlign: itemInputAlign,
    border: itemBorder
  });
  if (isFieldChildren) return _react().default.cloneElement(children, attrs);
  return (0, _jsxRuntime().jsx)(_field.default, Object.assign({}, attrs, {
    children: children
  }));
};

const FormItem = props => {
  var _a;

  const {
    className,
    style,
    label,
    name,
    required,
    noStyle,
    tooltip,
    intro,
    customField,
    disabled,
    colon,
    rules,
    children,
    messageVariables,
    trigger = 'onChange',
    validateTrigger,
    onClick,
    shouldUpdate,
    dependencies,
    labelWidth,
    labelAlign,
    labelClass,
    showValidateMessage,
    inputAlign,
    errorMessageAlign,
    border,
    layout
  } = props,
        fieldProps = (0, _tslib().__rest)(props, ["className", "style", "label", "name", "required", "noStyle", "tooltip", "intro", "customField", "disabled", "colon", "rules", "children", "messageVariables", "trigger", "validateTrigger", "onClick", "shouldUpdate", "dependencies", "labelWidth", "labelAlign", "labelClass", "showValidateMessage", "inputAlign", "errorMessageAlign", "border", "layout"]);

  const {
    validateTrigger: contextValidateTrigger
  } = _react().default.useContext(_rcFieldForm().FieldContext);

  const mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : contextValidateTrigger;

  const updateRef = _react().default.useRef(0);

  updateRef.current += 1;
  const isFieldChildren = ((_a = children.type) === null || _a === void 0 ? void 0 : _a[_constant.COMPONENT_TYPE_KEY]) === _Field.FIELD_KEY || customField;

  function renderLayout(baseChildren, fieldId, meta, isRequired) {
    if (noStyle) {
      return baseChildren;
    }

    return (0, _jsxRuntime().jsx)(FormItemLayout, Object.assign({
      isFieldChildren: isFieldChildren,
      className: className,
      style: style,
      label: label,
      tooltip: tooltip,
      intro: intro,
      required: isRequired,
      disabled: disabled,
      htmlFor: fieldId,
      meta: meta,
      colon: colon,
      border: border,
      layout: layout,
      labelWidth: labelWidth,
      labelAlign: labelAlign,
      labelClass: labelClass,
      inputAlign: inputAlign,
      errorMessageAlign: errorMessageAlign,
      showValidateMessage: showValidateMessage,
      onClick: onClick
    }, {
      children: baseChildren
    }));
  }

  const isRenderProps = typeof children === 'function';

  if (!name && !isRenderProps && !props.dependencies) {
    return renderLayout(children);
  }

  let variables = {};

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

  if (messageVariables) {
    variables = Object.assign(Object.assign({}, variables), messageVariables);
  }

  return (0, _jsxRuntime().jsx)(_rcFieldForm().Field, Object.assign({}, fieldProps, {
    name: name,
    shouldUpdate: shouldUpdate,
    dependencies: dependencies,
    rules: rules,
    trigger: trigger,
    validateTrigger: mergedValidateTrigger
  }, {
    children: (control, meta, context) => {
      var _a;

      let childNode = null;
      const isRequired = required !== undefined ? required : !!(rules && rules.some(rule => {
        if (rule && typeof rule === 'object' && rule.required) {
          return true;
        }

        return false;
      }));
      const fieldId = ((0, _utils.toArray)(name).length && meta ? meta.name : []).join('_');

      if (shouldUpdate && dependencies) {
        (0, _devLog.devWarning)('Form.Item', "`shouldUpdate` and `dependencies` shouldn't be used together.");
      }

      if (isRenderProps) {
        if ((shouldUpdate || dependencies) && !name) {
          childNode = children(context);
        } else {
          if (!(shouldUpdate || dependencies)) {
            (0, _devLog.devWarning)('Form.Item', '`children` of render props only work with `shouldUpdate` or `dependencies`.');
          }

          if (name) {
            (0, _devLog.devWarning)('Form.Item', "Do not use `name` with `children` of render props since it's not a field.");
          }
        } // not render props

      } else if (dependencies && !name) {
        (0, _devLog.devWarning)('Form.Item', 'Must set `name` or use render props when `dependencies` is set.');
      } else if (_react().default.isValidElement(children)) {
        const childProps = Object.assign(Object.assign({}, children.props), control);

        if (!childProps.id) {
          childProps.id = fieldId;
        }

        if (disabled) {
          childProps.disabled = disabled;
        } // We should keep user origin event handler


        const triggers = new Set([...(0, _utils.toArray)(trigger), ...(0, _utils.toArray)(mergedValidateTrigger)]);
        triggers.forEach(eventName => {
          childProps[eventName] = (...args) => {
            var _a, _b, _c;

            (_a = control[eventName]) === null || _a === void 0 ? void 0 : _a.call(control, ...args);
            (_c = (_b = children.props)[eventName]) === null || _c === void 0 ? void 0 : _c.call(_b, ...args);
          };
        });
        childNode = (0, _jsxRuntime().jsx)(MemoInput, Object.assign({
          value: control[props.valuePropName || 'value'],
          update: updateRef.current
        }, {
          children: _react().default.cloneElement(children, childProps)
        }));

        if (isFieldChildren) {
          childProps.value = (_a = childProps.value) !== null && _a !== void 0 ? _a : '';
          childNode = _react().default.cloneElement(children, childProps);
        }
      } else {
        if (name) {
          (0, _devLog.devWarning)('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;