'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var React = require('react');
var classnames = require('classnames');
var ramda = require('ramda');
var useId = require('./useId-DXHUzdxd.js');
require('react-router-dom');
require('@bigbinary/neeto-hotkeys');
require('./overlayManager.js');
var index = require('./index-CNZKW5X0.js');
require('qs');
var Label = require('./Label.js');
var jsxRuntime = require('react/jsx-runtime');
require('@babel/runtime/helpers/classCallCheck');
require('@babel/runtime/helpers/createClass');
require('@bigbinary/neeto-cist');
require('./en-B1i-pQJm.js');
require('./index-BgzkP01c.js');
require('@babel/runtime/helpers/toConsumableArray');
require('dayjs');
require('dayjs/plugin/localeData');
require('dayjs/plugin/utc');
require('dayjs/plugin/weekday');
require('dayjs/plugin/weekOfYear');
require('i18next');
require('@bigbinary/neeto-icons/Help');
require('./Button.js');
require('./Spinner.js');
require('./Tooltip.js');
require('@tippyjs/react');
require('tippy.js');
require('./usePrefersReducedMotion-D2Ck84HM.js');
require('./Popover.js');
require('./Typography.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

var toFixed = function toFixed(numStr, precision) {
  var num = Number(numStr);
  if (Number.isNaN(num)) return numStr;
  return num.toFixed(precision);
};
var isValidNumberString = function isValidNumberString(numStr) {
  if (typeof numStr !== "string") return false;
  return !Number.isNaN(Number(numStr.trim()));
};
var formatWithPrecision = function formatWithPrecision(value, precision) {
  if (precision < 0 || !value) return value;
  var str = value.toString();
  if (isValidNumberString(str)) return toFixed(str, precision);
  return str;
};
var enforceDecimalPrecision = function enforceDecimalPrecision(value, precision) {
  if (precision < 0 || !value) return value;
  var valueStr = value.toString();
  if (precision === 0) return valueStr.split(".")[0];
  var regex = new RegExp("^\\d*\\.?\\d{0,".concat(precision, "}$"));
  if (regex.test(valueStr)) return value;
  var parts = valueStr.split(".");
  if (parts.length === 1) return parts[0];
  var _parts = _slicedToArray__default.default(parts, 2),
    integerPart = _parts[0],
    decimalPart = _parts[1];
  return "".concat(integerPart, ".").concat(decimalPart.substring(0, precision));
};
var formatWithRejectCharsRegex = function formatWithRejectCharsRegex(value, rejectCharsRegex) {
  if (!rejectCharsRegex) return value;
  var globalRegex = new RegExp(rejectCharsRegex, "g");
  return ramda.replace(globalRegex, "", value);
};
var getTrimmedValue = function getTrimmedValue(value, disableTrimOnBlur) {
  if (disableTrimOnBlur || typeof value !== "string") return value;
  return value.trim();
};
var preserveCursor = function preserveCursor(e, updateValueFn) {
  var input = e.target;
  var prevCursor = input.selectionStart;
  var prevValue = input.value;
  updateValueFn();
  var lengthDiff = input.value.length - prevValue.length;
  var newCursor = Math.max(0, prevCursor + lengthDiff);
  requestAnimationFrame(function () {
    if (document.activeElement !== input) return;
    if (input.type === "number") return;
    input.setSelectionRange(newCursor, newCursor);
  });
};

var _excluded = ["size", "type", "label", "dataTestid", "error", "suffix", "prefix", "disabled", "helpText", "className", "nakedInput", "contentSize", "required", "maxLength", "unlimitedChars", "labelProps", "rejectCharsRegex", "onBlur", "disableTrimOnBlur", "precision"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var SIZES = {
  medium: "medium"};
var Input = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
  var _ref2, _formatWithPrecision;
  var _ref$size = _ref.size,
    size = _ref$size === void 0 ? SIZES.medium : _ref$size,
    _ref$type = _ref.type,
    type = _ref$type === void 0 ? "text" : _ref$type,
    _ref$label = _ref.label,
    label = _ref$label === void 0 ? "" : _ref$label,
    _ref$dataTestid = _ref.dataTestid,
    dataTestid = _ref$dataTestid === void 0 ? "" : _ref$dataTestid,
    _ref$error = _ref.error,
    error = _ref$error === void 0 ? "" : _ref$error,
    _ref$suffix = _ref.suffix,
    suffix = _ref$suffix === void 0 ? null : _ref$suffix,
    _ref$prefix = _ref.prefix,
    prefix = _ref$prefix === void 0 ? null : _ref$prefix,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _ref$helpText = _ref.helpText,
    helpText = _ref$helpText === void 0 ? "" : _ref$helpText,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? "" : _ref$className,
    _ref$nakedInput = _ref.nakedInput,
    nakedInput = _ref$nakedInput === void 0 ? false : _ref$nakedInput,
    _ref$contentSize = _ref.contentSize,
    contentSize = _ref$contentSize === void 0 ? null : _ref$contentSize,
    _ref$required = _ref.required,
    required = _ref$required === void 0 ? false : _ref$required,
    maxLength = _ref.maxLength,
    _ref$unlimitedChars = _ref.unlimitedChars,
    unlimitedChars = _ref$unlimitedChars === void 0 ? false : _ref$unlimitedChars,
    labelProps = _ref.labelProps,
    rejectCharsRegex = _ref.rejectCharsRegex,
    onBlur = _ref.onBlur,
    _ref$disableTrimOnBlu = _ref.disableTrimOnBlur,
    disableTrimOnBlur = _ref$disableTrimOnBlu === void 0 ? false : _ref$disableTrimOnBlu,
    _ref$precision = _ref.precision,
    precision = _ref$precision === void 0 ? -1 : _ref$precision,
    otherProps = _objectWithoutProperties__default.default(_ref, _excluded);
  var _useState = React.useState(otherProps.value),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    valueInternal = _useState2[0],
    setValueInternal = _useState2[1];
  var id = useId.useId(otherProps.id);
  var errorId = "error_".concat(id);
  var helpTextId = "helpText_".concat(id);
  var value = (_ref2 = (_formatWithPrecision = formatWithPrecision(otherProps.value, precision)) !== null && _formatWithPrecision !== void 0 ? _formatWithPrecision : valueInternal) !== null && _ref2 !== void 0 ? _ref2 : "";
  var valueLength = (value === null || value === void 0 ? void 0 : value.toString().length) || 0;
  var isCharacterLimitVisible = valueLength >= maxLength * 0.85;
  var maxLengthError = unlimitedChars && valueLength > maxLength;
  var onChange = function onChange(e) {
    var _otherProps$onChange;
    if (!otherProps.onChange || !otherProps.value) {
      setValueInternal(e.target.value);
    }
    (_otherProps$onChange = otherProps.onChange) === null || _otherProps$onChange === void 0 ? void 0 : _otherProps$onChange.call(otherProps, e);
  };
  var isMaxLengthPresent = !!maxLength || maxLength === 0;
  var handleChange = function handleChange(e) {
    if (type === "file") {
      onChange(e);
      return;
    }
    var formattedValue = formatWithRejectCharsRegex(e.target.value, rejectCharsRegex);
    formattedValue = enforceDecimalPrecision(formattedValue, precision);
    if (formattedValue !== e.target.value) {
      preserveCursor(e, function () {
        return ramda.mergeDeepLeft({
          target: {
            value: formattedValue
          }
        }, e);
      });
    } else {
      onChange(e);
    }
  };
  var handleOnBlur = function handleOnBlur(e) {
    if (type === "file") {
      onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
      return;
    }
    var trimmedValue = getTrimmedValue(value, disableTrimOnBlur);
    var formattedValue = formatWithPrecision(trimmedValue, precision);
    if (formattedValue !== value) {
      e.target.value = formattedValue;
      handleChange(e);
    }
    onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
  };
  var handleOnWheel = function handleOnWheel(e) {
    if (type === "number") e.target.blur();
  };
  var dataTestIdLabel = typeof label === "string" ? index.hyphenize(label) : index.hyphenize(dataTestid);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: classnames__default.default(["neeto-ui-input__wrapper", className]),
    "data-testid": "nui-input-wrapper",
    children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "neeto-ui-input__label-wrapper",
      children: [label && /*#__PURE__*/jsxRuntime.jsx(Label, _objectSpread(_objectSpread({
        required: required,
        "data-testid": "".concat(dataTestIdLabel, "-input-label"),
        htmlFor: id
      }, labelProps), {}, {
        children: label
      })), isCharacterLimitVisible && /*#__PURE__*/jsxRuntime.jsxs("p", {
        className: classnames__default.default("neeto-ui-input__max-length", {
          "neeto-ui-input__max-length--error": maxLengthError
        }),
        children: [valueLength, "/", maxLength]
      })]
    }), /*#__PURE__*/jsxRuntime.jsxs("div", {
      "data-testid": "".concat(dataTestIdLabel, "-input"),
      className: classnames__default.default("neeto-ui-input", {
        "neeto-ui-input--naked": !!nakedInput,
        "neeto-ui-input--error": !!error,
        "neeto-ui-input--disabled": !!disabled,
        "neeto-ui-input--small": size === "small",
        "neeto-ui-input--medium": size === "medium",
        "neeto-ui-input--large": size === "large"
      }),
      children: [prefix && /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "neeto-ui-input__prefix",
        children: prefix
      }), /*#__PURE__*/jsxRuntime.jsx("input", _objectSpread(_objectSpread({
        "aria-invalid": !!error,
        "data-testid": "".concat(dataTestIdLabel, "-input-field"),
        size: contentSize,
        "aria-describedby": classnames__default.default(_defineProperty__default.default(_defineProperty__default.default({}, errorId, !!error), helpTextId, helpText))
      }, _objectSpread(_objectSpread(_objectSpread({
        disabled: disabled,
        id: id,
        ref: ref,
        required: required,
        type: type
      }, isMaxLengthPresent && !unlimitedChars && {
        maxLength: maxLength
      }), otherProps), {}, {
        value: value
      })), {}, {
        onBlur: handleOnBlur,
        onChange: handleChange,
        onWheel: handleOnWheel
      })), suffix && /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "neeto-ui-input__suffix",
        children: suffix
      })]
    }), !!error && /*#__PURE__*/jsxRuntime.jsx("p", {
      className: "neeto-ui-input__error",
      "data-testid": "".concat(dataTestIdLabel, "-input-error"),
      id: errorId,
      children: error
    }), helpText && /*#__PURE__*/jsxRuntime.jsx("p", {
      className: "neeto-ui-input__help-text",
      "data-testid": "".concat(dataTestIdLabel, "-input-help"),
      id: helpTextId,
      children: helpText
    })]
  });
});
Input.displayName = "Input";

module.exports = Input;
//# sourceMappingURL=Input.js.map
