"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;exports.__esModule = true;exports.InputLikeTextDataTids = exports.InputLikeText = void 0;var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));var _react = _interopRequireDefault(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _lodash = _interopRequireDefault(require("lodash.debounce"));

var _globalObject = require("@skbkontur/global-object");

var _utils = require("../../lib/utils");
var _identifiers = require("../../lib/events/keyboard/identifiers");

var _MouseDrag = require("../../lib/events/MouseDrag");
var _client = require("../../lib/client");
var _selectionHelpers = require("../../lib/dom/selectionHelpers");

var _Input = require("../../components/Input");
var _Input2 = require("../../components/Input/Input.styles");
var _ThemeContext = require("../../lib/theming/ThemeContext");


var _CommonWrapper = require("../CommonWrapper");
var _Emotion = require("../../lib/theming/Emotion");
var _listenFocusOutside = require("../../lib/listenFocusOutside");

var _rootNode = require("../../lib/rootNode");
var _createPropsGetter = require("../../lib/createPropsGetter");
var _InputLayoutAside = require("../../components/Input/InputLayout/InputLayoutAside");
var _InputLayoutContext = require("../../components/Input/InputLayout/InputLayoutContext");
var _isInstanceOf = require("../../lib/isInstanceOf");
var _FocusControlWrapper = require("../FocusControlWrapper");
var _ClearCrossIcon = require("../ClearCrossIcon/ClearCrossIcon");
var _blink2 = require("../../lib/blink");
var _SizeDecorator = require("../../lib/size/SizeDecorator");


var _HiddenInput = require("./HiddenInput");
var _InputLikeText2 = require("./InputLikeText.styles");var _excluded = ["innerRef", "tabIndex", "placeholder", "align", "borderless", "width", "error", "warning", "onValueChange", "disabled", "prefix", "suffix", "leftIcon", "rightIcon", "value", "onMouseDragStart", "onMouseDragEnd", "takeContentWidth", "aria-describedby", "aria-label", "aria-labelledby", "showClearIcon", "onClearCrossClick"];var _class, _InputLikeText;














var InputLikeTextDataTids = exports.InputLikeTextDataTids = {
  root: 'InputLikeText__root',
  input: 'InputLikeText__input',
  nativeInput: 'InputLikeText__nativeInput'
};var





