"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof3 = require("@babel/runtime/helpers/typeof");

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

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

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

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

var _uiIcons = require("@teamleader/ui-icons");

var _button = _interopRequireDefault(require("../button"));

var _icon = _interopRequireDefault(require("../icon"));

var _SingleLineInputBase = _interopRequireDefault(require("./SingleLineInputBase"));

var _lodash = _interopRequireDefault(require("lodash.omit"));

var _theme = _interopRequireDefault(require("./theme.css"));

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

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

var _excluded = ["value"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

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

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var StepperControls = /*#__PURE__*/function (_PureComponent) {
  (0, _inherits2.default)(StepperControls, _PureComponent);

  var _super = _createSuper(StepperControls);

  function StepperControls() {
    (0, _classCallCheck2.default)(this, StepperControls);
    return _super.apply(this, arguments);
  }

  (0, _createClass2.default)(StepperControls, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          inverse = _this$props.inverse,
          stepperUpProps = _this$props.stepperUpProps,
          stepperDownProps = _this$props.stepperDownProps;
      var iconProps = {
        color: inverse ? 'teal' : 'neutral',
        element: 'button',
        tabIndex: '-1',
        tint: inverse ? 'lightest' : 'darkest',
        type: 'button'
      };
      return /*#__PURE__*/_react.default.createElement("div", {
        className: _theme.default['stepper']
      }, /*#__PURE__*/_react.default.createElement(_icon.default, (0, _extends2.default)({
        className: _theme.default['stepper-up']
      }, stepperUpProps, iconProps), /*#__PURE__*/_react.default.createElement(_uiIcons.IconChevronUpSmallOutline, null)), /*#__PURE__*/_react.default.createElement(_icon.default, (0, _extends2.default)({
        className: _theme.default['stepper-down']
      }, stepperDownProps, iconProps), /*#__PURE__*/_react.default.createElement(_uiIcons.IconChevronDownSmallOutline, null)));
    }
  }]);
  return StepperControls;
}(_react.PureComponent);

