"use strict";

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

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

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

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

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

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 _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

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

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

var _TextField = _interopRequireDefault(require("@material-ui/core/TextField"));

var _classnames = _interopRequireDefault(require("classnames"));

var _styles = require("@material-ui/core/styles");

var _debug = _interopRequireDefault(require("debug"));

var _isFinite = _interopRequireDefault(require("lodash/isFinite"));

var _InputAdornment = _interopRequireDefault(require("@material-ui/core/InputAdornment"));

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 log = (0, _debug["default"])('@pie-lib:config-ui:number-text-field');

var styles = function styles(theme) {
  return {
    root: {
      marginRight: theme.spacing.unit,
      '& label': {
        width: 'max-content'
      }
    }
  };
};

var fallbackNumber = function fallbackNumber(min, max) {
  if (!(0, _isFinite["default"])(min) && !(0, _isFinite["default"])(max)) {
    return 0;
  }

  if (!(0, _isFinite["default"])(min) && (0, _isFinite["default"])(max)) {
    return max;
  }

  if ((0, _isFinite["default"])(min)) {
    return min;
  }
};

var NumberTextField = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(NumberTextField, _React$Component);

  var _super = _createSuper(NumberTextField);

  function NumberTextField(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, NumberTextField);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onBlur", function (event) {
      var value = event.target.value;
      var rawNumber = parseFloat(value);
      log('rawNumber: ', rawNumber);

      var number = _this.clamp(rawNumber);

      log('number: ', number);

      if (number !== _this.state.value) {
        log('trigger update...');

        _this.setState({
          value: number.toString()
        }, function () {
          _this.props.onChange(event, number);
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "errorMessage", function () {
      var _this$props = _this.props,
          min = _this$props.min,
          max = _this$props.max;

      if (min && max) {
        return "The value must be between ".concat(min, " and ").concat(max);
      }

      if (min) {
        return "The value must be greater than ".concat(min);
      }

      if (max) {
        return "The value must be less than ".concat(max);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getError", function () {
      var value = _this.state.value;

      var _float = parseFloat(value);

      var clamped = _this.clamp(_float);

      if (clamped !== _float) {
        return _this.errorMessage();
      }
    });

    var _value = _this.clamp(props.value);

    _this.state = {
      value: _value
    };

    if (_value !== props.value) {
      _this.props.onChange({}, _value);
    }

    _this.onChange = _this.onChange.bind((0, _assertThisInitialized2["default"])(_this));
    return _this;
  }

  (0, _createClass2["default"])(NumberTextField, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(props) {
      var value = this.clamp(props.value, props.min, props.max);
      this.setState({
        value: value
      });
    }
  }, {
    key: "clamp",
    value: function clamp(value) {
      var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.props.min;
      var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.props.max;

      if (!(0, _isFinite["default"])(value)) {
        return fallbackNumber(min, max);
      }

      if ((0, _isFinite["default"])(max)) {
        value = Math.min(value, max);
      }

      if ((0, _isFinite["default"])(min)) {
        value = Math.max(value, min);
      }

      return value;
    }
    /**
     * on Blur (this can be triggered by pressing Enter, see below)
     * we check the entered value and reset it if needed
     */

  }, {
    key: "onChange",
    value: function onChange(event) {
      var value = event.target.value;
      this.setState({
        value: value
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props2 = this.props,
          className = _this$props2.className,
          classes = _this$props2.classes,
          label = _this$props2.label,
          disabled = _this$props2.disabled,
          suffix = _this$props2.suffix,
          min = _this$props2.min,
          max = _this$props2.max,
          inputClassName = _this$props2.inputClassName,
          disableUnderline = _this$props2.disableUnderline,
          showErrorWhenOutsideRange = _this$props2.showErrorWhenOutsideRange,
          variant = _this$props2.variant;
      var names = (0, _classnames["default"])(classes.root, className);
      var error = showErrorWhenOutsideRange && this.getError();
      return /*#__PURE__*/_react["default"].createElement(_TextField["default"], {
        variant: variant || 'standard',
        inputRef: function inputRef(ref) {
          _this2.inputRef = ref;
        },
        disabled: disabled,
        label: label,
        value: this.state.value,
        error: !!error,
        helperText: error,
        onChange: this.onChange,
        onBlur: this.onBlur,
        onKeyPress: function onKeyPress(e) {
          // once the Enter key is pressed, we force input blur
          if (e.key === 'Enter' && _this2.inputRef) {
            _this2.inputRef.blur();
          }
        },
        type: "number",
        className: names,
        InputLabelProps: {
          shrink: true
        },
        InputProps: {
          endAdornment: suffix && /*#__PURE__*/_react["default"].createElement(_InputAdornment["default"], {
            position: "end"
          }, suffix),
          className: inputClassName,
          disableUnderline: disableUnderline
        },
        inputProps: {
          min: min,
          max: max
        },
        margin: "normal"
      });
    }
  }]);
  return NumberTextField;
}(_react["default"].Component);

exports.NumberTextField = NumberTextField;
(0, _defineProperty2["default"])(NumberTextField, "propTypes", {
  disabled: _propTypes["default"].bool,
  classes: _propTypes["default"].object.isRequired,
  className: _propTypes["default"].string,
  inputClassName: _propTypes["default"].string,
  onChange: _propTypes["default"].func.isRequired,
  value: _propTypes["default"].number,
  min: _propTypes["default"].number,
  max: _propTypes["default"].number,
  label: _propTypes["default"].string,
  suffix: _propTypes["default"].string,
  showErrorWhenOutsideRange: _propTypes["default"].bool,
  disableUnderline: _propTypes["default"].bool,
  variant: _propTypes["default"].string
});
(0, _defineProperty2["default"])(NumberTextField, "defaultProps", {
  showErrorWhenOutsideRange: false
});

var _default = (0, _styles.withStyles)(styles)(NumberTextField);

exports["default"] = _default;
//# sourceMappingURL=number-text-field.js.map