"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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

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

var _uuid = require("uuid");

var _lodash = require("lodash");

var _box = require("../../../primitives/box");

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

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

var _components = require("./components");

var _forms = require("../internals/forms.common");

var _helpers = require("./helpers");

var _typography = require("../../typography");

var _hideAccessibly = require("../../../primitives/hide-accessibly");

var _aria = require("../../../mixins/aria");

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _extends() { _extends = Object.assign || 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(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var TextInput = function TextInput(_ref) {
  var _ref$id = _ref.id,
      id = _ref$id === void 0 ? '' : _ref$id,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'text' : _ref$type,
      placeholder = _ref.placeholder,
      label = _ref.label,
      _ref$labelStyle = _ref.labelStyle,
      labelStyle = _ref$labelStyle === void 0 ? 'floating' : _ref$labelStyle,
      value = _ref.value,
      _ref$disabled = _ref.disabled,
      disabled = _ref$disabled === void 0 ? false : _ref$disabled,
      _ref$readOnly = _ref.readOnly,
      readOnly = _ref$readOnly === void 0 ? false : _ref$readOnly,
      focusOnMount = _ref.focusOnMount,
      _ref$fontSize = _ref.fontSize,
      fontSize = _ref$fontSize === void 0 ? 'f2' : _ref$fontSize,
      error = _ref.error,
      success = _ref.success,
      description = _ref.description,
      customMaskOptions = _ref.customMaskOptions,
      _ref$isEmbeddable = _ref.isEmbeddable,
      isEmbeddable = _ref$isEmbeddable === void 0 ? false : _ref$isEmbeddable,
      inputMode = _ref.inputMode,
      _ref$onChange = _ref.onChange,
      onChange = _ref$onChange === void 0 ? function (_value, _formattedValue) {} : _ref$onChange,
      onBlur = _ref.onBlur,
      onFocus = _ref.onFocus,
      onRef = _ref.onRef,
      hideValueButtonLabel = _ref.hideValueButtonLabel,
      revealValueButtonLabel = _ref.revealValueButtonLabel,
      dataQa = _ref['data-qa'],
      dataCy = _ref['data-cy'],
      name = _ref.name,
      autocomplete = _ref.autocomplete,
      locked = _ref.locked,
      onClear = _ref.onClear,
      clearButtonLabel = _ref.clearButtonLabel,
      currencyCode = _ref.currencyCode,
      decimalPlaces = _ref.decimalPlaces,
      props = _objectWithoutProperties(_ref, ["id", "type", "placeholder", "label", "labelStyle", "value", "disabled", "readOnly", "focusOnMount", "fontSize", "error", "success", "description", "customMaskOptions", "isEmbeddable", "inputMode", "onChange", "onBlur", "onFocus", "onRef", "hideValueButtonLabel", "revealValueButtonLabel", "data-qa", "data-cy", "name", "autocomplete", "locked", "onClear", "clearButtonLabel", "currencyCode", "decimalPlaces"]);

  var inputId = (0, _react.useMemo)(function () {
    return "input-".concat(id, "-").concat((0, _uuid.v4)());
  }, [id]);
  var descriptionId = (0, _react.useMemo)(function () {
    return "description-".concat(id, "-").concat((0, _uuid.v4)());
  }, [id]);

  var _useState = (0, _react.useState)(type !== 'password'),
      _useState2 = _slicedToArray(_useState, 2),
      textVisible = _useState2[0],
      setTextVisible = _useState2[1];

  var disableAutofillProps = (0, _utils.useDisableAutofill)(autocomplete);
  var maskOptions = (0, _react.useMemo)(function () {
    return (0, _helpers.getMaskOptions)(type, currencyCode, decimalPlaces, customMaskOptions);
  }, [type, currencyCode, decimalPlaces, customMaskOptions]);

  if (labelStyle === 'hidden') {
    // eslint-disable-next-line no-console
    console.warn('LabelStyle="hidden" is deprecated for a11y reasons and will be removed in a future release.');
  }

  var hasErrorMessage = error != null && typeof error !== 'boolean';
  var hasText = value != null && value !== '';
  var showMessage = hasErrorMessage || description != null && description !== '' || success != null && success !== ''; // Cleave's ref handling needs to be updated. See https://github.com/nosir/cleave.js/issues/497
  // For now we need to work around it with a custom callback prop instead of using
  // forwardRef.

  var handleHtmlRef = function handleHtmlRef(ref) {
    if (onRef != null) {
      onRef(ref);
    }
  };

  var handleClear = function handleClear() {
    onChange();

    if (onClear) {
      onClear();
    }
  };

  var handleChange = function handleChange(event) {
    onChange(event.target.rawValue, event.target.value);
  };

  return /*#__PURE__*/_react["default"].createElement(_box.Box, _extends({
    "data-qa": dataQa,
    "data-cy": dataCy,
    id: id,
    stacked: "column"
  }, (0, _lodash.omit)(props, _aria.INPUT_ROLE_ARIA_PROPS)), labelStyle === 'external' && /*#__PURE__*/_react["default"].createElement(_typography.FieldLabel, {
    htmlFor: inputId
  }, label), labelStyle === 'external-large' && /*#__PURE__*/_react["default"].createElement(_typography.FieldLabel, {
    htmlFor: inputId,
    spacing: "mb2"
  }, label), labelStyle === 'hidden' && /*#__PURE__*/_react["default"].createElement(_hideAccessibly.HideAccessibly, null, /*#__PURE__*/_react["default"].createElement("label", {
    htmlFor: inputId
  }, label)), /*#__PURE__*/_react["default"].createElement(_components.Wrapper, {
    stacked: "row",
    align: "center",
    justify: "space-between",
    disabled: disabled,
    readOnly: readOnly,
    isEmbeddable: isEmbeddable,
    labelStyle: labelStyle
  }, type === 'search' && /*#__PURE__*/_react["default"].createElement(_components.IconBox, {
    labelStyle: labelStyle,
    stacked: "row",
    align: "center",
    spacing: "pl1",
    "aria-hidden": true
  }, /*#__PURE__*/_react["default"].createElement(_icon.SearchIcon, null)), /*#__PURE__*/_react["default"].createElement(_components.RelativeBox, {
    grow: 1,
    stacked: "column",
    align: "stretch"
  }, labelStyle === 'floating' && /*#__PURE__*/_react["default"].createElement(_forms.FloatingLabel, {
    htmlFor: inputId,
    fontSize: fontSize,
    isEmbeddable: isEmbeddable,
    hasLeftIcon: type === 'search',
    labelStyle: labelStyle,
    "data-has-value": value != null && value !== ''
  }, label), /*#__PURE__*/_react["default"].createElement(_components.Input, _extends({
    id: inputId,
    type: (0, _helpers.getDomType)(type, textVisible),
    disabled: disabled,
    readOnly: readOnly,
    value: value != null ? String(value) : '',
    onChange: handleChange,
    onFocus: onFocus,
    onBlur: onBlur,
    inputMode: inputMode == null ? (0, _helpers.getInputModeType)(type) : inputMode,
    options: maskOptions,
    htmlRef: handleHtmlRef,
    name: name,
    spellCheck: type === 'email' || type === 'password' ? false : undefined
  }, disableAutofillProps, {
    placeholder: placeholder,
    error: error,
    fontSize: fontSize,
    isEmbeddable: isEmbeddable,
    labelStyle: labelStyle
  }, (0, _lodash.pick)(props, _aria.INPUT_ROLE_ARIA_PROPS), {
    "aria-invalid": !!error,
    "aria-describedby": descriptionId,
    size: "1",
    "data-has-value": value != null && value !== '',
    autoFocus: focusOnMount
  }))), /*#__PURE__*/_react["default"].createElement(_components.IconBox, {
    labelStyle: labelStyle,
    stacked: "row",
    align: "center",
    spacing: "pr1"
  }, error != null && error !== false && /*#__PURE__*/_react["default"].createElement(_box.Box, {
    "aria-hidden": true,
    stacked: "row",
    align: "center"
  }, /*#__PURE__*/_react["default"].createElement(_icon.ErrorIcon, null)), locked && /*#__PURE__*/_react["default"].createElement(_icon.Lock, null), onClear && clearButtonLabel != null && hasText && /*#__PURE__*/_react["default"].createElement(_components.ClearButton, {
    onClick: handleClear,
    label: clearButtonLabel
  }), type === 'password' && /*#__PURE__*/_react["default"].createElement(_components.ShowHideButton, {
    textVisible: textVisible,
    onToggle: function onToggle() {
      return setTextVisible(function (old) {
        return !old;
      });
    },
    hideLabel: hideValueButtonLabel,
    revealLabel: revealValueButtonLabel,
    disabled: disabled
  }))), /*#__PURE__*/_react["default"].createElement(_box.Box, {
    id: descriptionId,
    spacing: showMessage ? 'mb1' : 'mb0'
  }, /*#__PURE__*/_react["default"].createElement(_box.Box, {
    "aria-live": "polite"
  }, hasErrorMessage && error != null && /*#__PURE__*/_react["default"].createElement(_forms.ErrorMessage, {
    message: error
  }), success != null && /*#__PURE__*/_react["default"].createElement(_forms.SuccessMessage, {
    message: success
  })), description != null && /*#__PURE__*/_react["default"].createElement(_forms.Description, {
    message: description
  })));
};

exports.TextInput = TextInput;
TextInput.displayName = 'TextInput';