"use strict";

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

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

var _icons = require("@react-vant/icons");

var _clsx = _interopRequireDefault(require("clsx"));

var _cell = _interopRequireDefault(require("../cell"));

var _dialog = _interopRequireDefault(require("../dialog"));

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

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

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

var _Object$assign;

var _excluded = ["icon"];

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

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 _extends() { _extends = Object.assign || 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 _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; }

var ICON_SIZE = '16px';
var Field = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _bem;

  var _useContext = (0, _react.useContext)(_ConfigProviderContext.default),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('field', prefixCls),
      bem = _createNamespace[0];

  var _useState = (0, _react.useState)(false),
      inputFocus = _useState[0],
      setInputFocus = _useState[1];

  var fieldRef = (0, _react.useRef)(null);
  var inputRef = (0, _react.useRef)(null);
  (0, _react.useEffect)(function () {
    if (props.getFieldRef) props.getFieldRef(fieldRef);
    if (props.getInputRef) props.getInputRef(inputRef);
  }, [props.getFieldRef, props.getInputRef]);

  var focus = function focus() {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  var blur = function blur() {
    if (inputRef.current) {
      inputRef.current.blur();
    }
  };

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      focus: focus,
      blur: blur
    };
  });

  var getProp = function getProp(key) {
    if ((0, _utils.isDef)(props[key])) {
      return props[key];
    }

    return null;
  };

  var getModelValue = function getModelValue() {
    var _props$value;

    return String((_props$value = props.value) != null ? _props$value : '');
  };

  var showClear = (0, _react.useMemo)(function () {
    var readonly = getProp('readonly');

    if (props.clearable && !readonly) {
      var hasValue = getModelValue() !== '';
      var trigger = props.clearTrigger === 'always' || props.clearTrigger === 'focus' && inputFocus;
      return hasValue && trigger;
    }

    return false;
  }, [props.value, props.clearTrigger, inputFocus]);

  var labelStyle = function labelStyle() {
    var labelW = getProp('labelWidth');

    if (labelW) {
      return {
        width: (0, _utils.addUnit)(labelW)
      };
    }

    return {};
  };

  var adjustSize = function adjustSize() {
    var input = inputRef.current;

    if (!(props.type === 'textarea' && props.autosize) || !input) {
      return;
    }

    input.style.height = 'auto';
    var height = input.scrollHeight;

    if ((0, _utils.isObject)(props.autosize)) {
      var _props$autosize = props.autosize,
          maxHeight = _props$autosize.maxHeight,
          minHeight = _props$autosize.minHeight;

      if (maxHeight) {
        height = Math.min(height, maxHeight);
      }

      if (minHeight) {
        height = Math.max(height, minHeight);
      }
    }

    if (height) {
      input.style.height = height + "px";
    }
  };

  (0, _react.useEffect)(function () {
    adjustSize();
  }, [props.value]);

  var formatValue = function formatValue(inputValue, trigger) {
    if (trigger === void 0) {
      trigger = 'onChange';
    }

    var formatTrigger = props.formatTrigger,
        formatter = props.formatter;

    if (formatter && trigger === formatTrigger) {
      return formatter(inputValue);
    }

    return inputValue;
  };

  var renderInput = function renderInput() {
    var type = props.type,
        error = props.error,
        name = props.name,
        rows = props.rows,
        value = props.value,
        placeholder = props.placeholder,
        disabled = props.disabled,
        readonly = props.readonly;
    var controlClass = bem('control', [getProp('inputAlign'), {
      error: error,
      custom: !!props.children,
      'min-height': props.type === 'textarea' && !props.autosize
    }]);

    if (props.children) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(controlClass)
      }, props.children);
    }

    var handleChange = function handleChange(e) {
      var _e$currentTarget;

      var maxlength = props.maxlength,
          onChange = props.onChange;
      var inputValue = e == null ? void 0 : (_e$currentTarget = e.currentTarget) == null ? void 0 : _e$currentTarget.value;
      var finalValue = inputValue;

      if ((0, _utils.isDef)(maxlength) && finalValue.length > +maxlength) {
        finalValue = finalValue.slice(0, maxlength);
      }

      if (type === 'number' || type === 'digit') {
        var isNumber = type === 'number';
        finalValue = (0, _utils.formatNumber)(finalValue, isNumber, isNumber);
      }

      finalValue = formatValue(finalValue, 'onChange'); // if (inputRef.value && inputValue !== inputRef.value.value) {
      //   inputRef.value.value = inputValue;
      // }

      if (onChange && typeof onChange === 'function') {
        onChange(finalValue);
      }
    };

    var handleFocus = function handleFocus(e) {
      var onFocus = props.onFocus;
      setInputFocus(true);

      if (onFocus && typeof onFocus === 'function') {
        onFocus(e);
      } // readonly not work in legacy mobile safari


      if (readonly) {
        blur();
      }
    };

    var handleBulr = function handleBulr(e) {
      var onBlur = props.onBlur;
      setInputFocus(false);

      if (onBlur && typeof onBlur === 'function') {
        onBlur(e);
      }

      (0, _utils.resetScroll)();
    };

    var handleKeypress = function handleKeypress(e) {
      var onKeypress = props.onKeypress;

      if (e.key === 'Enter' || +e.charCode === 13) {
        if (props.type !== 'textarea') {
          (0, _utils.preventDefault)(e);
        } // trigger blur after click keyboard search button


        if (props.type === 'search') {
          blur();
        }
      }

      if (onKeypress && typeof onKeypress === 'function') {
        onKeypress(e);
      }
    };

    if (type === 'textarea') {
      return /*#__PURE__*/_react.default.createElement("textarea", {
        ref: inputRef,
        name: name,
        rows: rows,
        className: (0, _clsx.default)(controlClass),
        value: value,
        disabled: disabled,
        readOnly: readonly,
        placeholder: placeholder || '',
        onBlur: handleBulr,
        onFocus: handleFocus,
        onChange: handleChange,
        onKeyPress: handleKeypress
      });
    }

    var inputType = type;
    var inputMode; // type="number" is weired in iOS, and can't prevent dot in Android
    // so use inputmode to set keyboard in mordern browers

    if (type === 'number') {
      inputType = 'text';
      inputMode = 'decimal';
    }

    if (type === 'digit') {
      inputType = 'tel';
      inputMode = 'numeric';
    }

    return /*#__PURE__*/_react.default.createElement("input", {
      value: value,
      type: inputType,
      inputMode: inputMode,
      ref: inputRef,
      name: name,
      className: (0, _clsx.default)(controlClass),
      disabled: disabled,
      readOnly: readonly,
      placeholder: placeholder || '',
      onBlur: handleBulr,
      onFocus: handleFocus,
      onChange: handleChange,
      onKeyPress: handleKeypress
    });
  };

  var renderLeftIcon = function renderLeftIcon() {
    var leftIcon = props.leftIcon,
        onClickLeftIcon = props.onClickLeftIcon;
    if (!leftIcon) return null;
    return /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _clsx.default)(bem('left-icon')),
      onClick: onClickLeftIcon
    }, leftIcon);
  };

  var renderRightIcon = function renderRightIcon() {
    var rightIcon = props.rightIcon,
        onClickRightIcon = props.onClickRightIcon;
    if (!rightIcon) return null;
    return /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _clsx.default)(bem('right-icon')),
      onClick: onClickRightIcon
    }, rightIcon);
  };

  var renderWordLimit = function renderWordLimit() {
    var value = props.value,
        showWordLimit = props.showWordLimit,
        maxlength = props.maxlength;

    if (showWordLimit && maxlength) {
      var count = (value ? "" + value : '').length;
      return /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(bem('word-limit'))
      }, /*#__PURE__*/_react.default.createElement("span", {
        className: (0, _clsx.default)(bem('word-num'))
      }, count), "/", maxlength);
    }

    return null;
  };

  var renderMessage = function renderMessage() {
    var message = props.errorMessage;

    if (message) {
      var errorMessageAlign = getProp('errorMessageAlign');
      return /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(bem('error-message', errorMessageAlign))
      }, message);
    }

    return null;
  };

  var renderIntro = function renderIntro() {
    if (props.intro) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(bem('intro', getProp('inputAlign')))
      }, props.intro);
    }

    return null;
  };

  var renderTooltip = function renderTooltip() {
    var tooltip = props.tooltip;

    if (tooltip) {
      var icon = /*#__PURE__*/_react.default.createElement(_icons.QuestionO, null);

      var dialogProps = {
        message: tooltip
      };

      if (!( /*#__PURE__*/_react.default.isValidElement(tooltip) || typeof tooltip === 'string')) {
        var _ref = tooltip,
            customIcon = _ref.icon,
            customDialogProps = _objectWithoutPropertiesLoose(_ref, _excluded);

        icon = customIcon || icon;
        dialogProps = customDialogProps;
      }

      return /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(bem('tooltip')),
        onClick: function onClick() {
          return _dialog.default.show(dialogProps);
        }
      }, icon);
    }

    return null;
  };

  var renderLabel = function renderLabel() {
    var label = props.label,
        colon = props.colon;

    if (label) {
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, label, colon && ':', renderTooltip());
    }

    return null;
  };

  var handleClear = function handleClear(e) {
    var onClear = props.onClear,
        onChange = props.onChange;
    inputRef.current.value = '';

    if (onChange && typeof onChange === 'function') {
      onChange('');
    }

    if (onClear && typeof onClear === 'function') {
      onClear(e);
    }
  };

  var type = props.type,
      size = props.size,
      center = props.center,
      border = props.border,
      isLink = props.isLink,
      required = props.required,
      clickable = props.clickable,
      labelAlign = props.labelAlign,
      className = props.className,
      labelClass = props.labelClass,
      valueClass = props.valueClass,
      arrowDirection = props.arrowDirection,
      autosize = props.autosize,
      disabled = props.disabled,
      button = props.button,
      titleStyle = props.titleStyle,
      error = props.error;
  return /*#__PURE__*/_react.default.createElement(_cell.default, {
    title: renderLabel(),
    size: size,
    icon: renderLeftIcon(),
    center: center,
    border: border,
    isLink: isLink,
    required: required,
    clickable: clickable,
    extra: props.extra,
    titleStyle: _extends({}, labelStyle(), titleStyle),
    valueClass: (0, _clsx.default)(bem('value'), valueClass),
    titleClass: (0, _clsx.default)(bem('label', labelAlign), labelClass),
    arrowDirection: arrowDirection,
    onClick: props.onClick,
    style: props.style,
    className: (0, _clsx.default)(bem((_bem = {
      error: error,
      disabled: disabled
    }, _bem["label-" + labelAlign] = labelAlign, _bem['min-height'] = type === 'textarea' && !autosize, _bem)), className)
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _clsx.default)(bem('body'))
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _clsx.default)(bem('control-wrapper')),
    onClick: props.onClickInput
  }, renderInput()), showClear && /*#__PURE__*/_react.default.cloneElement(props.clearIcon, {
    className: (0, _clsx.default)(bem('clear')),
    onTouchStart: handleClear,
    size: ICON_SIZE
  }), renderRightIcon(), button && /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _clsx.default)(bem('button'))
  }, button)), renderWordLimit(), renderMessage(), renderIntro());
});
Field.defaultProps = {
  clearIcon: /*#__PURE__*/_react.default.createElement(_icons.Clear, null),
  clearTrigger: 'focus',
  formatTrigger: 'onChange'
};
var FIELD_KEY = Symbol('field');
exports.FIELD_KEY = FIELD_KEY;
var FieldNamespace = Object.assign(Field, (_Object$assign = {}, _Object$assign[_constant.COMPONENT_TYPE_KEY] = FIELD_KEY, _Object$assign));
var _default = FieldNamespace;
exports.default = _default;