"use strict";

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

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

var _reactDom = _interopRequireDefault(require("react-dom"));

var _propTypes = _interopRequireDefault(require("prop-types"));

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

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

var _base = _interopRequireDefault(require("./base"));

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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 _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

// safari in mac
var isMacSafari = typeof navigator !== 'undefined' && navigator && navigator.userAgent ? navigator.userAgent.match(/^((?!chrome|android|windows).)*safari/i) : false;
var hiddenStyle = {
  visibility: 'hidden',
  position: 'absolute',
  zIndex: '-1000',
  top: '-1000px',
  overflowY: 'hidden',
  left: 0,
  right: 0
};
/**
 * Input.TextArea
 * @order 2
 */

var TextArea =
/*#__PURE__*/
function (_Base) {
  _inherits(TextArea, _Base);

  function TextArea(props) {
    var _this;

    _classCallCheck(this, TextArea);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(TextArea).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "_resizeTextArea", function (value) {
      if (_this.nextFrameActionId) {
        (0, _util.clearNextFrameAction)(_this.nextFrameActionId);
      }

      _this.nextFrameActionId = (0, _util.onNextFrame)(function () {
        var height = _this._getHeight(value);

        var maxHeight = _this.state.maxHeight ? _this.state.maxHeight : Infinity;

        _this.setState({
          height: _this._getHeight(value),
          overflowY: height <= maxHeight ? 'hidden' : undefined
        });
      });
    });

    var _value;

    if ('value' in props) {
      _value = props.value;
    } else {
      _value = props.defaultValue;
    }

    _this.state = {
      value: typeof _value === 'undefined' ? '' : _value
    };
    return _this;
  }

  _createClass(TextArea, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var autoHeight = this.props.autoHeight;

      if (autoHeight) {
        if (_typeof(autoHeight) === 'object') {
          /* eslint-disable react/no-did-mount-set-state */
          this.setState(this._getMinMaxHeight(autoHeight, this.state.value));
        } else {
          this.setState({
            height: this._getHeight(this.state.value),
            overflowY: 'hidden'
          });
        }
      }
    }
  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if (_get(_getPrototypeOf(TextArea.prototype), "UNSAFE_componentWillReceiveProps", this)) {
        _get(_getPrototypeOf(TextArea.prototype), "UNSAFE_componentWillReceiveProps", this).call(this, nextProps);
      }

      if (this.props.autoHeight && this.props.value !== nextProps.value) {
        this._resizeTextArea(nextProps.value);
      }
    }
  }, {
    key: "_getMinMaxHeight",
    value: function _getMinMaxHeight(_ref, value) {
      var minRows = _ref.minRows,
          maxRows = _ref.maxRows;

      /* eslint-disable-next-line */
      var node = _reactDom["default"].findDOMNode(this.helpRef);

      node.setAttribute('rows', minRows);
      var minHeight = node.clientHeight;
      node.setAttribute('rows', maxRows);
      var maxHeight = node.clientHeight;
      node.setAttribute('rows', '1');

      var height = this._getHeight(value);

      return {
        minHeight: minHeight,
        maxHeight: maxHeight,
        height: height,
        overflowY: height <= maxHeight ? 'hidden' : undefined
      };
    }
  }, {
    key: "_getHeight",
    value: function _getHeight(value) {
      /* eslint-disable-next-line */
      var node = _reactDom["default"].findDOMNode(this.helpRef);

      node.value = value;
      return node.scrollHeight;
    }
  }, {
    key: "ieHack",
    value: function ieHack(value) {
      // Fix: textarea dit not support maxLength in ie9

      /* istanbul ignore if */
      if (_util.env.ieVersion === 9 && this.props.maxLength) {
        var maxLength = parseInt(this.props.maxLength);
        var len = this.getValueLength(value, true);

        if (len > maxLength && this.props.cutString) {
          value = value.replace(/\n/g, '\n\n');
          value = value.substr(0, maxLength);
          value = value.replace(/\n\n/g, '\n');
        }
      }

      this.props.autoHeight && this._resizeTextArea(value);
      return value;
    }
    /**
     * value.length !== maxLength  in ie/safari(mac) while value has `Enter`
     * about maxLength compute: `Enter` was considered to be one char(\n) in chrome , but two chars(\r\n) in ie/safari(mac).
     * so while value has `Enter`, we should let display length + 1
     */

  }, {
    key: "getValueLength",
    value: function getValueLength(value) {
      var _this$props = this.props,
          maxLength = _this$props.maxLength,
          cutString = _this$props.cutString;
      var nv = "".concat(value);
      var strLen = this.props.getValueLength(nv);

      if (typeof strLen !== 'number') {
        strLen = nv.length;
      }
      /* istanbul ignore if */


      if (_util.env.ieVersion || isMacSafari) {
        strLen = strLen + nv.split('\n').length - 1;

        if (strLen > maxLength && cutString) {
          strLen = maxLength;
        }
      }

      return strLen;
    }
  }, {
    key: "saveTextAreaRef",
    value: function saveTextAreaRef(textArea) {
      this.inputRef = textArea;
    }
  }, {
    key: "saveHelpRef",
    value: function saveHelpRef(ref) {
      this.helpRef = ref;
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames;

      var _this$props2 = this.props,
          rows = _this$props2.rows,
          style = _this$props2.style,
          className = _this$props2.className,
          autoHeight = _this$props2.autoHeight,
          prefix = _this$props2.prefix,
          rtl = _this$props2.rtl,
          hasBorder = _this$props2.hasBorder;
      var cls = (0, _classnames["default"])(this.getClass(), (_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "input-textarea"), true), _defineProperty(_classNames, "".concat(prefix, "noborder"), !hasBorder), _defineProperty(_classNames, className, !!className), _classNames));
      var props = this.getProps(); // custom data attributes are assigned to the top parent node
      // data-类自定义数据属性分配到顶层node节点

      var dataProps = _util.obj.pickAttrsWith(this.props, 'data-'); // Custom props are transparently transmitted to the core input node by default
      // 自定义属性默认透传到核心node节点：input


      var others = _util.obj.pickOthers(_extends({}, dataProps, TextArea.propTypes), this.props);

      var textareStyle = _objectSpread({}, props.style, {
        height: this.state.height,
        minHeight: this.state.minHeight,
        maxHeight: this.state.maxHeight,
        overflowY: this.state.overflowY
      });

      var wrapStyle = autoHeight ? _objectSpread({}, style, {
        position: 'relative'
      }) : style;
      return _react["default"].createElement("span", _extends({
        className: cls,
        style: wrapStyle,
        dir: rtl ? 'rtl' : undefined
      }, dataProps), _react["default"].createElement("textarea", _extends({}, others, props, {
        "data-real": true,
        rows: rows,
        style: textareStyle,
        ref: this.saveRef.bind(this),
        onKeyDown: this.onKeyDown.bind(this)
      })), autoHeight ? _react["default"].createElement("textarea", {
        "data-fake": true,
        ref: this.saveHelpRef.bind(this),
        style: _objectSpread({}, props.style, {}, hiddenStyle),
        rows: "1"
      }) : null, this.renderControl());
    }
  }]);

  return TextArea;
}(_base["default"]);

exports["default"] = TextArea;

_defineProperty(TextArea, "propTypes", _objectSpread({}, _base["default"].propTypes, {
  /**
   * 是否有边框
   */
  hasBorder: _propTypes["default"].bool,

  /**
   * 状态
   * @enumdesc 错误
   */
  state: _propTypes["default"].oneOf(['error']),

  /**
   * 自动高度 true / {minRows: 2, maxRows: 4}
   */
  autoHeight: _propTypes["default"].oneOfType([_propTypes["default"].bool, _propTypes["default"].object]),

  /**
   * 多行文本框高度 <br />(不要直接用height设置多行文本框的高度, ie9 10会有兼容性问题)
   */
  rows: _propTypes["default"].number
}));

_defineProperty(TextArea, "defaultProps", _objectSpread({}, _base["default"].defaultProps, {
  hasBorder: true,
  rows: 4,
  autoHeight: false
}));