"use strict";

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

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

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

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

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

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

var _Pagination = _interopRequireDefault(require("../Pagination"));

var _Title = _interopRequireDefault(require("../../../../components/Title"));

/* istanbul ignore file */
// Components
// 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",
  "SearchResults": "_2BQNj-SearchResults",
  "SearchResults_empty": "_3FpEF-SearchResults_empty",
  "SearchResults-ScrollTo": "_2lHjD-SearchResults-ScrollTo",
  "SearchResults-Result": "_1EW7w-SearchResults-Result",
  "SearchResults-Result-Project": "Wv0xt-SearchResults-Result-Project",
  "SearchResults-Result-Link": "TX38L-SearchResults-Result-Link",
  "SearchResults-Result-Header": "_3mq_e-SearchResults-Result-Header",
  "SearchResults-Result-Excerpt": "_1o71G-SearchResults-Result-Excerpt",
  "SearchResults-Result-Title": "_2HKq9-SearchResults-Result-Title",
  "SearchResults-Method": "_9dBts-SearchResults-Method",
  "SearchResults-Method_get": "_2Ggf5-SearchResults-Method_get",
  "SearchResults-Method_put": "OyXe5-SearchResults-Method_put",
  "SearchResults-Method_post": "_32wY--SearchResults-Method_post",
  "SearchResults-Method_delete": "SCV0_-SearchResults-Method_delete"
}; // custom results

var Results = (0, _reactInstantsearchDom.connectStateResults)(function (_ref) {
  var searchState = _ref.searchState,
      searchResults = _ref.searchResults,
      children = _ref.children;

  // welcome state
  if (searchState && !searchState.query) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: [classes.SearchResults, classes.SearchResults_empty].join(' ')
    }, /*#__PURE__*/_react["default"].createElement("i", {
      className: "icon icon-search"
    }), /*#__PURE__*/_react["default"].createElement(_Title["default"], {
      level: 6
    }, "Start typing to search\u2026"));
  } // empty state (no results)


  if (searchResults && searchResults.nbHits === 0) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: [classes.SearchResults, classes.SearchResults_empty].join(' ')
    }, /*#__PURE__*/_react["default"].createElement(_Title["default"], {
      level: 6
    }, "Try a different search."), /*#__PURE__*/_react["default"].createElement("div", null, "No results for \u2018", searchState.query, "\u2019."));
  }

  return children;
});

var determineResultDisplay = function determineResultDisplay(hit) {
  var snippet = hit._snippetResult;
  var fullMatch = Object.entries(snippet).sort(function (a, b) {
    var _a = (0, _slicedToArray2["default"])(a, 2),
        aVal = _a[1];

    var _b = (0, _slicedToArray2["default"])(b, 2),
        bVal = _b[1];

    if (aVal.matchLevel === 'full' && (bVal.matchLevel === 'partial' || bVal.matchLevel === 'none')) return -1;else if (aVal.matchLevel === bVal.matchLevel) return 0;
    return 1;
  });
  return fullMatch[0][0];
};

var handleArrowFocus = function handleArrowFocus(e) {
  var key = e.key,
      target = e.target;
  var hitList = target.querySelector('.SearchResults-list') || target.parentElement;
  var focusAt = document.querySelector('a:focus');
  var focusTo;
  if (!focusAt) focusTo = hitList.firstElementChild.focus();else if (key && (key === 'ArrowUp' || key === 'ArrowDown')) {
    if (key === 'ArrowUp') focusTo = focusAt.previousElementSibling || hitList.lastElementChild;
    if (key === 'ArrowDown') focusTo = focusAt.nextElementSibling || hitList.firstElementChild;
    e.preventDefault();
  }
  if (focusTo) focusTo.focus();
};

