"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;exports.__esModule = true;exports.CurrencyInputDataTids = exports.CurrencyInput = void 0;var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _react = _interopRequireDefault(require("react"));
var _warning = _interopRequireDefault(require("warning"));
var _lodash = _interopRequireDefault(require("lodash.debounce"));
var _globalObject = require("@skbkontur/global-object");

var _utils = require("../../lib/utils");
var _client = require("../../lib/client");

var _Input = require("../Input");


var _CommonWrapper = require("../../internal/CommonWrapper");

var _rootNode = require("../../lib/rootNode");
var _createPropsGetter = require("../../lib/createPropsGetter");
var _isInstanceOf = require("../../lib/isInstanceOf");
var _FocusControlWrapper = require("../../internal/FocusControlWrapper");

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

var _SelectionHelper = require("./SelectionHelper");
var _CurrencyHelper = require("./CurrencyHelper");
var _CurrencyInputHelper = require("./CurrencyInputHelper");
var _CurrencyInputKeyboardActions = require("./CurrencyInputKeyboardActions");var _excluded = ["fractionDigits", "signed", "onSubmit", "integerDigits", "hideTrailingZeros"];var _class, _CurrencyInput;





































var CurrencyInputDataTids = exports.CurrencyInputDataTids = {
  root: 'CurrencyInput__root'
};





