"use strict";

exports.__esModule = true;
exports.default = exports.FormItemContext = void 0;

var _babelRuntimeJsxStyleTransform = require("babel-runtime-jsx-style-transform");

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

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

var _meetReactComponentOne = require("@alifd/meet-react-component-one");

var _icon = _interopRequireDefault(require("../icon"));

var _index = _interopRequireDefault(require("../list/index"));

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

var _hooks = require("../utils/hooks");

var _view = _interopRequireDefault(require("../view"));

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

var _utils2 = require("./utils");

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; }

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

var FormItemContext = /*#__PURE__*/(0, _react.createContext)({
  isInsideForm: false,
  labelAlign: 'top',
  validateState: 'normal',
  labelTextAlign: 'left',
  contentAlign: 'left',
  hasFeedback: true,
  size: 'medium'
});
exports.FormItemContext = FormItemContext;

var FormItem = function (props) {
  var _classNames, _classNames2, _classNames3, _classNames4, _classNames5;

  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      label = props.label,
      labelWidthProp = props.labelWidth,
      labelAlignProp = props.labelAlign,
      labelTextAlignProp = props.labelTextAlign,
      contentAlignProp = props.contentAlign,
      helpProp = props.help,
      extra = props.extra,
      className = props.className,
      style = props.style,
      children = props.children,
      isPreviewProp = props.isPreview,
      renderPreview = props.renderPreview,
      validateStateProp = props.validateState,
      _props$hasFeedback = props.hasFeedback,
      hasFeedback = _props$hasFeedback === void 0 ? false : _props$hasFeedback,
      _props$embedded = props.embedded,
      embedded = _props$embedded === void 0 ? false : _props$embedded,
      previewClassNameProp = props.previewClassName,
      _props$previewStyle = props.previewStyle,
      previewStyle = _props$previewStyle === void 0 ? {} : _props$previewStyle,
      sizeProp = props.size,
      valuePropName = props.valuePropName,
      required = props.required,
      requiredMessage = props.requiredMessage,
      requiredTrigger = props.requiredTrigger,
      min = props.min,
      max = props.max,
      minmaxMessage = props.minmaxMessage,
      minmaxTrigger = props.minmaxTrigger,
      minLength = props.minLength,
      maxLength = props.maxLength,
      minmaxLengthMessage = props.minmaxLengthMessage,
      minmaxLengthTrigger = props.minmaxLengthTrigger,
      length = props.length,
      lengthMessage = props.lengthMessage,
      lengthTrigger = props.lengthTrigger,
      pattern = props.pattern,
      patternMessage = props.patternMessage,
      patternTrigger = props.patternTrigger,
      format = props.format,
      formatMessage = props.formatMessage,
      formatTrigger = props.formatTrigger,
      validator = props.validator,
      validatorTrigger = props.validatorTrigger;

  var _useContext = (0, _react.useContext)(_context.default),
      contextLabelAlign = _useContext.labelAlign,
      contextLabelWidth = _useContext.labelWidth,
      contextLabelTextAlign = _useContext.labelTextAlign,
      useLabelForErrorMessage = _useContext.useLabelForErrorMessage,
      contextContentAlign = _useContext.contentAlign,
      form = _useContext.form,
      field = _useContext.field,
      sizeContext = _useContext.size,
      contextIsPreview = _useContext.isPreview;

  var itemId = (0, _hooks.useGuid)('form-item-');
  var size = sizeProp || sizeContext;
  var valueNames = [];
  var validateName;

  if (label && useLabelForErrorMessage) {
    validateName = (0, _utils.isString)(label) ? label : label.toString();
  } else {
    validateName = valueNames.join(' ');
  }

  var _useState = (0, _react.useState)(validateStateProp || 'normal'),
      validateStateInner = _useState[0],
      setValidateState = _useState[1];

  var validateState = 'validateState' in props ? validateStateProp || 'normal' : validateStateInner;

  var _useState2 = (0, _react.useState)(''),
      error = _useState2[0],
      setError = _useState2[1];

  var rules = (0, _react.useMemo)(function () {
    return (0, _utils2.getValidationRules)(validateName, props);
  }, [required, requiredMessage, requiredTrigger, min, max, minmaxMessage, minmaxTrigger, minLength, maxLength, minmaxLengthMessage, minmaxLengthTrigger, length, lengthMessage, lengthTrigger, pattern, patternMessage, patternTrigger, format, formatMessage, formatTrigger, validator, validatorTrigger]);
  var clsPrefix = prefix + "form-item";
  var previewClassName = (0, _classnames.default)(previewClassNameProp, clsPrefix + "-input", clsPrefix + "-input--preview-" + size);
  var isPreview = !(0, _utils.isUndef)(isPreviewProp) ? isPreviewProp : contextIsPreview;
  var labelAlign = labelAlignProp || contextLabelAlign;

  if (labelAlign === 'left') {
    labelAlign = 'inset';
  }

  var contentAlign = contentAlignProp || contextContentAlign || 'left';
  var labelTextAlign = labelTextAlignProp || contextLabelTextAlign || 'left';
  var help = helpProp;

  if (!help && validateState === 'error') {
    help = error;
  }

  var hasError = validateState === 'error';
  var hasHelp = !!help;
  var isInset = labelAlign === 'inset';
  (0, _react.useEffect)(function () {
    if (validateStateProp && validateStateProp !== validateState) {
      setValidateState(validateStateProp);
    }
  }, [validateState, validateStateProp]);

  var getValidateResult = function () {
    if (rules.length === 0) {
      if (validateState !== 'normal') {
        setValidateState('normal');
      }

      return;
    }

    if (!('validateState' in props) && field) {
      var errors = [];
      Object.values(field.getErrors(valueNames)).forEach(function (err) {
        if (err && Array.isArray(err) && err.length > 0) {
          err.forEach(function (it) {
            return errors.push(it);
          });
        }
      });

      if (errors.length > 0) {
        if (validateState !== 'error') {
          setValidateState('error');
        }

        if (errors[0] !== error) {
          setError(errors[0]);
        }
      } else if (validateState !== 'success' && validateState !== 'normal') {
        setValidateState('success');
      }
    }
  };

  (0, _react.useEffect)(function () {
    if (form) {
      return form.onValidate(getValidateResult);
    }
  }, []);
  (0, _react.useEffect)(function () {
    return getValidateResult();
  });

  var fn = function (child, index) {
    if (!field) {
      return child;
    }

    var valueName = valuePropName;

    if (!valueName) {
      if (child.type && child.type.valueName) {
        valueName = child.type.valueName;
      } else if ('checked' in child.props || 'defaultChecked' in child.props) {
        valueName = 'checked';
      } else {
        valueName = 'value';
      }
    }

    if ('name' in child.props) {
      var name = child.props.name;
      valueNames.push(name);

      if (form && form.mapNameToGuid) {
        form.mapNameToGuid[name] = itemId;
      }

      if (!('data-meta' in child.props)) {
        var init = field.init;
        return (0, _react.cloneElement)(child, Object.assign(Object.assign(Object.assign({}, child.props), init(name, {
          valueName: valueName,
          rules: rules,
          props: Object.assign(Object.assign({}, child.props), {
            ref: child.ref
          })
        }, child.props)), {
          labelAlign: labelAlign,
          size: size,
          key: child.key || name || index
        }));
      }
    } else if (child.props.children) {
      return _react.Children.map(child.props.children, fn);
    }

    return child;
  };

  var newChildren = _react.Children.map(children, fn);

  var previewElement = null;

  if (isPreview && field && renderPreview !== false) {
    var values = Object.values(field.getValues(valueNames));
    previewElement = /*#__PURE__*/(0, _react.createElement)(_view.default, {
      className: previewClassName,
      style: (0, _babelRuntimeJsxStyleTransform.rpx2vw4style)(Object.assign(Object.assign({}, previewStyle), {
        textAlign: contentAlign
      }))
    }, renderPreview ? renderPreview.apply(void 0, values) : values.join(','));
  }

  return /*#__PURE__*/(0, _react.createElement)(_index.default.Item, {
    id: itemId,
    className: (0, _classnames.default)(clsPrefix, (_classNames = {}, _classNames[clsPrefix + "--inset"] = isInset, _classNames[clsPrefix + "--error"] = hasError, _classNames[clsPrefix + "--help"] = hasHelp, _classNames), className),
    style: (0, _babelRuntimeJsxStyleTransform.rpx2vw4style)(style)
  }, /*#__PURE__*/(0, _react.createElement)(_index.default.ItemContent, null, /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: (0, _classnames.default)(clsPrefix + "-container", (_classNames2 = {}, _classNames2[clsPrefix + "-container--inset"] = isInset, _classNames2))
  }, !embedded && label ? /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: (0, _classnames.default)(clsPrefix + "-label-container", (_classNames3 = {}, _classNames3[clsPrefix + "-label-container--" + size] = !isInset, _classNames3[clsPrefix + "-label-container--inset"] = isInset, _classNames3[clsPrefix + "-label-container--right"] = isInset && labelTextAlign === 'right', _classNames3)),
    style: (0, _babelRuntimeJsxStyleTransform.rpx2vw4style)({
      width: labelWidthProp || contextLabelWidth || 'auto',
      flexShrink: 0
    })
  }, isInset && required && !isPreview ? /*#__PURE__*/(0, _react.createElement)(_icon.default, {
    name: "asterisk",
    className: (0, _classnames.default)(clsPrefix + "-required", clsPrefix + "-required--inset-" + size, (_classNames4 = {}, _classNames4[clsPrefix + "-required--inset"] = labelTextAlign !== 'right', _classNames4))
  }) : null, (0, _utils.isString)(label) ? /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Text, {
    className: (0, _classnames.default)(clsPrefix + "-label", clsPrefix + "-label--" + size, (_classNames5 = {}, _classNames5[clsPrefix + "-label--inset"] = isInset, _classNames5[clsPrefix + "-label--inset--" + size] = isInset, _classNames5[clsPrefix + "-label--error"] = hasError, _classNames5))
  }, label) : label, !isInset && required && !isPreview ? /*#__PURE__*/(0, _react.createElement)(_icon.default, {
    name: "asterisk",
    className: clsPrefix + "-required " + clsPrefix + "-required--" + size
  }) : null) : null, /*#__PURE__*/(0, _react.createElement)(FormItemContext.Provider, {
    value: {
      isInsideForm: true,
      labelAlign: labelAlign,
      labelTextAlign: labelTextAlign,
      validateState: validateState,
      hasFeedback: hasFeedback,
      contentAlign: contentAlign,
      size: size
    }
  }, previewElement, /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: (0, _classnames.default)(clsPrefix + "-input", clsPrefix + "-input--" + contentAlign),
    style: (0, _babelRuntimeJsxStyleTransform.rpx2vw4style)({
      display: previewElement ? 'none' : 'flex'
    })
  }, newChildren))), /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: (0, _classnames.default)(clsPrefix + "-help", clsPrefix + "-help--" + contentAlign, clsPrefix + "-help--" + (hasError ? 'error' : 'help'))
  }, help ? /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: (0, _classnames.default)(clsPrefix + "-help-text", clsPrefix + "-help-text--" + size)
  }, help) : null, extra && /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: (0, _classnames.default)(clsPrefix + "-help-extra", clsPrefix + "-help-text--" + size)
  }, extra))));
};

var _default = /*#__PURE__*/(0, _react.forwardRef)(FormItem);

exports.default = _default;