var createCustomHitsComponent = function createCustomHitsComponent(subdomains, onReload, UrlManager) {
  var Hits = function Hits(_ref2) {
    var hits = _ref2.hits;

    // if there are no results within the current filters
    if (hits.length === 0) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: [classes.SearchResults, classes.SearchResults_empty].join(' ')
      }, /*#__PURE__*/_react["default"].createElement(_Title["default"], {
        level: 6
      }, "No results."), /*#__PURE__*/_react["default"].createElement("div", null, "Try a different filter or tab."));
    } // if there are results


    if (typeof onReload === 'function') onReload(); // callback

    var results = hits.map(function (hit) {
      // Build hitUrl
      var hitUrl;

      if (typeof window !== 'undefined' && window.location.hash) {
        hitUrl = UrlManager.remove('hash', window.location.href);
      }

      hitUrl = UrlManager.upsert('slugs', hit.internalLink.split('/'), hitUrl); // Enterprise only: Populate child if project has parent & hit is from a different child project

      if (UrlManager.options.parent && subdomains[hit.project] !== UrlManager.options.project.subdomain) {
        hitUrl = UrlManager.upsert('child', subdomains[hit.project], hitUrl); // Remove version if hit is from a different child project

        if (UrlManager.options.version) {
          hitUrl = UrlManager.remove('version', hitUrl);
        }
      }

      var attribute = determineResultDisplay(hit);
      var title = hit.isReference && hit.method ? "(".concat(hit.method.toUpperCase(), ") ").concat(hit.title) : hit.title;
      return /*#__PURE__*/_react["default"].createElement("a", {
        key: hit.objectID,
        className: classes['SearchResults-Result'],
        href: hitUrl,
        tabIndex: 0,
        target: "_self"
      }, /*#__PURE__*/_react["default"].createElement("header", {
        className: classes['SearchResults-Result-Header'],
        title: title
      }, hit.isReference && /*#__PURE__*/_react["default"].createElement("span", {
        className: [classes['SearchResults-Method'], classes["SearchResults-Method_".concat(hit.method)]].join(' ')
      }, hit.method), /*#__PURE__*/_react["default"].createElement("span", {
        className: classes['SearchResults-Result-Title']
      }, hit.title, Object.keys(subdomains).length <= 1 || /*#__PURE__*/_react["default"].createElement("span", {
        className: classes['SearchResults-Result-Project']
      }, hit.subdomain)), hit.link_url && /*#__PURE__*/_react["default"].createElement("small", {
        className: classes['SearchResults-Result-Link']
      }, /*#__PURE__*/_react["default"].createElement("i", {
        className: "fa fa-external-link-alt"
      }))), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes['SearchResults-Result-Excerpt'],
        title: title
      }, /*#__PURE__*/_react["default"].createElement(_reactInstantsearchDom.Snippet, {
        attribute: attribute,
        hit: hit
      })));
    });
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: [classes.SearchResults, classes.SearchResults_default].join(' ')
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: classes['SearchResults-ScrollTo']
    }), /*#__PURE__*/_react["default"].createElement("div", {
      className: "SearchResults-list",
      onKeyDownCapture: function onKeyDownCapture() {
        if (typeof window !== 'undefined') handleArrowFocus();
      }
    }, results), /*#__PURE__*/_react["default"].createElement(_Pagination["default"], null));
  };

  Hits.propTypes = {
    hits: _propTypes["default"].array
  };
  return Hits;
};

var SearchResults = function SearchResults(_ref3) {
  var subdomains = _ref3.subdomains,
      onReload = _ref3.onReload,
      UrlManager = _ref3.UrlManager;
  var Hits = createCustomHitsComponent(subdomains, onReload, UrlManager);
  var CustomHits = (0, _reactInstantsearchDom.connectHits)(Hits);
  return /*#__PURE__*/_react["default"].createElement(Results, null, /*#__PURE__*/_react["default"].createElement(CustomHits, {
    hitComponent: Hits
  }));
};

SearchResults.propTypes = {
  onReload: _propTypes["default"].func,
  subdomains: _propTypes["default"].object,
  tab: _propTypes["default"].string,
  UrlManager: _propTypes["default"].object
};
SearchResults.defaultProps = {
  subdomains: {}
};
var _default = SearchResults;
exports["default"] = _default;