"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Number = void 0;
var _pick2 = _interopRequireDefault(require("ramda/src/pick"));
var _replace2 = _interopRequireDefault(require("ramda/src/replace"));
var _react = _interopRequireWildcard(require("react"));
var _reactIntl = require("react-intl");
var _styledComponents = _interopRequireWildcard(require("styled-components"));
var _ = require("../../..");
var _NormalizedElements = _interopRequireDefault(require("../../../common/NormalizedElements"));
var _utils = require("./utils");
var _utils2 = require("../../../common/utils");
var _adjustValue = _interopRequireDefault(require("./adjustValue"));
var _Text = require("../Text/Text");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
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."); }
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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var hasError = function hasError(error) {
  return error && error !== '';
};
var removeNonNumberCharacters = (0, _replace2.default)(/[^0-9 \u00A0\-.,]+/, '');
var calculateHeight = function calculateHeight(p, variant, size) {
  if (variant === 'quiet') return 'auto';
  return size === 's' ? "".concat(p.theme.spacing.unit(8), "px") : "".concat(p.theme.spacing.unit(10), "px");
};
var width = (0, _styledComponents.css)(["width:", "px;"], function (p) {
  return p.size === 's' ? p.theme.spacing.unit(8) : p.theme.spacing.unit(10);
});
var height = (0, _styledComponents.css)(["height:", ";"], function (p) {
  return calculateHeight(p, p.variant, p.size);
});
var background = (0, _styledComponents.css)(["background-color:", ";"], function (p) {
  if (p.disabled && p.variant !== 'quiet') {
    return p.theme.color.disabledBackground;
  }
  if (p.variant === 'quiet') {
    return 'transparent';
  }
  return p.theme.color.inputBackground;
});
var hoverBorderStyles = (0, _styledComponents.css)(["", ""], function (p) {
  return p.disabled ? '' : "\n      &:hover {\n        border-color: ".concat(p.theme.color.inputBorderHover, ";\n        z-index: 2;\n      }\n");
});
var focusBorderStyles = (0, _styledComponents.css)(["&:focus{border-color:", ";z-index:3;}"], function (p) {
  return p.theme.color.borderActive;
});
var borderStyles = (0, _styledComponents.css)(["border:1px solid ", ";position:relative;", " ", " border-width:", ";&:focus{border-width:1px;}", ""], function (p) {
  if (hasError(p.error)) return p.theme.color.inputBorderError;
  if (p.success) return p.theme.color.inputBorderSuccess;
  return p.theme.color.inputBorder;
}, hoverBorderStyles, focusBorderStyles, function (p) {
  return p.variant === 'quiet' ? '0 0 2px 0' : '1px';
}, function (p) {
  return p.disabled && p.variant === 'quiet' ? "border-color: ".concat(p.theme.isDarkMode ? p.theme.color.inputBorder : p.theme.color.buttonBackgroundDisabled, ";") : '';
});
var Wrapper = (0, _styledComponents.default)(_.Flexbox).withConfig({
  displayName: "Number__Wrapper",
  componentId: "sc-qvkb6m-0"
})(["position:relative;box-shadow:0 1px 3px ", ";"], function (p) {
  return p.theme.color.shadowInput;
});
var getPositionStyles = function getPositionStyles(p) {
  if (p.position === 'right') return "right: ".concat(p.theme.spacing.unit(2), "px;");
  if (p.position === 'left') return "left: ".concat(p.theme.spacing.unit(2), "px;");
  return '';
};
var AddonBox = (0, _styledComponents.default)(_.Flexbox).withConfig({
  displayName: "Number__AddonBox",
  componentId: "sc-qvkb6m-1"
})(["position:absolute;top:0;height:100%;z-index:3;", ""], getPositionStyles);
var Stepper = _styledComponents.default.button.attrs(function () {
  return {
    type: 'button'
  };
}).withConfig({
  displayName: "Number__Stepper",
  componentId: "sc-qvkb6m-2"
})(["", " ", " ", " ", " padding:0;cursor:pointer;box-sizing:border-box;display:flex;align-items:center;justify-content:center;flex:1 0 auto;&:first-of-type{order:-1;border-top-left-radius:", ";border-bottom-left-radius:", ";}&:last-of-type{border-top-right-radius:", ";border-bottom-right-radius:", ";}&:active:enabled{background-color:", ";svg{fill:", ";}}"], width, height, background, borderStyles, function (p) {
  return p.theme.borderRadius4;
}, function (p) {
  return p.theme.borderRadius4;
}, function (p) {
  return p.theme.borderRadius4;
}, function (p) {
  return p.theme.borderRadius4;
}, function (p) {
  return p.theme.color.cta;
}, function (p) {
  return p.theme.color.buttonText;
});
var Input = (0, _styledComponents.default)(_NormalizedElements.default.Input).attrs(function () {
  return {
    type: 'text'
  };
}).withConfig({
  displayName: "Number__Input",
  componentId: "sc-qvkb6m-3"
})(["", " ", " ", " ", " padding:", "px;width:100%;color:", ";&:disabled{color:", ";}text-align:", ";box-sizing:border-box;border-radius:", ";", " ", " ", ";"], background, borderStyles, height, _Text.placeholderNormalization, function (p) {
  return p.theme.spacing.unit(p.variant === 'quiet' ? 0 : 2);
}, function (p) {
  return p.theme.color.text;
}, function (p) {
  return p.theme.color.disabledText;
}, function (p) {
  return p.showSteppers ? 'center' : 'left';
}, function (p) {
  return p.showSteppers ? '0' : p.theme.borderRadius4;
}, function (p) {
  return p.leftAddon || p.rightAddon ? "\n      padding-top: ".concat(p.theme.spacing.unit(2), "px;\n      padding-bottom: ").concat(p.theme.spacing.unit(2), "px;\n      ") : "\n      margin: 0 -1px;\n      min-width: 0;\n      z-index: 1;\n      ";
}, function (p) {
  return p.leftAddon ? "\n      padding-left: ".concat(p.theme.spacing.unit(8), "px;\n    ") : '';
}, function (p) {
  return p.variant === 'quiet' ? "color: ".concat(p.theme.isDarkMode ? p.theme.color.buttonText : p.theme.color.backgroundBlack, ";\n        &:disabled {\n          color: ").concat(p.theme.color.disabledText, ";\n        }\n        font-size: 28px;\n        font-weight: bold;\n        &:focus {\n          border-width: 0 0 2px 0;\n          outline: none;\n        }\n        &:-webkit-autofill {\n         -webkit-text-fill-color: ").concat(p.theme.color.cta, ";\n        }\n        ") : '';
});
var components = {
  AddonBox: AddonBox,
  Input: Input,
  Stepper: Stepper,
  Wrapper: Wrapper
};
var NumberInput = function NumberInput(props) {
  var autoFocus = props.autoFocus,
    autoComplete = props.autoComplete,
    defaultValue = props.defaultValue,
    disabled = props.disabled,
    error = props.error,
    id = props.id,
    leftAddon = props.leftAddon,
    max = props.max,
    _props$min = props.min,
    min = _props$min === void 0 ? 0 : _props$min,
    name = props.name,
    noSteppers = props.noSteppers,
    onBlur = props.onBlur,
    onChange = props.onChange,
    onClick = props.onClick,
    onFocus = props.onFocus,
    onKeyDown = props.onKeyDown,
    onKeyPress = props.onKeyPress,
    onKeyUp = props.onKeyUp,
    onStepDown = props.onStepDown,
    onStepUp = props.onStepUp,
    placeholderRaw = props.placeholder,
    rightAddon = props.rightAddon,
    required = props.required,
    size = props.size,
    _props$step = props.step,
    step = _props$step === void 0 ? 1 : _props$step,
    _props$inputMode = props.inputMode,
    inputMode = _props$inputMode === void 0 ? 'decimal' : _props$inputMode,
    success = props.success,
    controlledValueRaw = props.value,
    visuallyEmphasiseRequired = props.visuallyEmphasiseRequired,
    _props$variant = props.variant,
    variant = _props$variant === void 0 ? 'normal' : _props$variant;
  var _useState = (0, _react.useState)((0, _utils.getNumberAsString)(defaultValue)),
    _useState2 = _slicedToArray(_useState, 2),
    internalValue = _useState2[0],
    setInternalValue = _useState2[1];
  var intl = (0, _reactIntl.useIntl)();
  var showSteppers = noSteppers !== true && (0, _utils2.isUndefined)(leftAddon) && (0, _utils2.isUndefined)(rightAddon) && variant !== 'quiet';
  var placeholder = showSteppers ? undefined : placeholderRaw;
  var handleValueChange = function handleValueChange(val) {
    setInternalValue(val);
    if (typeof onChange === 'function') {
      onChange(val);
    }
  };
  var inputRef = (0, _react.useRef)(null);
  var isControlled = (0, _utils2.isString)(controlledValueRaw) || (0, _utils2.isNumber)(controlledValueRaw);
  var numberAsString = controlledValueRaw === '-' ? controlledValueRaw : (0, _utils.getNumberAsString)(controlledValueRaw);
  var controlledValue = isControlled && numberAsString;
  var value = isControlled ? controlledValue : internalValue;
  var sanitizedNumbers = {
    max: max ? (0, _utils.getStringAsNumber)(max) : undefined,
    min: min ? (0, _utils.getStringAsNumber)(min) : undefined,
    step: (0, _utils2.isNumber)(step) ? step : (0, _utils.getStringAsNumber)(step),
    uncontrolledValue: (0, _utils.getStringAsNumber)(value)
  };
  var getUpdateValue = function getUpdateValue(increment) {
    return (0, _adjustValue.default)({
      originalValue: sanitizedNumbers.uncontrolledValue,
      step: sanitizedNumbers.step,
      min: sanitizedNumbers.min,
      max: sanitizedNumbers.max,
      shouldIncrement: increment,
      intl: intl
    });
  };
  var onStepHandler = function onStepHandler(stepUp) {
    var updatedValue = getUpdateValue(stepUp);
    handleValueChange(updatedValue);
    if (stepUp && onStepUp) {
      onStepUp();
    }
    if (!stepUp && onStepDown) {
      onStepDown();
    }
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };
  var onChangeHandler = function onChangeHandler(e) {
    handleValueChange(e.target.value);
  };
  var onKeyDownHandler = function onKeyDownHandler(e) {
    var key = e.key;
    var upKey = 'ArrowUp';
    var downKey = 'ArrowDown';
    if (key === upKey || key === downKey) {
      e.preventDefault();
      onStepHandler(key === upKey);
    }
    if (onKeyDown) {
      onKeyDown(e);
    }
  };
  if (props.fieldId) {
    (0, _utils2.assert)(false, "Input.Number: The prop fieldId is deprecated, please use id instead", {
      level: 'warn'
    });
  }
  if (props.hasError) {
    (0, _utils2.assert)(false, "Input.Number: The prop hasError is deprecated and not needed. The error prop is enough.", {
      level: 'warn'
    });
  }
  return _react.default.createElement(_.FormField, _extends({}, (0, _pick2.default)(['error', 'extraInfo', 'hideLabel', 'label', 'labelTooltip', 'labelTooltipPosition', 'labelTooltipInModal', 'width', 'className'], props), {
    required: visuallyEmphasiseRequired,
    fieldId: id
  }), _react.default.createElement(_.Typography, {
    type: "secondary",
    color: function color(t) {
      return t.color.text;
    }
  }, _react.default.createElement(Wrapper, {
    container: true,
    item: true,
    grow: 1,
    alignItems: "center"
  }, _react.default.createElement(Input, _extends({
    autoFocus: autoFocus,
    disabled: disabled,
    id: id,
    error: error,
    leftAddon: leftAddon,
    max: max,
    min: min,
    name: name,
    onBlur: onBlur,
    onChange: onChangeHandler,
    onClick: onClick,
    onFocus: onFocus,
    onKeyDown: onKeyDownHandler,
    onKeyPress: onKeyPress,
    onKeyUp: onKeyUp,
    placeholder: placeholder,
    ref: inputRef,
    rightAddon: rightAddon,
    required: required,
    size: size,
    step: step,
    success: success,
    value: removeNonNumberCharacters(value),
    inputMode: inputMode,
    showSteppers: showSteppers,
    variant: variant
  }, hasError(error) ? {
    'aria-invalid': true
  } : {}, autoComplete ? {
    autoComplete: autoComplete
  } : {})), showSteppers && _react.default.createElement(_react.default.Fragment, null, _react.default.createElement(Stepper, {
    onClick: function onClick() {
      return onStepHandler(false);
    },
    size: size,
    disabled: disabled
  }, _react.default.createElement(_.VisuallyHidden, null, "decrease number by ", step), _react.default.createElement(_.OldIcon.Minus, {
    size: 3
  })), _react.default.createElement(Stepper, {
    onClick: function onClick() {
      return onStepHandler(true);
    },
    size: size,
    disabled: disabled
  }, _react.default.createElement(_.VisuallyHidden, null, "increase number by ", step), _react.default.createElement(_.OldIcon.Plus, {
    size: 3
  }))), leftAddon && _react.default.createElement(AddonBox, {
    container: true,
    justifyContent: "center",
    alignItems: "center",
    position: "left"
  }, leftAddon), rightAddon && _react.default.createElement(AddonBox, {
    container: true,
    justifyContent: "center",
    alignItems: "center",
    position: "right",
    variant: variant
  }, rightAddon))));
};
NumberInput.components = components;
var Number = exports.Number = NumberInput;