"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.SearchInput = void 0;

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

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _uuid = require("uuid");

var _lodash = require("lodash");

var _branding = require("../../../mixins/branding");

var _primitives = require("../../../primitives");

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

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

var _textInput = require("../text-input");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 NotFoundItem = (0, _styledComponents["default"])(_components.DefaultSearchResult).withConfig({
  displayName: "NotFoundItem",
  componentId: "sc-111zqxb-0"
})(["color:", ";"], (0, _branding.getPaletteColor)('greyscale-dark'));
var SeachInputContainer = (0, _styledComponents["default"])(_primitives.Box).withConfig({
  displayName: "SeachInputContainer",
  componentId: "sc-111zqxb-1"
})(["position:relative;"]);

var SearchInput = function SearchInput(_ref) {
  var _ref$value = _ref.value,
      value = _ref$value === void 0 ? null : _ref$value,
      _ref$initialValue = _ref.initialValue,
      initialValue = _ref$initialValue === void 0 ? null : _ref$initialValue,
      placeholder = _ref.placeholder,
      searchResults = _ref.searchResults,
      onChange = _ref.onChange,
      _ref$onSearchResultCl = _ref.onSearchResultClicked,
      onSearchResultClicked = _ref$onSearchResultCl === void 0 ? function (_id, _value) {} : _ref$onSearchResultCl,
      _ref$allowNotFound = _ref.allowNotFound,
      allowNotFound = _ref$allowNotFound === void 0 ? false : _ref$allowNotFound,
      _ref$showNotFoundOnly = _ref.showNotFoundOnlyOnNoResults,
      showNotFoundOnlyOnNoResults = _ref$showNotFoundOnly === void 0 ? false : _ref$showNotFoundOnly,
      notFoundText = _ref.notFoundText,
      clearLabel = _ref.clearLabel,
      label = _ref.label,
      focusOnMount = _ref.focusOnMount,
      renderItem = _ref.renderItem,
      renderNotFoundItem = _ref.renderNotFoundItem,
      _ref$clearSearchOnCli = _ref.clearSearchOnClick,
      clearSearchOnClick = _ref$clearSearchOnCli === void 0 ? false : _ref$clearSearchOnCli,
      onClear = _ref.onClear,
      spacing = _ref.spacing,
      grow = _ref.grow,
      shrink = _ref.shrink,
      basis = _ref.basis,
      onFocus = _ref.onFocus,
      onBlur = _ref.onBlur,
      className = _ref.className,
      dataQa = _ref['data-qa'],
      dataCy = _ref['data-cy'],
      id = _ref.id,
      name = _ref.name,
      _ref$error = _ref.error,
      error = _ref$error === void 0 ? false : _ref$error,
      success = _ref.success,
      description = _ref.description,
      labelStyle = _ref.labelStyle,
      props = _objectWithoutProperties(_ref, ["value", "initialValue", "placeholder", "searchResults", "onChange", "onSearchResultClicked", "allowNotFound", "showNotFoundOnlyOnNoResults", "notFoundText", "clearLabel", "label", "focusOnMount", "renderItem", "renderNotFoundItem", "clearSearchOnClick", "onClear", "spacing", "grow", "shrink", "basis", "onFocus", "onBlur", "className", "data-qa", "data-cy", "id", "name", "error", "success", "description", "labelStyle"]);

  var _useState = (0, _react.useState)(value || initialValue || ''),
      _useState2 = _slicedToArray(_useState, 2),
      searchInput = _useState2[0],
      setSearchInput = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      showSearchResults = _useState4[0],
      setShowSearchResults = _useState4[1];

  var _useState5 = (0, _react.useState)(-1),
      _useState6 = _slicedToArray(_useState5, 2),
      selectedSearchResultIndex = _useState6[0],
      setSelectedSearchResultIndex = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      _useState8 = _slicedToArray(_useState7, 2),
      timeoutId = _useState8[0],
      setTimeoutId = _useState8[1];

  var resultsListId = (0, _react.useMemo)(function () {
    return (0, _uuid.v4)();
  }, []);
  var handleChange = (0, _react.useCallback)(function (newSearchInput) {
    setSelectedSearchResultIndex(-1);
    setSearchInput(newSearchInput !== null && newSearchInput !== void 0 ? newSearchInput : '');
    onChange(newSearchInput !== null && newSearchInput !== void 0 ? newSearchInput : '');
    setShowSearchResults(!!newSearchInput);
  }, [onChange]);
  (0, _react.useEffect)(function () {
    if (value != null && searchInput !== value) {
      setSearchInput(value);
    }
  }, [searchInput, value]);
  var handleSearchResultClicked = (0, _react.useCallback)(function (resultId, newValue) {
    setSelectedSearchResultIndex(-1);
    setShowSearchResults(false);

    if (clearSearchOnClick) {
      setSearchInput('');
    } else {
      setSearchInput(newValue !== null && newValue !== void 0 ? newValue : '');
    }

    onSearchResultClicked(resultId, newValue);
  }, [onSearchResultClicked, clearSearchOnClick]);
  var handleSearchInputFocused = (0, _react.useCallback)(function (e) {
    setShowSearchResults(!!searchInput.length);
    if (onFocus) onFocus(e);
  }, [searchInput, onFocus]);
  var handleSearchInputBlurred = (0, _react.useCallback)(function (e) {
    // Wait before closing the drop-down so clicking on an item has time
    // to register before the list is dismissed.
    setTimeoutId(window.setTimeout(function () {
      return setShowSearchResults(false);
    }, 200));
    if (onBlur) onBlur(e);
  }, [onBlur]); // Clear any outstanding timeout when the component is unmounted.

  (0, _react.useEffect)(function () {
    return function () {
      return timeoutId && window.clearTimeout(timeoutId);
    };
  });
  var handleKeyDown = (0, _react.useCallback)(function (evt) {
    var enterKey = evt.keyCode === 13;

    if (enterKey && selectedSearchResultIndex >= 0) {
      var clickedResult = searchResults[selectedSearchResultIndex];

      if (clickedResult) {
        handleSearchResultClicked(clickedResult.id, clickedResult.text);
      } else {
        handleSearchResultClicked();
      }

      evt.stopPropagation();
      evt.preventDefault();
    }
  }, [handleSearchResultClicked, searchResults, selectedSearchResultIndex]);
  var handleKeyUp = (0, _react.useCallback)(function (evt) {
    var highlightedIndex = selectedSearchResultIndex;
    var upKey = evt.keyCode === 38;
    var downKey = evt.keyCode === 40;
    var escapeKey = evt.keyCode === 27; // Search results should be 1 longer for if the last option is the "Not Found" option

    var searchResultsLength = searchResults.length - (allowNotFound ? 0 : 1);

    if (escapeKey) {
      highlightedIndex = -1;
      setShowSearchResults(false);
    } else if (upKey && selectedSearchResultIndex >= 0) {
      var selectedSearchResult;

      do {
        highlightedIndex--;
        selectedSearchResult = searchResults[highlightedIndex];
      } while (selectedSearchResult && selectedSearchResult.isSeparator);
    } else if (downKey && selectedSearchResultIndex < searchResultsLength) {
      var _selectedSearchResult;

      do {
        highlightedIndex++;
        _selectedSearchResult = searchResults[highlightedIndex];
      } while (_selectedSearchResult && _selectedSearchResult.isSeparator);
    }

    setSelectedSearchResultIndex(highlightedIndex);
  }, [allowNotFound, searchResults, selectedSearchResultIndex]);
  /**
   * In the handlers, `searchResults` is outdated so we need to check it in the render.
   * Make an exception to show search results regardless if there are any for `allowNotFound`
   */

  var shouldShowSearchResults = showSearchResults && (!!searchResults.length || allowNotFound);
  var showNotFoundItem = allowNotFound && (!showNotFoundOnlyOnNoResults || showNotFoundOnlyOnNoResults && !searchResults.length);
  return /*#__PURE__*/_react["default"].createElement(SeachInputContainer, _extends({
    stacked: "column",
    onKeyUp: handleKeyUp,
    onKeyDown: handleKeyDown,
    spacing: spacing,
    grow: grow,
    shrink: shrink,
    basis: basis,
    className: className,
    "data-cy": dataCy,
    "data-qa": dataQa,
    id: id
  }, (0, _lodash.omit)(props, _aria.INPUT_ROLE_ARIA_PROPS)), /*#__PURE__*/_react["default"].createElement(_textInput.TextInput, _extends({
    name: name,
    label: label,
    type: "search",
    onChange: handleChange,
    value: searchInput,
    placeholder: placeholder,
    focusOnMount: focusOnMount,
    onBlur: handleSearchInputBlurred,
    onFocus: handleSearchInputFocused,
    error: error,
    success: success,
    description: description,
    clearButtonLabel: clearLabel,
    onClear: onClear,
    labelStyle: labelStyle
  }, (0, _lodash.pick)(props, _aria.INPUT_ROLE_ARIA_PROPS), {
    "aria-autocomplete": "list",
    "aria-expanded": shouldShowSearchResults,
    "aria-owns": resultsListId,
    role: "combobox",
    autoComplete: "off",
    autoCapitalize: "none",
    spellCheck: false
  })), /*#__PURE__*/_react["default"].createElement(_components.SearchResultsWrapper, {
    isVisible: shouldShowSearchResults,
    role: "listbox",
    id: resultsListId,
    spacing: "mt1"
  }, searchResults.map(function (result, i) {
    return result.isSeparator ? /*#__PURE__*/_react["default"].createElement(_components.SearchResultSeparator, {
      role: "separator",
      key: result.id
    }, result.text) : /*#__PURE__*/_react["default"].createElement(_components.ClickableSearchResult, {
      type: "button",
      role: "option",
      key: result.id,
      onClick: function onClick() {
        return handleSearchResultClicked(result.id, result.text);
      },
      "aria-selected": selectedSearchResultIndex === i,
      id: "opt-".concat(resultsListId, "-").concat(i)
    }, renderItem ? renderItem(_objectSpread(_objectSpread({}, result), {}, {
      selected: selectedSearchResultIndex === i
    })) : /*#__PURE__*/_react["default"].createElement(_components.DefaultSearchResult, {
      matchedValue: searchInput,
      isFirst: i === 0,
      isSelected: selectedSearchResultIndex === i,
      text: result.text
    }));
  }), showNotFoundItem && !renderNotFoundItem && /*#__PURE__*/_react["default"].createElement(NotFoundItem, {
    onClick: function onClick() {
      return handleSearchResultClicked();
    },
    isSelected: selectedSearchResultIndex === searchResults.length,
    bold: false,
    isFirst: searchResults.length === 0,
    text: notFoundText
  }), showNotFoundItem && renderNotFoundItem && renderNotFoundItem()));
};

exports.SearchInput = SearchInput;
SearchInput.displayName = 'SearchInput';