/** Поле для денежных сумм. */var

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











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
















    state = (0, _extends2.default)({},
    _this.getState(_this.getProps().value, _this.getProps().fractionDigits, _this.getProps().hideTrailingZeros), {
      focused: false });_this.



    tempSelectionForOnChange = _SelectionHelper.SelectionHelper.fromPosition(0);_this.






































    renderMain = function (props) {
      var fractionDigits = props.fractionDigits,signed = props.signed,onSubmit = props.onSubmit,integerDigits = props.integerDigits,hideTrailingZeros = props.hideTrailingZeros,rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);

      return /*#__PURE__*/(
        _react.default.createElement(_FocusControlWrapper.FocusControlWrapper, { onBlurWhenDisabled: _this.resetFocus }, /*#__PURE__*/
        _react.default.createElement(_Input.Input, (0, _extends2.default)({
          "data-tid": CurrencyInputDataTids.root },
        rest, {
          align: _this.getProps().align,
          value: _this.state.formatted,
          onBlur: _this.handleBlur,
          onFocus: _this.handleFocus,
          onMouseUp: _this.handleMouseUp,
          onKeyDown: _this.handleKeyDown,
          onValueChange: _this.handleValueChange,
          onPaste: _this.handlePaste,
          onCopy: _this.handleCopy,
          onCut: _this.handleCut,
          "aria-label": _this.props['aria-label'],
          onMouseEnter: _this.props.onMouseEnter,
          onMouseLeave: _this.props.onMouseLeave,
          onMouseOver: _this.props.onMouseOver,
          ref: _this.refInput,
          placeholder: _this.state.focused ? '' : getPlaceholder(props) })
        )
        ));

    };

    /** Программно устанавливает фокус на поле.
     * Появляется фокусная рамка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
     * @public
     */_this.
    focus = function () {
      if (_this.input) {
        _this.input.focus();
      }
    };

    /** Программно снимает фокус с кнопки.
     * @public
     */_this.
    blur = function () {
      if (_this.input) {
        _this.input.blur();
      }
    };














    // for IE11
    _this.debouncedSetSelectionFromEvent = (0, _lodash.default)(_this.setSelectionFromEvent, 300);_this.

    handleMouseUp = function (event) {
      if (_client.isIE11) {
        event.persist();
        _this.debouncedSetSelectionFromEvent(event);
      } else {
        _this.setSelectionFromEvent(event);
      }
    };_this.

    handleKeyDown = function (event) {
      var selection = _this.getSelection(event.target);
      _this.tempSelectionForOnChange = selection;

      if (_this.props.onKeyDown) {
        _this.props.onKeyDown(event);
        if (event.defaultPrevented) {
          return;
        }
      }

      var action = (0, _CurrencyInputKeyboardActions.extractAction)(event);

      if (action === _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.Ignore) {
        return;
      }

      if (action !== _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.Unknown) {
        event.preventDefault();
      }

      switch (action) {
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.Submit:{
            if (_this.props.onSubmit) {
              _this.props.onSubmit();
            }
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.Backspace:{
            _this.inputValue(_CurrencyInputHelper.CurrencyInputHelper.moveCursor(_this.state.formatted, selection, -1), selection.end, '');
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.Delete:{
            _this.inputValue(selection.start, _CurrencyInputHelper.CurrencyInputHelper.moveCursor(_this.state.formatted, selection, +1), '');
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.MoveCursorLeft:{
            _this.moveCursor(selection, -1);
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.MoveCursorRight:{
            _this.moveCursor(selection, +1);
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.Home:{
            _this.setState({ selection: _SelectionHelper.SelectionHelper.fromPosition(0) });
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.End:{
            var end = _this.state.formatted.length;
            _this.setState({ selection: _SelectionHelper.SelectionHelper.fromPosition(end) });
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.ExtendSelectionLeft:{
            _this.extendSelection(selection, -1);
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.ExtendSelectionRight:{
            _this.extendSelection(selection, +1);
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.FullSelection:{
            _this.setState({
              selection: _SelectionHelper.SelectionHelper.forward(0, _this.state.formatted.length)
            });
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.ExtendSelectionToStart:{
            _this.setState({
              selection: _SelectionHelper.SelectionHelper.backward(0, selection.start)
            });
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.ExtendSelectionToEnd:{
            var inputEnd = _this.state.formatted.length;
            _this.setState({
              selection: _SelectionHelper.SelectionHelper.forward(selection.start, inputEnd)
            });
            return;
          }
        case _CurrencyInputKeyboardActions.CURRENCY_INPUT_ACTIONS.Comma:{
            _this.inputValue(selection.start, selection.end, ',');
            return;
          }
      }
    };_this.

    scrollInput = function () {var _this$input;
      var node = (_this$input = _this.input) == null ? void 0 : _this$input.getNode();
      if (!node || node.scrollWidth === node.clientWidth) {
        return;
      }
      var PAD = 1;
      var SHIFT = 3;

      var selection = _this.state.selection;
      var selected = selection.start !== selection.end;
      var position = selected && selection.direction === 'forward' ? selection.end : selection.start;
      var charsCount = _this.state.formatted.length;
      var charWidth = node.scrollWidth / charsCount;
      var frame = Math.ceil(node.clientWidth / charWidth);
      var frameStart = Math.ceil(node.scrollLeft / charWidth);
      var frameEnd = frameStart + frame;

      if (position < frameStart + PAD) {
        node.scrollLeft = (position - SHIFT) * charWidth;
      }
      if (position > frameEnd - PAD) {
        node.scrollLeft = (position - frame + SHIFT) * charWidth;
      }
    };_this.

    getSelection = function (input) {
      var selection = getInputSelectionFromEvent(input);
      return {
        start: selection.start,
        end: selection.end,
        direction: _this.state.selection.direction
      };
    };_this.

    moveCursor = function (selection, step) {
      var position = _CurrencyInputHelper.CurrencyInputHelper.moveCursor(_this.state.formatted, selection, step);
      _this.setState({ selection: _SelectionHelper.SelectionHelper.fromPosition(position) });
    };_this.

    extendSelection = function (selection, step) {
      var extended = _CurrencyInputHelper.CurrencyInputHelper.extendSelection(_this.state.formatted, selection, step);
      _this.setState({ selection: extended });
    };_this.

    inputValue = function (start, end, value) {
      var result = _CurrencyInputHelper.CurrencyInputHelper.safeInsert(_this.state.formatted, start, end, value, {
        integerDigits: _this.props.integerDigits,
        fractionDigits: _this.getProps().fractionDigits,
        unsigned: !_this.props.signed
      });
      if (result) {
        var formatted = result.value;
        var selection = _SelectionHelper.SelectionHelper.fromPosition(result.position);
        _this.setState({ formatted: formatted, selection: selection }, function () {
          var parsedValue = _CurrencyHelper.CurrencyHelper.parse(formatted);
          if (_this.props.value !== parsedValue) {
            _this.props.onValueChange(parsedValue);
          }
        });
        return true;
      }

      if (_this.input) {
        _this.input.blink();
      }
      return false;
    };_this.

    getOnChangeDelta = function (value) {
      var selection = _this.tempSelectionForOnChange;
      var oldValue = _this.state.formatted;
      if (selection.start !== selection.end) {
        return value.substring(selection.start, value.length - (oldValue.length - selection.end));
      } else if (value.length > oldValue.length) {
        return value.substr(selection.start, value.length - oldValue.length);
      }
      return null;
    };_this.

    handleValueChange = function (value) {
      var selection = _this.tempSelectionForOnChange;
      var delta = _this.getOnChangeDelta(value);
      if ((0, _utils.isNonNullable)(delta) && !_this.inputValue(selection.start, selection.end, delta)) {
        _this.setState({ selection: selection });
      }
    };_this.

    handlePaste = function (event) {
      var data = event.clipboardData.getData('text');
      var selection = _this.getSelection(event.target);
      _this.inputValue(selection.start, selection.end, data);
      event.preventDefault();
      _this.props.onPaste == null || _this.props.onPaste(event);
    };_this.

    handleCopy = function (event) {
      var selection = _this.getSelection(event.target);
      if (selection.start !== selection.end) {
        var substring = _this.state.formatted.substring(selection.start, selection.end);
        var data = _CurrencyHelper.CurrencyHelper.formatForClipboard(substring);
        event.clipboardData.setData('text', data);
      }
      event.preventDefault();
    };_this.

    handleCut = function (event) {
      var selection = _this.getSelection(event.target);
      if (selection.start !== selection.end) {
        var substring = _this.state.formatted.substring(selection.start, selection.end);
        var data = _CurrencyHelper.CurrencyHelper.formatForClipboard(substring);
        event.clipboardData.setData('text', data);
        _this.inputValue(selection.start, selection.end, '');
      }
      event.preventDefault();
    };_this.

    handleFocus = function (event) {
      var _event$target = event.target,selectionStart = _event$target.selectionStart,selectionEnd = _event$target.selectionEnd,selectionDirection = _event$target.selectionDirection;
      var valueLength = event.target.value.length;

      var selection = {
        start: selectionStart !== selectionEnd ? selectionStart || 0 : selectionStart || valueLength,
        end: selectionEnd !== selectionStart ? selectionEnd || 0 : selectionEnd || valueLength,
        direction: selectionDirection || 'none'
      };

      _this.setState({
        focused: true,
        selection: selection
      });

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

    resetFocus = function () {
      var value = _CurrencyHelper.CurrencyHelper.parse(_this.state.formatted);

      _this.setState((0, _extends2.default)({},
      _this.getState(value, _this.getProps().fractionDigits, _this.getProps().hideTrailingZeros), {
        focused: false })
      );
    };_this.

    handleBlur = function (event) {
      _this.resetFocus();
      _this.props.onBlur == null || _this.props.onBlur(event);
    };_this.

    refInput = function (element) {
      _this.input = element;
    };return _this;}(0, _inheritsLoose2.default)(CurrencyInput, _React$PureComponent);var _proto = CurrencyInput.prototype;_proto.validateProps = function validateProps(props) {(0, _warning.default)(isNumeric(props.value) || (0, _utils.isNullable)(props.value), '[CurrencyInput]: Prop `value` is not a valid number. Received value is `' + props.value + '`.');(0, _warning.default)(props.maxLength === undefined, "[CurrencyInput]: Prop 'maxLength' has been deprecated. See 'integerDigits' and 'fractionDigits'");(0, _warning.default)((props.integerDigits || 0) + (props.fractionDigits || 0) <= _constants.MAX_SAFE_DIGITS, "[CurrencyInput]: Sum of 'integerDigits' and 'fractionDigits' exceeds " + _constants.MAX_SAFE_DIGITS + "." + "\nSee CurrencyInput documentation");};_proto.componentDidMount = function componentDidMount() {this.validateProps(this.getProps());};_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {var _this$getProps = this.getProps(),value = _this$getProps.value,fractionDigits = _this$getProps.fractionDigits,hideTrailingZeros = _this$getProps.hideTrailingZeros;this.validateProps(this.getProps());if (isNumeric(value) && Number(value) !== _CurrencyHelper.CurrencyHelper.parse(prevState.formatted) || prevProps.fractionDigits !== fractionDigits) {this.setState(this.getState(value, fractionDigits, hideTrailingZeros));}if ((0, _utils.isNonNullable)(prevProps.value) && (0, _utils.isNullable)(value)) {this.setState({ formatted: '' });}if (this.state.focused && this.input) {var _this$state$selection = this.state.selection,start = _this$state$selection.start,end = _this$state$selection.end;this.input.setSelectionRange(start, end);}if (prevState.selection !== this.state.selection) {this.scrollInput();}};_proto.render = function render() {return /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, (0, _extends2.default)({ rootNodeRef: this.setRootNode }, this.getProps()), this.renderMain);};_proto.getState = function getState(value, fractionDigits, hideTrailingZeros) {return { formatted: _CurrencyHelper.CurrencyHelper.format(value, { fractionDigits: fractionDigits, hideTrailingZeros: hideTrailingZeros }), selection: _SelectionHelper.SelectionHelper.fromPosition(0) };};_proto.setSelectionFromEvent = function setSelectionFromEvent(event) {var selection = getInputSelectionFromEvent(event.target);var normilized = _CurrencyInputHelper.CurrencyInputHelper.normalizeSelection(this.state.formatted, selection);this.setState({ selection: normilized });};return CurrencyInput;}(_react.default.PureComponent), _CurrencyInput.__KONTUR_REACT_UI__ = 'CurrencyInput', _CurrencyInput.displayName = 'CurrencyInput', _CurrencyInput.defaultProps = { align: 'right', fractionDigits: 2, hideTrailingZeros: false, value: null, inputMode: 'decimal' }, _CurrencyInput)) || _class;


function getInputSelectionFromEvent(input) {var _input$selectionStart, _input$selectionEnd;
  if (!(0, _isInstanceOf.isInstanceOf)(input, _globalObject.globalObject.HTMLInputElement)) {
    throw new Error('input is not HTMLInputElement');
  }

  return {
    start: (_input$selectionStart = input.selectionStart) != null ? _input$selectionStart : 0,
    end: (_input$selectionEnd = input.selectionEnd) != null ? _input$selectionEnd : 0,
    direction: input.selectionDirection
  };
}

function isNumeric(value) {
  return !isNaN(parseFloat(value)) && isFinite(value);
}

var getPlaceholder = function getPlaceholder(props) {
  if ((0, _utils.isNullable)(props.placeholder)) {
    return _CurrencyHelper.CurrencyHelper.format(0, {
      fractionDigits: props.fractionDigits,
      hideTrailingZeros: props.hideTrailingZeros
    });
  }

  return props.placeholder;
};