"use strict";

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

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

var _overrides = require("../helpers/overrides.js");

var _constants = require("./constants.js");

var _styledComponents = require("./styled-components.js");

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

var _index = require("../button/index.js");

var _hide = _interopRequireDefault(require("../icon/hide.js"));

var _show = _interopRequireDefault(require("../icon/show.js"));

var _createEvent = _interopRequireDefault(require("../utils/create-event.js"));

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

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

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 _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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

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 _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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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

var NullComponent = function NullComponent() {
  return null;
};

var BaseInput =
/*#__PURE__*/
function (_React$Component) {
  _inherits(BaseInput, _React$Component);

  function BaseInput() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, BaseInput);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(BaseInput)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      isFocused: _this.props.autoFocus || false,
      isMasked: _this.props.type === 'password'
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onInputKeyDown", function (e) {
      if (_this.props.clearable && e.key === 'Escape' && _this.props.inputRef.current) {
        _this.clearValue(); // prevent event from closing modal or doing something unexpected


        e.stopPropagation();
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onClearIconClick", function () {
      if (_this.props.inputRef.current) {
        _this.clearValue(); // return focus to the input after click


        _this.props.inputRef.current.focus();
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onFocus", function (e) {
      _this.setState({
        isFocused: true
      });

      _this.props.onFocus(e);
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onBlur", function (e) {
      _this.setState({
        isFocused: false
      });

      _this.props.onBlur(e);
    });

    return _this;
  }

  _createClass(BaseInput, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props = this.props,
          inputRef = _this$props.inputRef,
          autoFocus = _this$props.autoFocus,
          clearable = _this$props.clearable;

      if (inputRef.current) {
        if (autoFocus) {
          inputRef.current.focus();
        }

        if (clearable) {
          inputRef.current.addEventListener('keydown', this.onInputKeyDown);
        }
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var _this$props2 = this.props,
          inputRef = _this$props2.inputRef,
          clearable = _this$props2.clearable;

      if (clearable && inputRef.current) {
        inputRef.current.removeEventListener('keydown', this.onInputKeyDown);
      }
    }
  }, {
    key: "clearValue",
    value: function clearValue() {
      // trigger a fake input change event (as if all text was deleted)
      var input = this.props.inputRef.current;

      if (input) {
        var nativeInputValue = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value');

        if (nativeInputValue) {
          var nativeInputValueSetter = nativeInputValue.set;

          if (nativeInputValueSetter) {
            nativeInputValueSetter.call(input, '');
            var event = (0, _createEvent.default)('input');
            input.dispatchEvent(event);
          }
        }
      }
    }
  }, {
    key: "getInputType",
    value: function getInputType() {
      // If the type prop is equal to "password" we allow the user to toggle between
      // masked and non masked text. Internally, we toggle between type "password"
      // and "text".
      if (this.props.type === 'password') {
        return this.state.isMasked ? 'password' : 'text';
      } else {
        return this.props.type;
      }
    }
  }, {
    key: "renderMaskToggle",
    value: function renderMaskToggle() {
      var _SIZE$compact$SIZE$de,
          _this2 = this;

      if (this.props.type !== 'password') return null;

      var _getOverrides = (0, _overrides.getOverrides)(this.props.overrides.MaskToggleButton, _index.Button),
          _getOverrides2 = _slicedToArray(_getOverrides, 2),
          MaskToggleButton = _getOverrides2[0],
          maskToggleButtonProps = _getOverrides2[1];

      var baseButtonOverrides = {
        BaseButton: {
          style: function style(_ref) {
            var $theme = _ref.$theme;
            return {
              color: $theme.colors.foreground
            };
          }
        }
      }; // $FlowFixMe

      maskToggleButtonProps.overrides = (0, _overrides.mergeOverrides)(baseButtonOverrides, // $FlowFixMe
      maskToggleButtonProps.overrides);

      var _getOverrides3 = (0, _overrides.getOverrides)(this.props.overrides.MaskToggleShowIcon, _show.default),
          _getOverrides4 = _slicedToArray(_getOverrides3, 2),
          MaskToggleShowIcon = _getOverrides4[0],
          maskToggleIconShowProps = _getOverrides4[1];

      var _getOverrides5 = (0, _overrides.getOverrides)(this.props.overrides.MaskToggleHideIcon, _hide.default),
          _getOverrides6 = _slicedToArray(_getOverrides5, 2),
          MaskToggleHideIcon = _getOverrides6[0],
          maskToggleIconHideProps = _getOverrides6[1];

      var label = this.state.isMasked ? 'Show password text' : 'Hide password text';
      var iconSize = (_SIZE$compact$SIZE$de = {}, _defineProperty(_SIZE$compact$SIZE$de, _constants.SIZE.compact, '16px'), _defineProperty(_SIZE$compact$SIZE$de, _constants.SIZE.default, '20px'), _defineProperty(_SIZE$compact$SIZE$de, _constants.SIZE.large, '24px'), _SIZE$compact$SIZE$de)[this.props.size];
      return React.createElement(MaskToggleButton, _extends({
        "aria-label": label,
        kind: _index.KIND.minimal,
        onClick: function onClick() {
          return _this2.setState({
            isMasked: !_this2.state.isMasked
          });
        },
        title: label
      }, maskToggleButtonProps), this.state.isMasked ? React.createElement(MaskToggleShowIcon, _extends({
        size: iconSize,
        title: label
      }, maskToggleIconShowProps)) : React.createElement(MaskToggleHideIcon, _extends({
        size: iconSize,
        title: label
      }, maskToggleIconHideProps)));
    }
  }, {
    key: "renderClear",
    value: function renderClear() {
      var _this$props3 = this.props,
          clearable = _this$props3.clearable,
          value = _this$props3.value,
          disabled = _this$props3.disabled,
          _this$props3$override = _this$props3.overrides,
          overrides = _this$props3$override === void 0 ? {} : _this$props3$override,
          size = _this$props3.size;

      if (!clearable || !value || !value.length || disabled) {
        return null;
      }

      var _getOverrides7 = (0, _overrides.getOverrides)(overrides.ClearIconContainer, _styledComponents.StyledClearIconContainer),
          _getOverrides8 = _slicedToArray(_getOverrides7, 2),
          ClearIconContainer = _getOverrides8[0],
          clearIconContainerProps = _getOverrides8[1];

      var _getOverrides9 = (0, _overrides.getOverrides)(overrides.ClearIcon, _styledComponents.StyledClearIcon),
          _getOverrides10 = _slicedToArray(_getOverrides9, 2),
          ClearIcon = _getOverrides10[0],
          clearIconProps = _getOverrides10[1];

      var ariaLabel = 'Clear value';
      return React.createElement(ClearIconContainer, _extends({
        $size: size,
        $alignTop: this.props.type === _constants.CUSTOM_INPUT_TYPE.textarea
      }, clearIconContainerProps), React.createElement(ClearIcon, _extends({
        size: size === _constants.SIZE.large ? 'scale700' : 'scale600',
        title: ariaLabel,
        "aria-label": ariaLabel,
        onClick: this.onClearIconClick,
        role: "button"
      }, clearIconProps)));
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props4 = this.props,
          value = _this$props4.value,
          type = _this$props4.type,
          _this$props4$override = _this$props4.overrides,
          InputContainerOverride = _this$props4$override.InputContainer,
          InputOverride = _this$props4$override.Input,
          BeforeOverride = _this$props4$override.Before,
          AfterOverride = _this$props4$override.After;
      var sharedProps = (0, _utils.getSharedProps)(this.props, this.state);

      var _getOverrides11 = (0, _overrides.getOverrides)(InputContainerOverride, _styledComponents.InputContainer),
          _getOverrides12 = _slicedToArray(_getOverrides11, 2),
          InputContainer = _getOverrides12[0],
          inputContainerProps = _getOverrides12[1];

      var _getOverrides13 = (0, _overrides.getOverrides)(InputOverride, _styledComponents.Input),
          _getOverrides14 = _slicedToArray(_getOverrides13, 2),
          Input = _getOverrides14[0],
          inputProps = _getOverrides14[1];

      var _getOverrides15 = (0, _overrides.getOverrides)(BeforeOverride, NullComponent),
          _getOverrides16 = _slicedToArray(_getOverrides15, 2),
          Before = _getOverrides16[0],
          beforeProps = _getOverrides16[1];

      var _getOverrides17 = (0, _overrides.getOverrides)(AfterOverride, NullComponent),
          _getOverrides18 = _slicedToArray(_getOverrides17, 2),
          After = _getOverrides18[0],
          afterProps = _getOverrides18[1];

      return React.createElement(InputContainer, _extends({
        "data-baseweb": this.props['data-baseweb'] || 'base-input'
      }, sharedProps, inputContainerProps), React.createElement(Before, _extends({}, sharedProps, beforeProps)), React.createElement(Input, _extends({
        ref: this.props.inputRef,
        "aria-label": this.props['aria-label'],
        "aria-labelledby": this.props['aria-labelledby'],
        "aria-describedby": this.props['aria-describedby'],
        "aria-invalid": this.props.error,
        "aria-required": this.props.required,
        autoComplete: this.props.autoComplete,
        disabled: this.props.disabled,
        id: this.props.id,
        inputMode: this.props.inputMode,
        name: this.props.name,
        onBlur: this.onBlur,
        onChange: this.props.onChange,
        onFocus: this.onFocus,
        onKeyDown: this.props.onKeyDown,
        onKeyPress: this.props.onKeyPress,
        onKeyUp: this.props.onKeyUp,
        pattern: this.props.pattern,
        placeholder: this.props.placeholder,
        type: this.getInputType(),
        value: this.props.value,
        rows: this.props.type === _constants.CUSTOM_INPUT_TYPE.textarea ? this.props.rows : null
      }, sharedProps, inputProps), type === _constants.CUSTOM_INPUT_TYPE.textarea ? value : null), this.renderClear(), this.renderMaskToggle(), React.createElement(After, _extends({}, sharedProps, afterProps)));
    }
  }]);

  return BaseInput;
}(React.Component);

_defineProperty(BaseInput, "defaultProps", {
  'aria-label': null,
  'aria-labelledby': null,
  'aria-describedby': null,
  adjoined: _constants.ADJOINED.none,
  autoComplete: 'on',
  autoFocus: false,
  disabled: false,
  error: false,
  positive: false,
  name: '',
  inputMode: 'text',
  inputRef: React.createRef(),
  onBlur: function onBlur() {},
  onChange: function onChange() {},
  onKeyDown: function onKeyDown() {},
  onKeyPress: function onKeyPress() {},
  onKeyUp: function onKeyUp() {},
  onFocus: function onFocus() {},
  onClear: function onClear() {},
  clearable: false,
  overrides: {},
  pattern: null,
  placeholder: '',
  required: false,
  size: _constants.SIZE.default,
  type: 'text'
});

var _default = BaseInput;
exports.default = _default;