"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
exports.__esModule = true;
exports["default"] = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _react = _interopRequireWildcard(require("react"));
var _InputWithOptions = _interopRequireDefault(require("../InputWithOptions"));
var _wixUiIconsCommon = require("@wix/wix-ui-icons-common");
var _StringUtils = require("../utils/StringUtils");
var _SearchSt = require("./Search.st.css.js");
var _Input = _interopRequireDefault(require("../Input/Input"));
var _WixStyleReactDefaultsOverrideProvider = require("../WixStyleReactDefaultsOverrideProvider");
var _IconThemeContext = require("../WixDesignSystemIconThemeProvider/IconThemeContext");
var _excluded = ["defaultValue", "dataHook", "expandWidth", "highlight"];
var _jsxFileName = "/home/builduser/work/57e038ea7326c1ec/packages/wix-design-system/dist/cjs/Search/Search.jsx";
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
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), !0).forEach(function (r) { (0, _defineProperty2["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; }
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2["default"])(o), (0, _possibleConstructorReturn2["default"])(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2["default"])(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
// because lodash debounce is not compatible with jest timeout mocks
function debounce(fn, wait) {
  var timeout;
  return function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    var context = this;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      return fn.apply(context, args);
    }, wait);
  };
}

/**
 * Search component with suggestions based on input value listed in dropdown
 */
var Search = /*#__PURE__*/function (_Component) {
  function Search(props) {
    var _this;
    (0, _classCallCheck2["default"])(this, Search);
    _this = _callSuper(this, Search, [props]);
    _this.searchInput = /*#__PURE__*/_react["default"].createRef();
    _this.contentElementRef = /*#__PURE__*/_react["default"].createRef();
    _this._onContentTransitionEnd = function () {
      _this.props.onExpandTransitionEnd == null || _this.props.onExpandTransitionEnd(_this.state.collapsed);
    };
    _this._onContentTransitionStart = function () {
      _this.props.onExpandTransitionStart == null || _this.props.onExpandTransitionStart(_this.state.collapsed);
    };
    /**
     * Creates an onChange debounced function
     */
    _this._createDebouncedOnChange = function () {
      var _this$props = _this.props,
        debounceMs = _this$props.debounceMs,
        onChange = _this$props.onChange;
      return debounceMs > 0 ? debounce(onChange, debounceMs) : onChange;
    };
    _this._getIsControlled = function () {
      return 'value' in _this.props && 'onChange' in _this.props;
    };
    _this._getFilteredOptions = function () {
      var _this$props2 = _this.props,
        options = _this$props2.options,
        predicate = _this$props2.predicate;
      var searchText = _this._currentValue();
      if (!searchText || !searchText.length) {
        return options;
      }
      var filterFn = predicate || _this._stringFilter;
      return options.filter(filterFn);
    };
    _this._stringFilter = function (option) {
      var searchText = _this._currentValue();
      return _StringUtils.StringUtils.includesCaseInsensitive(option.value, searchText.trim());
    };
    _this._onChange = function (e) {
      e.persist();
      _this.setState({
        inputValue: e.target.value
      }, function () {
        _this._onChangeHandler(e);
      });
    };
    _this._onClear = function (event) {
      var expandable = _this.props.expandable;
      var collapsed = _this.state.collapsed;
      var stateChanges = {};
      if (!_this._getIsControlled()) {
        stateChanges.inputValue = '';
      }
      if (expandable && !collapsed && _this._currentValue === '') {
        stateChanges.collapsed = true;
        _this.searchInput.current && _this.searchInput.current.blur();
      }
      _this.setState(stateChanges, function () {
        _this._onClearHandler(event);
      });
    };
    _this._onClearHandler = function (event) {
      var onClear = _this.props.onClear;
      if (onClear) onClear(event);
    };
    _this._currentValue = function () {
      return _this.state.inputValue;
    };
    _this._onFocus = function (event) {
      var onFocus = _this.props.onFocus;
      if (_this.state.collapsed && _this.props.expandable) {
        _this.setState({
          collapsed: false
        });
      }
      onFocus && onFocus(event);
    };
    _this._onBlur = /*#__PURE__*/function () {
      var _ref = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee(event) {
        var onBlur, value;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              onBlur = _this.props.onBlur;
              _context.t0 = onBlur;
              if (!_context.t0) {
                _context.next = 5;
                break;
              }
              _context.next = 5;
              return onBlur(event);
            case 5:
              if (!_this.state.collapsed && _this.props.expandable) {
                value = _this._currentValue();
                if (value === '') {
                  _this.setState({
                    collapsed: true
                  });
                }
              }
            case 6:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }();
    _this._onWrapperClick = function () {
      if (!_this.props.expandable || _this.props.expandable && _this.state.collapsed) {
        _this.searchInput.current && _this.searchInput.current.focus();
      }
    };
    _this._onWrapperMouseDown = function (e) {
      // We need to capture mouse down and prevent it's event if the input
      // is already open
      if (_this.props.expandable && !_this.state.collapsed) {
        var value = _this._currentValue();
        if (value === '') {
          e.preventDefault();
        }
      }
    };
    /**
     * Sets focus on the input element
     */
    _this.focus = function () {
      _this.searchInput.current && _this.searchInput.current.focus();
    };
    /**
     * Removes focus on the input element
     */
    _this.blur = function () {
      _this.searchInput.current && _this.searchInput.current.blur();
    };
    /**
     * Clears the input.
     *
     * @param event
     */
    _this.clear = function (event) {
      _this.searchInput.current && _this.searchInput.current.clear(event);
    };
    var initialValue = _this._getIsControlled() ? props.value : props.defaultValue || '';
    _this._onChangeHandler = _this._createDebouncedOnChange();
    _this.state = {
      inputValue: initialValue,
      collapsed: props.expandable && !initialValue && !props.autoFocus
    };
    return _this;
  }
  (0, _inherits2["default"])(Search, _Component);
  return (0, _createClass2["default"])(Search, [{
    key: "_addContentElementListeners",
    value: function _addContentElementListeners() {
      var contentElement = this.contentElementRef.current;
      if (!contentElement) {
        return;
      }
      contentElement.addEventListener('transitionstart', this._onContentTransitionStart);
      contentElement.addEventListener('transitionend', this._onContentTransitionEnd);
    }
  }, {
    key: "_removeContentElementListeners",
    value: function _removeContentElementListeners() {
      var contentElement = this.contentElementRef.current;
      if (!contentElement) {
        return;
      }
      contentElement.removeEventListener('transitionstart', this._onContentTransitionStart);
      contentElement.removeEventListener('transitionend', this._onContentTransitionEnd);
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this._addContentElementListeners();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this._removeContentElementListeners();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var _this$props3 = this.props,
        value = _this$props3.value,
        expandable = _this$props3.expandable;
      if (prevProps.value !== value) {
        // Collapse the expandable input when the input has no focus & no value in it.
        var collapsed = expandable && this.searchInput.current && !this.searchInput.current._focused && prevProps.value && !value ? true : this.props.collapsed;
        this.setState({
          inputValue: value,
          collapsed: collapsed
        });
      }
      if (prevProps.debounceMs !== this.props.debounceMs || prevProps.onChange !== this.props.onChange) {
        this._onChangeHandler = this._createDebouncedOnChange();
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var inputPropsDefaults = this.context.input;
      var _this$props4 = this.props,
        defaultValue = _this$props4.defaultValue,
        dataHook = _this$props4.dataHook,
        expandWidth = _this$props4.expandWidth,
        highlight = _this$props4.highlight,
        restProps = (0, _objectWithoutProperties2["default"])(_this$props4, _excluded);
      var expandable = restProps.expandable,
        _restProps$size = restProps.size,
        size = _restProps$size === void 0 ? inputPropsDefaults.size : _restProps$size;
      var _this$state = this.state,
        collapsed = _this$state.collapsed,
        inputValue = _this$state.inputValue;
      var contentStyle = expandable && !collapsed ? {
        width: expandWidth
      } : undefined;
      return /*#__PURE__*/_react["default"].createElement(_IconThemeContext.IconThemeContext.Consumer, {
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 281,
          columnNumber: 7
        }
      }, function (_ref2) {
        var _icons$Search, _icons$Search2;
        var _ref2$icons = _ref2.icons,
          icons = _ref2$icons === void 0 ? {} : _ref2$icons;
        var SearchIcons = {
          Search: ((_icons$Search = icons.Search) == null ? void 0 : _icons$Search.Search) || _wixUiIconsCommon.Search,
          SearchSmall: ((_icons$Search2 = icons.Search) == null ? void 0 : _icons$Search2.SearchSmall) || _wixUiIconsCommon.SearchSmall
        };
        return /*#__PURE__*/_react["default"].createElement("div", {
          "data-hook": dataHook,
          className: (0, _SearchSt.st)(_SearchSt.classes.root, {
            expandable: expandable,
            collapsed: expandable && collapsed,
            expandDirection: restProps.expandDirection,
            size: size,
            border: restProps.border
          }),
          onClick: _this2._onWrapperClick,
          onMouseDown: _this2._onWrapperMouseDown,
          "data-expandable": expandable || null,
          "data-collapsed": expandable && collapsed || null,
          __self: _this2,
          __source: {
            fileName: _jsxFileName,
            lineNumber: 289,
            columnNumber: 13
          }
        }, /*#__PURE__*/_react["default"].createElement("div", {
          ref: _this2.contentElementRef,
          "data-hook": "search-content",
          className: _SearchSt.classes.content,
          style: contentStyle,
          __self: _this2,
          __source: {
            fileName: _jsxFileName,
            lineNumber: 303,
            columnNumber: 15
          }
        }, /*#__PURE__*/_react["default"].createElement(_InputWithOptions["default"], (0, _extends2["default"])({}, restProps, {
          showDrawerOnMobile: false,
          value: inputValue,
          ref: _this2.searchInput,
          prefix: /*#__PURE__*/_react["default"].createElement(_Input["default"].IconAffix, {
            __self: _this2,
            __source: {
              fileName: _jsxFileName,
              lineNumber: 315,
              columnNumber: 21
            }
          }, size === 'small' ? /*#__PURE__*/_react["default"].createElement(SearchIcons.SearchSmall, {
            __self: _this2,
            __source: {
              fileName: _jsxFileName,
              lineNumber: 317,
              columnNumber: 25
            }
          }) : /*#__PURE__*/_react["default"].createElement(SearchIcons.Search, {
            __self: _this2,
            __source: {
              fileName: _jsxFileName,
              lineNumber: 319,
              columnNumber: 25
            }
          })),
          dataHook: "search-inputwithoptions",
          menuArrow: false,
          closeOnSelect: true,
          options: _this2._getFilteredOptions(),
          customDropdownContent: !_this2._getFilteredOptions().length && (_this2.props.renderEmptyState == null ? void 0 : _this2.props.renderEmptyState(inputValue)),
          onClear: restProps.clearButton ? _this2._onClear : undefined,
          onChange: _this2._onChange,
          onFocus: _this2._onFocus,
          onBlur: _this2._onBlur,
          highlight: highlight,
          __self: _this2,
          __source: {
            fileName: _jsxFileName,
            lineNumber: 309,
            columnNumber: 17
          }
        }))));
      });
    }
  }]);
}(_react.Component);
Search.contextType = _WixStyleReactDefaultsOverrideProvider.WixStyleReactDefaultsOverrideContext;
Search.displayName = 'Search';
Search.defaultProps = _objectSpread(_objectSpread({}, _InputWithOptions["default"].defaultProps), {}, {
  clearButton: true,
  placeholder: 'Search',
  expandable: false,
  expandWidth: '100%',
  expandDirection: 'right',
  debounceMs: 0,
  onChange: function onChange() {},
  highlight: true,
  border: 'round'
});
var _default = exports["default"] = Search;