function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React from 'react';
import { useEffect, useState } from 'react';
import classNames from 'classnames';
import mergeIds from '../utilities/mergeIds';
import useId from '../utilities/useId';
/**
 * Regular expressions for matching commonly used masks, ensure capture groups are
 * set for each set of items that are separated by a delimiter, delimiters are
 * optional and so should be shown as well with the `?` optional flag.
 */
export var RE_DATE = /^(\d{1,2})[\D]?(\d{1,2})?[\D]?(\d{1,4})?/;
export var RE_PHONE = /^\(?(\d{1,3})?\)?[\s.-]?(\d{1,3})?[\s.-]?(\d{1,4})?/;
export var RE_SSN = /([*\d]{1,3})[\s.-]?([*\d]{1,2})?[\s.-]?([\d{1,4}]+)?/;
export var RE_ZIP = /(\d{1,5})/;
export var RE_CURRENCY = /\$?[\d,.-]*/;

/**
 * This function returns a mask function which returns either the formatted match only, or
 * the formatted match + the hint substring which the regular expressions above match against
 * when determining what content has been filled in.
 */
var makeMask = function makeMask(regex, hint, formatter) {
  return function () {
    var rawInput = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
    var valueOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    var match = regex.exec(rawInput);
    var formattedMatch = match ? formatter(match) : '';
    if (valueOnly) {
      return formattedMatch;
    }
    var hintSub = hint.substring(formattedMatch.length);
    return formattedMatch + hintSub;
  };
};

/**
 * The date mask automatically pads months and days that are one digit
 */
export var DATE_MASK = makeMask(RE_DATE, 'MM/DD/YYYY', function (match) {
  var _match$slice = match.slice(1),
    _match$slice2 = _slicedToArray(_match$slice, 3),
    month = _match$slice2[0],
    day = _match$slice2[1],
    year = _match$slice2[2];
  var formattedDate = [
  // We treat all non-numeric characters as a delimiter. If they're using a
  // delimiter after a month or day, we interpret that as the user supplying
  // a single digit for month or day, which we will automatically pad for them.
  month && month.padStart(2, '0'), day && day.padStart(2, '0'), year].filter(function (s) {
    return s;
  }).join('/');
  return formattedDate;
});

/**
 * Formatting for US phone numbers
 */
export var PHONE_MASK = makeMask(RE_PHONE, '###-###-####', function (match) {
  return match.slice(1).filter(function (s) {
    return s;
  }).join('-');
});

/**
 * Formatting for US Postal codes, this could be expanded to allow for 9 digit numbers
 */
export var ZIP_MASK = makeMask(RE_ZIP, '#####', function (match) {
  return match[1];
});

/**
 * Formatting for social security numbers.
 */
export var SSN_MASK = makeMask(RE_SSN, '###-##-####', function (match) {
  /**
   * for future notice, there are rules regarding social security numbers, these could be validated
   * if we were to add error handling to useLabelMask as an additional set of functionality
   * The first part should have 3 digits and should not be 000, 666, or between 900 and 999.
   * The second part should have 2 digits and it should be from 01 to 99.
   * The third part should have 4 digits and it should be from 0001 to 9999.
   */
  return match.slice(1).filter(function (s) {
    return s;
  }).join('-');
});

/**
 * Does the same thing as SSN_MASK except that it obfuscates the first five digits
 */
export var SSN_MASK_OBFUSCATED = function SSN_MASK_OBFUSCATED(rawInput, valueOnly) {
  // Use the normal SSN_MASK function just to clean the raw input and format it
  var formatted = SSN_MASK(rawInput, true);
  // We only hide the first five digits of the SSNs
  var obfuscation = '***-**';
  var obfuscated;
  if (formatted.length < obfuscation.length) {
    obfuscated = obfuscation.substring(0, formatted.length);
  } else {
    obfuscated = obfuscation + formatted.substring(obfuscation.length);
  }
  return SSN_MASK(obfuscated, valueOnly);
};