var NumericInput = /*#__PURE__*/function (_PureComponent2) {
  (0, _inherits2.default)(NumericInput, _PureComponent2);

  var _super2 = _createSuper(NumericInput);

  function NumericInput(props) {
    var _this;

    (0, _classCallCheck2.default)(this, NumericInput);
    _this = _super2.call(this, props);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleOnChange", function (event) {
      var onChange = _this.props.onChange;
      onChange && onChange(event, event.currentTarget.value);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "updateStep", function (n) {
      var _this$props2 = _this.props,
          min = _this$props2.min,
          max = _this$props2.max,
          value = _this$props2.value,
          step = _this$props2.step;
      var currentValue = (0, _utils.toNumber)(value || 0);
      var stepN = step * n;
      var newValue = currentValue + stepN;

      if (newValue % step) {
        newValue = Math.ceil(currentValue / stepN) * stepN;
      }

      var newValueBoundToMinMax = (0, _utils.parseValue)(newValue, min, max);
      var inputElement = _this.inputElement.current;

      if (inputElement) {
        var prototype = Object.getPrototypeOf(inputElement);
        var prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
        prototypeValueSetter.call(inputElement, newValueBoundToMinMax);
        inputElement.dispatchEvent(new Event('change', {
          bubbles: true
        }));
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleIncreaseValue", function () {
      _this.updateStep(1);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleDecreaseValue", function () {
      _this.updateStep(-1);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleDecreaseMouseDown", function () {
      _this.handleDecreaseValue();

      var parent = (0, _assertThisInitialized2.default)(_this);
      _this.timeout.current = setTimeout(function () {
        parent.timer.current = setInterval(function () {
          if (_this.isMinReached()) {
            _this.handleClearStepperTimer();
          } else {
            _this.handleDecreaseValue();
          }
        }, 75);
      }, 300);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleIncreaseMouseDown", function () {
      _this.handleIncreaseValue();

      var parent = (0, _assertThisInitialized2.default)(_this);
      _this.timeout.current = setTimeout(function () {
        parent.timer.current = setInterval(function () {
          if (_this.isMaxReached()) {
            _this.handleClearStepperTimer();
          } else {
            _this.handleIncreaseValue();
          }
        }, 75);
      }, 300);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleClearStepperTimer", function () {
      clearTimeout(_this.timeout.current);
      clearInterval(_this.timer.current);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleKeyDown", function (event) {
      if (event.key === _constants.KEY.ArrowUp) {
        event.preventDefault();

        _this.handleIncreaseValue();
      } else if (event.key === _constants.KEY.ArrowDown) {
        event.preventDefault();

        _this.handleDecreaseValue();
      }

      _this.props.onKeyDown && _this.props.onKeyDown(event);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleBlur", function () {
      var onBlur = _this.props.onBlur;
      onBlur && onBlur.apply(void 0, arguments);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isMaxReached", function () {
      return _this.props.value >= _this.props.max;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isMinReached", function () {
      return _this.props.value <= _this.props.min;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getConnectedRight", function () {
      var _this$props3 = _this.props,
          connectedRight = _this$props3.connectedRight,
          size = _this$props3.size,
          stepper = _this$props3.stepper;

      if (stepper === 'connected') {
        return /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: _this.isMaxReached(),
          icon: /*#__PURE__*/_react.default.createElement(_uiIcons.IconAddSmallOutline, null),
          onBlur: _this.handleBlur,
          onMouseDown: _this.handleIncreaseMouseDown,
          onMouseUp: _this.handleClearStepperTimer,
          onMouseLeave: _this.handleClearStepperTimer,
          size: size
        });
      }

      return connectedRight;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getConnectedLeft", function () {
      var _this$props4 = _this.props,
          connectedLeft = _this$props4.connectedLeft,
          size = _this$props4.size,
          stepper = _this$props4.stepper;

      if (stepper === 'connected') {
        return /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: _this.isMinReached(),
          icon: /*#__PURE__*/_react.default.createElement(_uiIcons.IconMinusSmallOutline, null),
          onMouseDown: _this.handleDecreaseMouseDown,
          onMouseUp: _this.handleClearStepperTimer,
          onMouseLeave: _this.handleClearStepperTimer,
          onBlur: _this.handleBlur,
          size: size
        });
      }

      return connectedLeft;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getSuffix", function () {
      var _this$props5 = _this.props,
          inverse = _this$props5.inverse,
          stepper = _this$props5.stepper,
          suffix = _this$props5.suffix;

      if (stepper === 'suffix') {
        return [].concat((0, _toConsumableArray2.default)(suffix), [
        /*#__PURE__*/

        /* eslint-disable-next-line react/jsx-key */
        _react.default.createElement(StepperControls, {
          inverse: inverse,
          stepperUpProps: {
            onBlur: _this.handleBlur,
            disabled: _this.isMaxReached(),
            onMouseDown: _this.handleIncreaseMouseDown,
            onMouseUp: _this.handleClearStepperTimer,
            onMouseLeave: _this.handleClearStepperTimer
          },
          stepperDownProps: {
            onBlur: _this.handleBlur,
            disabled: _this.isMinReached(),
            onMouseDown: _this.handleDecreaseMouseDown,
            onMouseUp: _this.handleClearStepperTimer,
            onMouseLeave: _this.handleClearStepperTimer
          }
        })]);
      }

      return suffix;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "setRef", function (ref) {
      _this.inputElement.current = ref;
      var forwardedRef = _this.props.forwardedRef;

      if (typeof forwardedRef === 'function') {
        forwardedRef(ref);
      } else if ((0, _typeof2.default)(forwardedRef) === 'object' && forwardedRef !== null) {
        forwardedRef.current = ref;
      }
    });
    _this.inputElement = /*#__PURE__*/_react.default.createRef();
    _this.timer = /*#__PURE__*/_react.default.createRef();
    _this.timeout = /*#__PURE__*/_react.default.createRef();
    return _this;
  }

  (0, _createClass2.default)(NumericInput, [{
    key: "render",
    value: function render() {
      var _this$props6 = this.props,
          value = _this$props6.value,
          rest = (0, _objectWithoutProperties2.default)(_this$props6, _excluded);
      var restProps = (0, _lodash.default)(rest, ['suffix', 'onChange', 'onKeyDown']);
      return /*#__PURE__*/_react.default.createElement(_SingleLineInputBase.default, (0, _extends2.default)({
        ref: this.setRef,
        type: "number",
        value: value,
        onChange: this.handleOnChange,
        onKeyDown: this.handleKeyDown
      }, restProps, {
        connectedLeft: this.getConnectedLeft(),
        connectedRight: this.getConnectedRight(),
        suffix: this.getSuffix()
      }));
    }
  }]);
  return NumericInput;
}(_react.PureComponent);

NumericInput.defaultProps = {
  min: Number.MIN_SAFE_INTEGER,
  max: Number.MAX_SAFE_INTEGER,
  step: 1,
  suffix: [],
  stepper: 'suffix'
};
/** @type {React.ComponentType<any>} */

var ForwardedNumericInput = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  return /*#__PURE__*/_react.default.createElement(NumericInput, (0, _extends2.default)({}, props, {
    forwardedRef: ref
  }));
});
ForwardedNumericInput.displayName = 'NumericInput';
var _default = ForwardedNumericInput;
exports.default = _default;