"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _lite = _interopRequireDefault(require("algoliasearch/lite"));

var _find = _interopRequireDefault(require("lodash/find"));

var _pick = _interopRequireDefault(require("lodash/pick"));

var _propTypes = _interopRequireDefault(require("prop-types"));

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

var _reactInstantsearchDom = require("react-instantsearch-dom");

var _RefinementList = _interopRequireDefault(require("./components/RefinementList"));

var _SearchBox = _interopRequireDefault(require("./components/SearchBox"));

var _SearchResults = _interopRequireDefault(require("./components/SearchResults"));

var _SearchTabs = _interopRequireDefault(require("./components/SearchTabs"));

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) { (0, _defineProperty2["default"])(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

// Style
var classes = {};
/* istanbul ignore next */

if (typeof window !== 'undefined' || typeof _COMPILED_ === 'undefined') classes = {
  "slate": "#384248",
  "blue": "#118CFD",
  "green": "#12CA93",
  "red": "#E95F6A",
  "yellow": "#F7C543",
  "purple": "#8470BE",
  "graphite": "#4F5A66",
  "shale": "#939EAE",
  "chalk": "#c6cbd3",
  "ivory": "#F0F0F0",
  "lightGray": "#F8F8F8",
  "white": "#FFF",
  "AlgoliaSearch": "_1SYbw-AlgoliaSearch",
  "AlgoliaSearch-Col": "_7j_Pw-AlgoliaSearch-Col"
};

var AlgoliaSearch = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(AlgoliaSearch, _React$Component);

  var _super = _createSuper(AlgoliaSearch);

  function AlgoliaSearch(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, AlgoliaSearch);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleRefinementBlur", function (e) {
      var searchBox = document.querySelector(".".concat(classes.AlgoliaSearch, " input[type=search]"));
      searchBox.focus();
      searchBox.select();
      e.preventDefault();
      e.stopPropagation();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "enableModuleMap", function (metadata) {
      return (metadata || []).reduce(function (obj, _ref) {
        var name = _ref.name,
            subdomain = _ref.subdomain,
            modules = _ref.modules;
        obj[name || subdomain] = modules;
        return obj;
      }, {});
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setTabFilters", function () {
      var filters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var enabledModules = arguments.length > 1 ? arguments[1] : undefined;
      var initiaLoad = arguments.length > 2 ? arguments[2] : undefined;
      var meta = enabledModules || _this.state.enabledModules;
      var selectedModules = filters.length ? (0, _pick["default"])(meta, filters) : meta;
      var values = Object.values(selectedModules);
      var modules = Object.values(values).reduce(function (obj, child) {
        Object.keys(child).forEach(function (key) {
          if (obj[key]) obj[key] = !!(obj[key] + child[key]);else obj[key] = !!child[key];
        });
        return obj;
      }, {});
      var tabFilters = Object.entries(modules).filter(function (_ref2) {
        var _ref3 = (0, _slicedToArray2["default"])(_ref2, 2),
            v = _ref3[1];

        return v;
      }).map(function (_ref4) {
        var _ref5 = (0, _slicedToArray2["default"])(_ref4, 1),
            k = _ref5[0];

        return k;
      });
      if (!initiaLoad) _this.setState({
        tabFilters: tabFilters
      });
      return tabFilters;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleResultsReload", function () {
      var focused = document.activeElement;
      var search = document.querySelector(".".concat(classes.AlgoliaSearch));
      var searchHits = search.querySelector('.SearchResults-list');
      var searchBox = search.querySelector('input[type=search]');
      setTimeout(function () {
        if (searchHits) {
          var elem = searchHits.firstElementChild;
          if (focused.matches('[focus-hit]')) elem = searchHits[focused.attributes['focus-hit'].value];
          if (elem && searchBox !== focused) elem.focus();
        }
      }, 100);
    });

    var _enabledModules = _this.enableModuleMap(props.projectsMeta);

    _this.state = {
      activeTab: 'All',
      filters: '',
      refinementListOpen: true,
      tabs: {
        All: {
          filters: ''
        },
        Guides: {
          filters: 'indexName:Page AND isReference:false'
        },
        Tutorials: {
          filters: 'indexName:Tutorial'
        },
        Reference: {
          filters: 'indexName:Page AND isReference:true'
        },
        Changelog: {
          filters: 'indexName:Blog'
        },
        Discussions: {
          filters: 'indexName:Discuss'
        },
        Pages: {
          filters: 'indexName:CustomPage'
        }
      },
      tabFilters: _this.setTabFilters([], _enabledModules, true),
      enabledModules: _enabledModules,
      initializeAlgolia: 'PROXY'
    };
    _this.handleTabChange = _this.handleTabChange.bind((0, _assertThisInitialized2["default"])(_this));
    _this.handleFocusIn = _this.handleFocusIn.bind((0, _assertThisInitialized2["default"])(_this));
    _this.rootNode = /*#__PURE__*/_react["default"].createRef();

    if (typeof window !== 'undefined' && 'matchMedia' in window) {
      _this.MQ = window.matchMedia('(max-width: 700px)');

      _this.MQ.addListener(function () {
        return _this.setState({
          refinementListOpen: !_this.MQ.matches
        });
      });
    }

    return _this;
  }
  /* istanbul ignore next */
  // eslint-disable-next-line class-methods-use-this


  (0, _createClass2["default"])(AlgoliaSearch, [{
    key: "handleKeyboard",
    value: function handleKeyboard(e) {
      // keyboard event handling should fail silently
      try {
        var key = e.key;
        var search = document.querySelector(".".concat(classes.AlgoliaSearch));
        var searchBox = search.querySelector('input[type=search]');
        var searchHits = search.querySelector('.SearchResults-list');
        var searchPage = search.querySelector('footer');
        var focused = document.activeElement;

        if (searchBox === focused) {
          if (key === 'Tab' && e.shiftKey) {
            searchBox.select();
            e.preventDefault();
          } else if (key === 'Tab' || key === 'ArrowDown' || key === 'Enter' || key === 'ArrowUp') {
            var firstlastChild = key === 'ArrowUp' ? 'lastElementChild' : 'firstElementChild';
            searchHits[firstlastChild].focus();
            e.preventDefault();
          }
        } else if (!(searchPage && searchPage.matches(':focus-within')) && key === 'Tab' && e.shiftKey) {
          searchBox.focus();
          e.preventDefault();
        } else if (searchHits && !searchHits.matches(':focus-within') && (key === 'ArrowDown' || key === 'ArrowUp')) {
          searchHits[key === 'ArrowUp' ? 'lastElementChild' : 'firstElementChild'].focus();
          e.stopPropagation();
          e.preventDefault();
        }
      } catch (error) {
        // eslint-disable-next-line no-console
        console.warn(error);
      }
    }
  }, {
    key: "handleTabChange",
    value: function handleTabChange(tab) {
      /* handle keyboard events
       */
      if (typeof window !== 'undefined' && (0, _typeof2["default"])(tab) === 'object') {
        this.handleKeyboard(tab);
        return;
      }
      /* handle click events
       */


      if (tab in this.state.tabs) {
        this.setState(_objectSpread({
          activeTab: tab
        }, this.state.tabs[tab]));
      }
    }
  }, {
    key: "handleFocusIn",
    value: function handleFocusIn() {
      if (this.state.initializeAlgolia === 'PROXY') this.setState({
        initializeAlgolia: 'LIVE'
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$state = this.state,
          activeTab = _this$state.activeTab,
          filters = _this$state.filters;
      var _this$props = this.props,
          appId = _this$props.appId,
          currentProject = _this$props.currentProject,
          defaultRefinement = _this$props.defaultRefinement,
          indexName = _this$props.indexName,
          searchApiKey = _this$props.searchApiKey,
          showRefinementList = _this$props.showRefinementList,
          style = _this$props.style,
          _this$props$projectsM = _this$props.projectsMeta,
          projectsMeta = _this$props$projectsM === void 0 ? false : _this$props$projectsM,
          UrlManager = _this$props.UrlManager;
      /**
       * Wrap the Algolia client in a conditional, so we don't hit their
       * API on empty searches to limit unnecessary requests. More here:
       * https://algolia.com/doc/guides/building-search-ui/going-further/conditional-requests/react
       */

      var algoliaClient = {
        LIVE: (0, _lite["default"])(appId, searchApiKey),
        PROXY: {
          search: function search(requests) {
            return Promise.resolve({
              results: requests.map(function () {
                return {
                  hits: [],
                  nbHits: 0,
                  nbPages: 0,
                  page: 0,
                  processingTimeMS: 0
                };
              })
            });
          }
        }
      };
      /* istanbul ignore next */

      var subdomains = !projectsMeta ? undefined : projectsMeta.reduce(function (all, _ref6) {
        var id = _ref6.id,
            subdomain = _ref6.subdomain;
        all[id] = subdomain;
        return all;
      }, {});
      var tabRename = !projectsMeta ? {} : (0, _find["default"])(projectsMeta, {
        id: currentProject
      });
      return /*#__PURE__*/_react["default"].createElement(_reactInstantsearchDom.InstantSearch, {
        indexName: indexName,
        searchClient: algoliaClient[this.state.initializeAlgolia]
      }, /*#__PURE__*/_react["default"].createElement(_reactInstantsearchDom.Configure, {
        filters: filters
      }), /*#__PURE__*/_react["default"].createElement("div", {
        ref: this.rootNode,
        className: classes.AlgoliaSearch,
        onFocus: this.handleFocusIn,
        onKeyDown: this.handleTabChange,
        role: "tabpanel",
        style: style,
        tabIndex: 0
      }, /*#__PURE__*/_react["default"].createElement("div", {
        className: classes['AlgoliaSearch-Col']
      }, /*#__PURE__*/_react["default"].createElement(_SearchBox["default"], null), /*#__PURE__*/_react["default"].createElement(_SearchTabs["default"], {
        activeTab: activeTab,
        onTabChange: this.handleTabChange,
        tabFilters: this.state.tabFilters,
        tabNames: tabRename ? tabRename.nav_names : {}
      }), /*#__PURE__*/_react["default"].createElement(_SearchResults["default"], {
        onReload: function onReload() {
          if (typeof window !== 'undefined') _this2.handleResultsReload();
        },
        subdomains: subdomains,
        tab: "Guides",
        UrlManager: UrlManager
      })), showRefinementList && /*#__PURE__*/_react["default"].createElement(_RefinementList["default"], {
        attribute: "subdomain",
        defaultRefinement: defaultRefinement,
        isOpen: this.state.refinementListOpen,
        onBlur: function onBlur(e) {
          if (typeof window !== 'undefined') _this2.handleRefinementBlur(e);
        },
        onRefine: this.setTabFilters,
        showMore: true
      })));
    }
  }]);
  return AlgoliaSearch;
}(_react["default"].Component);

AlgoliaSearch.propTypes = {
  appId: _propTypes["default"].string.isRequired,
  currentProject: _propTypes["default"].string,
  defaultRefinement: _propTypes["default"].array,
  indexName: _propTypes["default"].string.isRequired,
  projectsMeta: _propTypes["default"].array,
  searchApiKey: _propTypes["default"].string.isRequired,
  showRefinementList: _propTypes["default"].any,
  style: _propTypes["default"].oneOfType([_propTypes["default"].object, _propTypes["default"].string]),
  UrlManager: _propTypes["default"].shape({
    options: _propTypes["default"].object,
    remove: _propTypes["default"].func.isRequired,
    upsert: _propTypes["default"].func.isRequired
  }).isRequired
};
AlgoliaSearch.defaultProps = {
  showRefinementList: true
};
var _default = AlgoliaSearch;
exports["default"] = _default;