'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var Input = require('@prom-ui/core/Input');
var useId = require('@prom-ui/core/useId');
var Button = require('@prom-ui/core/Button');
var Icon = require('@prom-ui/core/Icon');
var useBodyTTag = require('@prom-ui/core/useBodyTTag');
var EyeOpen = require('@prom-ui/icons/EyeOpen');
var EyeClose = require('@prom-ui/icons/EyeClose');
var Spinner = require('@prom-ui/core/Spinner');
var Ok = require('@prom-ui/icons/Ok');
var Cancel = require('@prom-ui/icons/Cancel');

function _interopNamespaceCompat(e) {
  if (e && typeof e === 'object' && 'default' in e) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var React__namespace = /*#__PURE__*/_interopNamespaceCompat(React);

function _iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function _extends() {
  _extends = Object.assign ? Object.assign.bind() : 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;
}
function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }
  return target;
}
function _taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

var _templateObject$1, _templateObject2;
var AfterTogglePassword = function AfterTogglePassword(_ref) {
  var inputType = _ref.inputType,
    onChange = _ref.onChange;
  var _useBodyTTag = useBodyTTag.useBodyTTag(),
    t = _useBodyTTag.t;
  if (inputType === 'text') {
    return /*#__PURE__*/React__namespace.createElement(Button.Button, {
      type: "button",
      "button-height": "1-1",
      "button-width": "1-1",
      "button-padding": "none",
      onClick: function onClick() {
        return onChange('password');
      },
      title: t(_templateObject$1 || (_templateObject$1 = _taggedTemplateLiteral(["\u0421\u043A\u0440\u044B\u0442\u044C \u043F\u0430\u0440\u043E\u043B\u044C"]))),
      tabIndex: -1,
      "data-qaid": "input_field_hide_password",
      "data-testid": "input_field_hide_password"
    }, /*#__PURE__*/React__namespace.createElement(Icon.Icon, {
      "icon-as": EyeOpen.SvgEyeOpen,
      "icon-color": "black-700",
      "icon-events": "none",
      style: {
        width: 16,
        height: 16
      }
    }));
  }
  return /*#__PURE__*/React__namespace.createElement(Button.Button, {
    type: "button",
    "button-height": "1-1",
    "button-width": "1-1",
    "button-padding": "none",
    onClick: function onClick() {
      return onChange('text');
    },
    title: t(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043F\u0430\u0440\u043E\u043B\u044C"]))),
    tabIndex: -1,
    "data-qaid": "input_field_show_password",
    "data-testid": "input_field_show_password"
  }, /*#__PURE__*/React__namespace.createElement(Icon.Icon, {
    "icon-as": EyeClose.SvgEyeClose,
    "icon-color": "black-600",
    "icon-events": "none",
    style: {
      width: 16,
      height: 16
    }
  }));
};

var AfterLoading = function AfterLoading() {
  return /*#__PURE__*/React__namespace.createElement(Spinner.Spinner, {
    "spinner-color": "violet-500",
    width: 16,
    height: 16,
    "data-qaid": "input_field_loading",
    "data-testid": "input_field_loading"
  });
};

var AfterCorrectValue = function AfterCorrectValue() {
  return /*#__PURE__*/React__namespace.createElement(Icon.Icon, {
    "icon-as": Ok.SvgOk,
    "icon-color": "green-800",
    "icon-events": "none",
    "data-qaid": "input_field_correct_value",
    "data-testid": "input_field_correct_value",
    style: {
      width: 16,
      height: 16
    }
  });
};

var _templateObject;
var AfterClearValue = function AfterClearValue(props) {
  var _useBodyTTag = useBodyTTag.useBodyTTag(),
    t = _useBodyTTag.t;
  return /*#__PURE__*/React__namespace.createElement(Button.Button, _extends({
    type: "button",
    "button-height": "1-1",
    "button-width": "1-1",
    "button-padding": "none",
    title: t(_templateObject || (_templateObject = _taggedTemplateLiteral(["\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C"]))),
    tabIndex: -1,
    "data-qaid": "input_field_clear_value",
    "data-testid": "input_field_clear_value"
  }, props), /*#__PURE__*/React__namespace.createElement(Icon.Icon, {
    "icon-as": Cancel.SvgCancel,
    "icon-color": "black-600",
    "icon-events": "none",
    style: {
      width: 16,
      height: 16
    }
  }));
};

var css = {"root":"InputField__root___EVTeN","input":"InputField__input___rfpBC","beforeAndAfter":"InputField__beforeAndAfter___oqO-V","before":"InputField__before___GeS6- InputField__beforeAndAfter___oqO-V","after":"InputField__after___Cl38- InputField__beforeAndAfter___oqO-V","error":"InputField__error___hSs8w","label":"InputField__label___bwxYk","labelRequired":"InputField__labelRequired___bTTTw"};

var ErrorText = function ErrorText(_ref) {
  var id = _ref.id,
    children = _ref.children;
  return /*#__PURE__*/React__namespace.createElement("div", {
    id: id,
    className: css.error,
    "data-qaid": "input_field_error",
    "data-testid": "input_field_error"
  }, children);
};

// https://github.com/ant-design/ant-design/blob/master/components/input/Input.tsx:36
function resolveOnChange(target, e, onChange, targetValue) {
  if (!onChange) {
    return;
  }
  var event = e;
  if (e.type === 'click') {
    // Clone a new target for event.
    // Avoid the following usage, the setQuery method gets the original value.
    //
    // const [query, setQuery] = React.useState('');
    // <InputField
    //     value={query}
    //     onChange={(e)=> {
    //         setQuery((prevStatus) => e.target.value);
    //     }}
    // />

    var currentTarget = target.cloneNode(true);

    // Click clear button
    event = Object.create(e, {
      target: {
        value: currentTarget
      },
      currentTarget: {
        value: currentTarget
      }
    });
    currentTarget.value = '';
    onChange(event);
    return;
  }

  // Trigger by composition event, this means we need force change the input value
  if (targetValue !== undefined) {
    event = Object.create(e, {
      target: {
        value: target
      },
      currentTarget: {
        value: target
      }
    });
    target.value = targetValue;
    onChange(event);
    return;
  }
  onChange(event);
}
function valueToString(value) {
  if (Number.isInteger(value)) {
    return "".concat(value);
  }
  if (!value) {
    return '';
  }
  return "".concat(value);
}
function isNotEmptyArray(arr) {
  return Array.isArray(arr) && arr.length > 0;
}
function getIsValueEmpty(value) {
  return valueToString(value).length <= 0;
}
var useForwardRef = function useForwardRef(ref) {
  var initialValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  var targetRef = React__namespace.useRef(initialValue);
  React__namespace.useEffect(function () {
    if (ref) {
      if (typeof ref === 'function') {
        ref(targetRef.current);
      } else {
        ref.current = targetRef.current;
      }
    }
    return function () {};
  }, [ref]);
  return targetRef;
};
var prepareErrorList = function prepareErrorList(prefix, error) {
  var result = [];
  if (Array.isArray(error)) {
    result = error.filter(function (errorItem) {
      return Boolean(errorItem);
    }).map(function (errorItem, index) {
      return {
        id: "".concat(prefix, "-error-").concat(index),
        content: errorItem
      };
    });
  } else if (typeof error === 'string' && Boolean(error)) {
    result = [{
      id: "".concat(prefix, "-error-0"),
      content: error
    }];
  }
  return result;
};

var _excluded = ["addonBefore", "addonAfter", "addonBeforeWidth", "addonAfterWidth", "error", "label", "isLabelRequired"];
var InputField = /*#__PURE__*/React__namespace.forwardRef(function (_ref, ref) {
  var addonBefore = _ref.addonBefore,
    addonAfter = _ref.addonAfter,
    _ref$addonBeforeWidth = _ref.addonBeforeWidth,
    addonBeforeWidth = _ref$addonBeforeWidth === void 0 ? 40 : _ref$addonBeforeWidth,
    _ref$addonAfterWidth = _ref.addonAfterWidth,
    addonAfterWidth = _ref$addonAfterWidth === void 0 ? 40 : _ref$addonAfterWidth,
    _ref$error = _ref.error,
    error = _ref$error === void 0 ? false : _ref$error,
    label = _ref.label,
    isLabelRequired = _ref.isLabelRequired,
    props = _objectWithoutProperties(_ref, _excluded);
  var componentId = useId.useId();
  var isMounted = React__namespace.useRef(false);
  var isSkipOnFocus = React__namespace.useRef(false);
  var isSkipOnBlur = React__namespace.useRef(false);
  var inputRef = useForwardRef(ref, null);
  var _React$useState = React__namespace.useState(props.type),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    localType = _React$useState2[0],
    setLocalType = _React$useState2[1];
  var _React$useState3 = React__namespace.useState(getIsValueEmpty(props.value || props.defaultValue)),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    isValueEmpty = _React$useState4[0],
    setIsValueEmpty = _React$useState4[1];
  React__namespace.useEffect(function () {
    if (isMounted.current) {
      var nextIsValueEmpty = getIsValueEmpty(props.value);
      if (nextIsValueEmpty !== isValueEmpty) {
        setIsValueEmpty(nextIsValueEmpty);
      }
    } else {
      isMounted.current = true;
    }
  }, [props.value]);
  var currentAddonAfter = null;
  if (props.type === 'password' && addonAfter === 'togglePassword') {
    currentAddonAfter = /*#__PURE__*/React__namespace.createElement(AfterTogglePassword, {
      inputType: localType,
      onChange: function onChange(type) {
        return setLocalType(type);
      }
    });
  } else if (addonAfter === 'clearValue') {
    currentAddonAfter = isValueEmpty ? null : /*#__PURE__*/React__namespace.createElement(AfterClearValue, {
      onClick: function onClick(e) {
        if (!getIsValueEmpty(props.value) && !props.onChange) {
          var _inputRef$current;
          (_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 ? void 0 : _inputRef$current.focus();
          return;
        }
        if (inputRef.current) {
          setIsValueEmpty(true);
          inputRef.current.focus();
          resolveOnChange(inputRef.current, e, props.onChange);
          if (getIsValueEmpty(props.value)) {
            inputRef.current.value = '';
          }
        }
      },
      onMouseEnter: function onMouseEnter() {
        isSkipOnFocus.current = true;
        isSkipOnBlur.current = true;
      },
      onTouchStart: function onTouchStart() {
        isSkipOnFocus.current = true;
        isSkipOnBlur.current = true;
      },
      onMouseLeave: function onMouseLeave() {
        isSkipOnFocus.current = false;
        isSkipOnBlur.current = false;
      },
      onTouchEnd: function onTouchEnd() {
        isSkipOnFocus.current = false;
        isSkipOnBlur.current = false;
      }
    });
  } else if (addonAfter === 'correctValue') {
    currentAddonAfter = /*#__PURE__*/React__namespace.createElement(AfterCorrectValue, null);
  } else if (addonAfter === 'loading') {
    currentAddonAfter = /*#__PURE__*/React__namespace.createElement(AfterLoading, null);
  } else {
    currentAddonAfter = addonAfter;
  }
  var currentInputId = (props === null || props === void 0 ? void 0 : props.id) || componentId;
  var currentErrorList = prepareErrorList(currentInputId, error);
  var isLabel = !!label;
  var isBefore = !!addonBefore;
  var isAfter = !!currentAddonAfter;
  var isRenderError = isNotEmptyArray(currentErrorList);
  var isInputError = isRenderError || error === true;
  var isInputRequired = Boolean((props === null || props === void 0 ? void 0 : props.required) || isLabelRequired);
  return /*#__PURE__*/React__namespace.createElement("div", {
    className: props.className,
    style: props.style,
    "data-qaid": props['data-qaid'] || 'input_field',
    "data-testid": props['data-testid'] || 'input_field'
  }, isLabel && /*#__PURE__*/React__namespace.createElement("div", {
    className: css.label
  }, /*#__PURE__*/React__namespace.createElement("label", {
    "data-qaid": "input_field_label",
    "data-testid": "input_field_label",
    htmlFor: currentInputId
  }, label), isInputRequired && /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, "\xA0", /*#__PURE__*/React__namespace.createElement("span", {
    className: css.labelRequired,
    "data-qaid": "input_field_label_required",
    "data-testid": "input_field_label_required"
  }, "*"))), /*#__PURE__*/React__namespace.createElement("div", {
    className: css.root
  }, /*#__PURE__*/React__namespace.createElement(Input.Input, _extends({
    ref: inputRef,
    "input-theme": isInputError ? 'red' : 'white',
    "aria-invalid": isInputError,
    "aria-required": isInputRequired,
    "aria-describedby": isRenderError ? currentErrorList.map(function (_ref2) {
      var id = _ref2.id;
      return id;
    }).join(' ') : undefined
  }, props, {
    id: currentInputId,
    "data-qaid": "input_field_textbox",
    "data-testid": "input_field_textbox",
    style: {
      paddingLeft: isBefore ? addonBeforeWidth : undefined,
      paddingRight: isAfter ? addonAfterWidth : undefined
    },
    className: css.input,
    type: localType,
    onFocus: function onFocus(e) {
      if (!isSkipOnFocus.current && props.onFocus) {
        props.onFocus(e);
      }
      isSkipOnFocus.current = false;
    },
    onBlur: function onBlur(e) {
      if (!isSkipOnBlur.current && props.onBlur) {
        props.onBlur(e);
      }
      isSkipOnBlur.current = false;
    },
    onChange: function onChange(e) {
      setIsValueEmpty(getIsValueEmpty(e.target.value));
      resolveOnChange(e.currentTarget, e, props.onChange);
    }
  })), isBefore && /*#__PURE__*/React__namespace.createElement("div", {
    className: css.before,
    style: {
      width: addonBeforeWidth
    }
  }, addonBefore), isAfter && /*#__PURE__*/React__namespace.createElement("div", {
    className: css.after,
    style: {
      width: addonAfterWidth
    }
  }, currentAddonAfter)), isRenderError && currentErrorList.map(function (_ref3) {
    var id = _ref3.id,
      content = _ref3.content;
    return /*#__PURE__*/React__namespace.createElement(ErrorText, {
      key: id,
      id: id
    }, content);
  }));
});
InputField.displayName = 'InputField';

exports.InputField = InputField;

require('./style.development.v2.css');