/**
 * Currency mask is a little different, we need to modify the incoming content to strip
 * out any commas or dollar signs before evaluating it via the Intl.NumberFormat function.
 */
export var CURRENCY_MASK = makeMask(RE_CURRENCY, '$', function (match) {
  var signed = match[0].includes('-');
  var stripped = match[0].replace(/[^0-9.]/g, '');
  var clipped = stripped.includes('.') ? stripped.slice(0, stripped.indexOf('.') + 3) : stripped;
  var USDollar = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
  });
  var formatted = USDollar.format(Number(clipped)).replace(/\.00/, '');
  if (Number(clipped) > 0) {
    return signed ? '-' + formatted : formatted;
  } else {
    return '';
  }
});
export function useLabelMask(maskFn, originalInputProps) {
  var _ref, _originalInputProps$v, _originalInputProps$v2, _originalInputProps$d;
  // TODO: Once we're on React 18, we can use the `useId` hook
  var generatedId = useId('label-mask--');
  var labelMaskId = originalInputProps.id ? "".concat(originalInputProps.id, "__label-mask") : generatedId;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    focused = _useState2[0],
    setFocused = _useState2[1];
  var _onFocus = originalInputProps.onFocus,
    _onBlur = originalInputProps.onBlur,
    _onChange = originalInputProps.onChange;
  var value = (_ref = (_originalInputProps$v = (_originalInputProps$v2 = originalInputProps.value) === null || _originalInputProps$v2 === void 0 ? void 0 : _originalInputProps$v2.toString()) !== null && _originalInputProps$v !== void 0 ? _originalInputProps$v : (_originalInputProps$d = originalInputProps.defaultValue) === null || _originalInputProps$d === void 0 ? void 0 : _originalInputProps$d.toString()) !== null && _ref !== void 0 ? _ref : '';
  var _useState3 = useState(value),
    _useState4 = _slicedToArray(_useState3, 2),
    currentValue = _useState4[0],
    setCurrentValue = _useState4[1];
  useEffect(function () {
    setCurrentValue(value);
  }, [value, setCurrentValue]);
  var inputProps = _objectSpread(_objectSpread({}, originalInputProps), {}, {
    defaultValue: undefined,
    value: currentValue,
    onChange: function onChange(e) {
      setCurrentValue(e.currentTarget.value);
      if (_onChange) {
        _onChange(e);
      }
    },
    onFocus: function onFocus(e) {
      if (_onFocus) {
        _onFocus(e);
      }
      setFocused(true);
    },
    onBlur: function onBlur(e) {
      var maskedValue = maskFn(currentValue, true);
      e.currentTarget.value = maskedValue;
      e.target.value = maskedValue;
      setCurrentValue(maskedValue);
      if (_onChange) {
        _onChange(e);
      }
      if (_onBlur) {
        _onBlur(e);
      }
      setFocused(false);
    },
    type: 'text',
    inputMode: 'numeric',
    'aria-describedby': mergeIds(originalInputProps['aria-describedby'], labelMaskId)
  });
  var currentMask = maskFn(currentValue);

  // Date mask needs to return the default empty mask when not focused
  if (maskFn === DATE_MASK && !focused) {
    currentMask = maskFn('');
  }

  // SSN mask needs to obfuscate the SSN when not focused
  if (maskFn === SSN_MASK && !focused && currentValue !== '') {
    currentMask = SSN_MASK_OBFUSCATED(currentValue);
    inputProps.value = SSN_MASK_OBFUSCATED(currentValue, true);
  }
  return {
    labelMask: /*#__PURE__*/React.createElement("div", {
      className: "ds-c-label-mask",
      id: labelMaskId
    }, /*#__PURE__*/React.createElement("span", {
      className: classNames(focused && 'ds-u-visibility--screen-reader')
    }, currentMask), /*#__PURE__*/React.createElement("span", {
      className: classNames(!focused && 'ds-u-display--none'),
      "aria-hidden": "true"
    }, currentMask)),
    inputProps: inputProps
  };
}
export default useLabelMask;