InputLikeText = exports.InputLikeText = (0, _SizeDecorator.withSize)(_class = (0, _rootNode.rootNode)(_class = (_InputLikeText = /*#__PURE__*/function (_React$Component) {function InputLikeText() {var _this;for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;_this.







    getProps = (0, _createPropsGetter.createPropsGetter)(InputLikeText.defaultProps);_this.

    getClearCrossShowed = function (_ref) {var focused = _ref.focused,hovered = _ref.hovered;
      if (_this.props.disabled) {
        return false;
      }
      return (0, _Input.calculateClearCrossShowedState)({
        showClearIcon: _this.getProps().showClearIcon,
        notEmptyValue: Boolean(_this.props.children),
        focused: focused,
        hovered: hovered
      });
    };_this.

    state = {
      focused: false,
      clearCrossShowed: _this.getClearCrossShowed({
        focused: false
      })
    };_this.



    node = null;_this.
    hiddenInput = null;_this.
    lastSelectedInnerNode = null;_this.
    frozen = false;_this.
    frozenBlur = false;_this.
    dragging = false;







































    // Async call required for Firefox
    _this.selectNodeContentsDebounced = (0, _lodash.default)(_selectionHelpers.selectNodeContents, 0);_this.

    selectInnerNode = function (node, start, end) {if (start === void 0) {start = 0;}if (end === void 0) {end = 1;}
      if (_this.dragging || !node) {
        return;
      }
      if (_client.isIE11 && _globalObject.globalObject.document && (0, _listenFocusOutside.findRenderContainer)(node, _globalObject.globalObject.document.body)) {
        // Code below causes Popup to close after triggering the focus event on the body in IE11
        return;
      }
      _this.frozen = true;
      _this.frozenBlur = true;

      _this.lastSelectedInnerNode = [node, start, end];
      _this.selectNodeContentsDebounced(node, start, end);

      if (_this.focusTimeout) {
        _globalObject.globalObject.clearInterval(_this.focusTimeout);
      }
      _this.focusTimeout = _globalObject.globalObject.setTimeout(function () {return (_client.isIE11 || _client.isEdge) && _this.node && _this.node.focus();}, 0);
    };_this.






























    renderMain = function (props) {var _cx, _cx2, _cx3;
      var
        innerRef =























        props.innerRef,tabIndex = props.tabIndex,placeholder = props.placeholder,align = props.align,borderless = props.borderless,width = props.width,error = props.error,warning = props.warning,onValueChange = props.onValueChange,disabled = props.disabled,prefix = props.prefix,suffix = props.suffix,leftIcon = props.leftIcon,rightIcon = props.rightIcon,value = props.value,onMouseDragStart = props.onMouseDragStart,onMouseDragEnd = props.onMouseDragEnd,takeContentWidth = props.takeContentWidth,ariaDescribedby = props['aria-describedby'],ariaLabel = props['aria-label'],ariaLabelledby = props['aria-labelledby'],showClearIcon = props.showClearIcon,onClearCrossClick = props.onClearCrossClick,rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);

      var focused = _this.state.focused;
      var getRightIcon = function getRightIcon() {
        return _this.state.clearCrossShowed ? /*#__PURE__*/
        _react.default.createElement(_ClearCrossIcon.ClearCrossIcon, {
          "data-tid": _Input.InputDataTids.clearCross,
          size: _this.size,
          onFocus: function onFocus(event) {return event.stopPropagation();},
          onClick: onClearCrossClick }
        ) :

        rightIcon;

      };
      var leftSide = /*#__PURE__*/_react.default.createElement(_InputLayoutAside.InputLayoutAside, { icon: leftIcon, text: prefix, side: "left" });
      var rightSide = /*#__PURE__*/_react.default.createElement(_InputLayoutAside.InputLayoutAside, { icon: getRightIcon(), text: suffix, side: "right" });

      var className = (0, _Emotion.cx)(_InputLikeText2.styles.root(), _Input2.styles.root(_this.theme), _this.getSizeClassName(), (_cx = {}, _cx[
      _Input2.styles.disabled(_this.theme)] = !!disabled, _cx[
      _Input2.styles.borderless()] = !!borderless, _cx[
      _Input2.styles.focus(_this.theme)] = focused, _cx[
      _Input2.styles.hovering(_this.theme)] = !focused && !disabled && !warning && !error && !borderless, _cx[
      _Input2.styles.warning(_this.theme)] = !!warning, _cx[
      _Input2.styles.error(_this.theme)] = !!error, _cx[
      _Input2.styles.focusFallback(_this.theme)] = focused && (_client.isIE11 || _client.isEdge), _cx[
      _Input2.styles.warningFallback(_this.theme)] = !!warning && (_client.isIE11 || _client.isEdge), _cx[
      _Input2.styles.errorFallback(_this.theme)] = !!error && (_client.isIE11 || _client.isEdge), _cx[
      _Input2.styles.hideBlinkingCursor()] = _client.isMobile, _cx)
      );

      var wrapperClass = (0, _Emotion.cx)(_Input2.styles.wrapper(), (_cx2 = {}, _cx2[
      _InputLikeText2.styles.userSelectContain()] = focused, _cx2)
      );
      var size = _this.size;
      var context = _InputLayoutContext.InputLayoutContextDefault;
      Object.assign(context, { disabled: disabled, focused: focused, size: size });

      return /*#__PURE__*/(
        _react.default.createElement(_FocusControlWrapper.FocusControlWrapper, { disabled: disabled, onBlurWhenDisabled: _this.resetFocus }, /*#__PURE__*/
        _react.default.createElement("span", (0, _extends2.default)({
          "data-tid": InputLikeTextDataTids.root },
        rest, {
          className: className,
          style: { width: width, textAlign: align },
          tabIndex: disabled ? -1 : 0,
          onFocus: _this.handleFocus,
          onMouseEnter: _this.handleHover,
          onMouseLeave: _this.handleUnhover,
          onBlur: _this.handleBlur,
          ref: _this.innerRef,
          onKeyDown: _this.handleKeyDown,
          onMouseDown: _this.handleMouseDown,
          role: "textbox",
          "aria-disabled": disabled,
          "aria-describedby": ariaDescribedby,
          "aria-label": ariaLabel,
          "aria-labelledby": ariaLabelledby }), /*#__PURE__*/

        _react.default.createElement(_InputLayoutContext.InputLayoutContext.Provider, { value: context }, /*#__PURE__*/
        _react.default.createElement("input", { type: "hidden", "data-tid": InputLikeTextDataTids.nativeInput, value: value, disabled: disabled }),
        leftSide, /*#__PURE__*/
        _react.default.createElement("span", { className: wrapperClass }, /*#__PURE__*/
        _react.default.createElement("span", {
          "data-tid": InputLikeTextDataTids.input,
          className: (0, _Emotion.cx)(_Input2.styles.input(_this.theme), (_cx3 = {}, _cx3[
          _InputLikeText2.styles.absolute()] = !takeContentWidth, _cx3[
          _Input2.styles.inputFocus(_this.theme)] = focused, _cx3[
          _Input2.styles.inputDisabled(_this.theme)] = disabled, _cx3)
          ) },

        _this.props.children
        ),
        _this.renderPlaceholder()
        ),
        rightSide,
        _client.isIE11 && focused && /*#__PURE__*/_react.default.createElement(_HiddenInput.HiddenInput, { nodeRef: _this.hiddenInputRef })
        )
        )
        ));

    };_this.

    renderPlaceholder = function () {
      var _this$props = _this.props,children = _this$props.children,placeholder = _this$props.placeholder,disabled = _this$props.disabled;
      var focused = _this.state.focused;
      var hasValue = (0, _utils.isNonNullable)(children) && children !== '';

      if (!hasValue && placeholder) {var _cx4;
        return /*#__PURE__*/(
          _react.default.createElement("span", {
            className: (0, _Emotion.cx)(_Input2.styles.placeholder(_this.theme), (_cx4 = {}, _cx4[
            _Input2.styles.placeholderDisabled(_this.theme)] = disabled, _cx4[
            _Input2.styles.placeholderFocus(_this.theme)] = focused, _cx4)
            ) },

          placeholder
          ));

      }
      return null;
    };_this.

    handleDocumentMouseDown = function (e) {
      if (_this.state.focused && _this.node && (0, _isInstanceOf.isInstanceOf)(e.target, _globalObject.globalObject.Node) && !_this.node.contains(e.target)) {
        _this.defrost();
      }
    };_this.

    handleDocumentKeyDown = function (e) {
      if (_this.state.focused && (0, _identifiers.isKeyTab)(e)) {
        _this.defrost();
      }
    };_this.

    handleMouseDown = function () {
      _this.frozen = true;
    };_this.

    handleKeyDown = function (e) {
      if (_this.props.disabled) {
        return;
      }

      if (_client.isIE11 && (0, _identifiers.isShortcutPaste)(e) && _this.hiddenInput) {
        _this.frozen = true;
        _globalObject.globalObject.setTimeout(function () {
          if (_this.lastSelectedInnerNode) {var _this2;
            (_this2 = _this).selectInnerNode.apply(_this2, _this.lastSelectedInnerNode);
          }
          if (_this.node) {
            _this.node.focus();
          }
        }, 0);

        _this.hiddenInput.focus();
      }

      if (_this.props.onKeyDown) {
        _this.props.onKeyDown(e);
      }
    };_this.

    handleMouseDragStart = function (e) {var _globalObject$documen;
      _this.dragging = true;
      (_globalObject$documen = _globalObject.globalObject.document) == null || _globalObject$documen.documentElement.classList.add(_InputLikeText2.styles.userSelectNone());

      if (_this.props.onMouseDragStart) {
        _this.props.onMouseDragStart(e);
      }
    };_this.

    handleMouseDragEnd = function (e) {var _globalObject$documen2;
      // Дожидаемся onMouseUp
      _globalObject.globalObject.setTimeout(function () {
        _this.dragging = false;

        if (_this.props.onMouseDragEnd) {
          _this.props.onMouseDragEnd(e);
        }
      }, 0);

      (_globalObject$documen2 = _globalObject.globalObject.document) == null || _globalObject$documen2.documentElement.classList.remove(_InputLikeText2.styles.userSelectNone());
    };_this.

    handleFocus = function (e) {
      if (_client.isMobile) {var _this$node;
        (_this$node = _this.node) == null || _this$node.setAttribute('contenteditable', 'true');
      }

      if (_this.props.disabled) {
        if (_client.isIE11 && _globalObject.globalObject.document) {
          (0, _selectionHelpers.selectNodeContents)(_globalObject.globalObject.document.body, 0, 0);
        }
        return;
      }

      if ((_client.isIE11 || _client.isEdge) && _this.frozen) {
        _this.frozen = false;
        if (_this.state.focused) {
          return;
        }
      }

      // Auto-batching React@18 creates problems that are fixed with flushSync
      // https://github.com/skbkontur/retail-ui/pull/3144#issuecomment-1535235366
      if (_react.default.version.search('18') === 0) {
        _reactDom.default.flushSync(function () {return _this.setState({ focused: true });});
      } else {
        _this.setState({ focused: true });
      }

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

    resetFocus = function () {
      _this.selectNodeContentsDebounced.cancel();
      if (_client.isMobile) {var _this$node2;
        (_this$node2 = _this.node) == null || _this$node2.removeAttribute('contenteditable');
      }
      if ((_client.isIE11 || _client.isEdge) && _this.frozenBlur) {
        _this.frozenBlur = false;
      }
      (0, _selectionHelpers.removeAllSelections)();
      _this.setState({ focused: false });
    };_this.

    handleBlur = function (e) {
      _this.selectNodeContentsDebounced.cancel();
      if (_client.isMobile) {var _this$node3;
        (_this$node3 = _this.node) == null || _this$node3.removeAttribute('contenteditable');
      }

      if (_this.props.disabled) {
        e.stopPropagation();
        return;
      }

      if ((_client.isIE11 || _client.isEdge) && _this.frozenBlur) {
        _this.frozenBlur = false;
        return;
      }
      if ((_client.isIE11 || _client.isEdge) && _this.frozen) {
        return;
      }

      (0, _selectionHelpers.removeAllSelections)();
      _this.setState({ focused: false });

      _this.props.onBlur == null || _this.props.onBlur(e);
    };_this.

    handleHover = function () {
      _this.setState({ clearCrossShowed: _this.getClearCrossShowed({ focused: _this.state.focused, hovered: true }) });
    };_this.

    handleUnhover = function () {
      _this.setState({ clearCrossShowed: _this.getClearCrossShowed({ focused: _this.state.focused, hovered: false }) });
    };_this.

    hiddenInputRef = function (el) {
      _this.hiddenInput = el;
    };_this.

    innerRef = function (el) {
      if (_this.props.innerRef) {
        _this.props.innerRef(el);
      }
      _this.node = el;
    };_this.

    defrost = function () {
      _this.frozen = false;
      _this.frozenBlur = false;
    };_this.

    getSizeClassName = function () {var _cx5, _cx6, _cx7;
      switch (_this.size) {
        case 'large':
          return (0, _Emotion.cx)((_cx5 = {}, _cx5[
          _Input2.styles.sizeLarge(_this.theme)] = true, _cx5[
          _Input2.styles.sizeLargeFallback(_this.theme)] = _client.isIE11 || _client.isEdge, _cx5)
          );
        case 'medium':
          return (0, _Emotion.cx)((_cx6 = {}, _cx6[
          _Input2.styles.sizeMedium(_this.theme)] = true, _cx6[
          _Input2.styles.sizeMediumFallback(_this.theme)] = _client.isIE11 || _client.isEdge, _cx6)
          );
        case 'small':
        default:
          return (0, _Emotion.cx)((_cx7 = {}, _cx7[
          _Input2.styles.sizeSmall(_this.theme)] = true, _cx7[
          _Input2.styles.sizeSmallFallback(_this.theme)] = _client.isIE11 || _client.isEdge, _cx7)
          );
      }
    };return _this;}(0, _inheritsLoose2.default)(InputLikeText, _React$Component);var _proto = InputLikeText.prototype; /**
   * @public
   */_proto.focus = function focus() {if (this.node) {this.node.focus();}} /**
   * @public
   */;_proto.blur = function blur() {if (this.node) {this.node.blur();}} /**
   * @public
   */;_proto.blink = function blink() {if (this.props.disabled) {return;}(0, _blink2.blink)({ el: this.node, blinkColor: this.theme.inputBlinkColor });};_proto.getNode = function getNode() {return this.node;};_proto.componentDidMount = function componentDidMount() {var _globalObject$documen3, _globalObject$documen4;if (this.node) {_MouseDrag.MouseDrag.listen(this.node).onMouseDragStart(this.handleMouseDragStart).onMouseDragEnd(this.handleMouseDragEnd);}(_globalObject$documen3 = _globalObject.globalObject.document) == null || _globalObject$documen3.addEventListener('mousedown', this.handleDocumentMouseDown);(_globalObject$documen4 = _globalObject.globalObject.document) == null || _globalObject$documen4.addEventListener('keydown', this.handleDocumentKeyDown);};_proto.componentWillUnmount = function componentWillUnmount() {var _globalObject$documen5, _globalObject$documen6;_MouseDrag.MouseDrag.stop(this.node);(_globalObject$documen5 = _globalObject.globalObject.document) == null || _globalObject$documen5.removeEventListener('mousedown', this.handleDocumentMouseDown);(_globalObject$documen6 = _globalObject.globalObject.document) == null || _globalObject$documen6.removeEventListener('keydown', this.handleDocumentKeyDown);};_proto.render = function render() {var _this3 = this;return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Consumer, null, function (theme) {_this3.theme = theme;return /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, (0, _extends2.default)({ rootNodeRef: _this3.setRootNode }, _this3.getProps()), _this3.renderMain);});};return InputLikeText;}(_react.default.Component), _InputLikeText.__KONTUR_REACT_UI__ = 'InputLikeText', _InputLikeText.displayName = 'InputLikeText', _InputLikeText.defaultProps = { showClearIcon: 'never' }, _InputLikeText)) || _class) || _class;