"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiSelectableTemplateSitewide = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../../services");
var _keys = require("../../../services/keys");
var _i18n = require("../../i18n");
var _loading = require("../../loading");
var _selectable = require("../selectable");
var _selectable_message = require("../selectable_message");
var _selectable_template_sitewide_option = require("./selectable_template_sitewide_option");
var _selectable_template_sitewide = require("./selectable_template_sitewide.styles");
var _selectable_template_sitewide_popover = require("./selectable_template_sitewide_popover");
var _react2 = require("@emotion/react");
var _excluded = ["children", "className", "options", "popoverProps", "popoverTitle", "popoverFooter", "searchProps", "listProps", "isLoading", "popoverButton", "popoverButtonBreakpoints", "colorModes"],
  _excluded2 = ["closePopover", "panelRef", "width"];
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
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; }
var EuiSelectableTemplateSitewide = exports.EuiSelectableTemplateSitewide = function EuiSelectableTemplateSitewide(_ref) {
  var _colorModes$search, _colorModes$popover;
  var children = _ref.children,
    className = _ref.className,
    options = _ref.options,
    popoverProps = _ref.popoverProps,
    popoverTitle = _ref.popoverTitle,
    popoverFooter = _ref.popoverFooter,
    searchProps = _ref.searchProps,
    listProps = _ref.listProps,
    isLoading = _ref.isLoading,
    popoverButton = _ref.popoverButton,
    popoverButtonBreakpoints = _ref.popoverButtonBreakpoints,
    _ref$colorModes = _ref.colorModes,
    colorModes = _ref$colorModes === void 0 ? {
      search: 'default',
      popover: 'default'
    } : _ref$colorModes,
    rest = (0, _objectWithoutProperties2.default)(_ref, _excluded);
  var _useEuiTheme = (0, _services.useEuiTheme)(),
    colorMode = _useEuiTheme.colorMode;
  var _useContext = (0, _react.useContext)(_services.EuiNestedThemeContext),
    hasDifferentColorFromGlobalTheme = _useContext.hasDifferentColorFromGlobalTheme;
  var _searchColorMode = colorModes === null || colorModes === void 0 || (_colorModes$search = colorModes.search) === null || _colorModes$search === void 0 ? void 0 : _colorModes$search.toLowerCase();
  var _popoverColorMode = colorModes === null || colorModes === void 0 || (_colorModes$popover = colorModes.popover) === null || _colorModes$popover === void 0 ? void 0 : _colorModes$popover.toLowerCase();
  var searchColorMode = (0, _react.useMemo)(function () {
    var isStaticTheme = [_services.COLOR_MODES_STANDARD.light.toLowerCase(), _services.COLOR_MODES_STANDARD.dark.toLowerCase()].includes(_searchColorMode);
    return isStaticTheme ? _searchColorMode : _searchColorMode === 'inverse' ? colorMode === _services.COLOR_MODES_STANDARD.dark ? _services.COLOR_MODES_STANDARD.light : _services.COLOR_MODES_STANDARD.dark : colorMode;
  }, [colorMode, _searchColorMode]);
  var popoverColorMode = (0, _react.useMemo)(function () {
    var isStaticTheme = [_services.COLOR_MODES_STANDARD.light.toLowerCase(), _services.COLOR_MODES_STANDARD.dark.toLowerCase()].includes(_popoverColorMode);
    var inverseColorMode = colorMode === _services.COLOR_MODES_STANDARD.dark ? _services.COLOR_MODES_STANDARD.light : _services.COLOR_MODES_STANDARD.dark;
    var globalColorMode = hasDifferentColorFromGlobalTheme ? colorMode === _services.COLOR_MODES_STANDARD.dark ? _services.COLOR_MODES_STANDARD.light : _services.COLOR_MODES_STANDARD.dark : colorMode;
    return isStaticTheme ? _popoverColorMode : _popoverColorMode === 'inverse' ? inverseColorMode : _popoverColorMode === 'global' ? globalColorMode : colorMode;
  }, [hasDifferentColorFromGlobalTheme, colorMode, _popoverColorMode]);

  /**
   * i18n text
   */
  var _useEuiI18n = (0, _i18n.useEuiI18n)(['euiSelectableTemplateSitewide.searchPlaceholder'], ['Search for anything...']),
    _useEuiI18n2 = (0, _slicedToArray2.default)(_useEuiI18n, 1),
    searchPlaceholder = _useEuiI18n2[0];

  /**
   * Popover helpers
   */
  var _useState = (0, _react.useState)(null),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    popoverRef = _useState2[0],
    setPopoverRef = _useState2[1];
  var _useState3 = (0, _react.useState)(false),
    _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
    popoverIsOpen = _useState4[0],
    setPopoverIsOpen = _useState4[1];
  var _popoverProps = _objectSpread({}, popoverProps),
    _closePopover = _popoverProps.closePopover,
    panelRef = _popoverProps.panelRef,
    width = _popoverProps.width,
    popoverRest = (0, _objectWithoutProperties2.default)(_popoverProps, _excluded2);
  var closePopover = function closePopover() {
    setPopoverIsOpen(false);
    _closePopover && _closePopover();
  };
  var togglePopover = (0, _react.useCallback)(function () {
    setPopoverIsOpen(function (isOpen) {
      return !isOpen;
    });
  }, []);

  // Width applied to the internal div
  var popoverWidth = width || 600;
  var setPanelRef = (0, _services.useCombinedRefs)([setPopoverRef, panelRef]);

  /**
   * Search helpers
   */
  var searchOnFocus = function searchOnFocus(e) {
    var _searchProps$onFocus;
    searchProps === null || searchProps === void 0 || (_searchProps$onFocus = searchProps.onFocus) === null || _searchProps$onFocus === void 0 || _searchProps$onFocus.call(searchProps, e);
    setPopoverIsOpen(true);
  };
  var onSearchInput = function onSearchInput(e) {
    var _searchProps$onInput;
    searchProps === null || searchProps === void 0 || (_searchProps$onInput = searchProps.onInput) === null || _searchProps$onInput === void 0 || _searchProps$onInput.call(searchProps, e);
    setPopoverIsOpen(true);
  };
  var onSearchKeydown = function onSearchKeydown(e) {
    var _searchProps$onKeyDow;
    searchProps === null || searchProps === void 0 || (_searchProps$onKeyDow = searchProps.onKeyDown) === null || _searchProps$onKeyDow === void 0 || _searchProps$onKeyDow.call(searchProps, e);
    if (e.key === _keys.ENTER) {
      setPopoverIsOpen(true);
    }
  };
  var searchOnBlur = function searchOnBlur(e) {
    var _searchProps$onBlur;
    searchProps === null || searchProps === void 0 || (_searchProps$onBlur = searchProps.onBlur) === null || _searchProps$onBlur === void 0 || _searchProps$onBlur.call(searchProps, e);
    if (!(popoverRef !== null && popoverRef !== void 0 && popoverRef.contains(e.relatedTarget))) {
      setPopoverIsOpen(false);
    }
  };

  /**
   * Classes & styles
   */
  var styles = (0, _services.useEuiMemoizedStyles)(_selectable_template_sitewide.euiSelectableTemplateSitewideStyles);
  var classes = (0, _classnames.default)('euiSelectableTemplateSitewide', className);
  var searchClasses = (0, _classnames.default)('euiSelectableTemplateSitewide__search', searchProps && searchProps.className);
  var listClasses = (0, _classnames.default)('euiSelectableTemplateSitewide__list', listProps && listProps.className);

  /**
   * List options
   */
  var formattedOptions = (0, _selectable_template_sitewide_option.euiSelectableTemplateSitewideFormatOptions)(options, styles);
  var loadingMessage = (0, _react2.jsx)(_selectable_message.EuiSelectableMessage, {
    style: {
      minHeight: 300
    }
  }, (0, _react2.jsx)(_loading.EuiLoadingSpinner, {
    size: "l"
  }), (0, _react2.jsx)("br", null), (0, _react2.jsx)("p", null, (0, _react2.jsx)(_i18n.EuiI18n, {
    token: "euiSelectableTemplateSitewide.loadingResults",
    default: "Loading results"
  })));
  var emptyMessage = (0, _react2.jsx)(_selectable_message.EuiSelectableMessage, {
    style: {
      minHeight: 300
    }
  }, (0, _react2.jsx)("p", null, (0, _react2.jsx)(_i18n.EuiI18n, {
    token: "euiSelectableTemplateSitewide.noResults",
    default: "No results available"
  })));

  /**
   * Changes based on showing the `popoverButton` if provided.
   * This will move the search input into the popover
   * and use the passed `popoverButton` as the popover trigger.
   */
  var currentBreakpoint = (0, _services.useCurrentEuiBreakpoint)();
  var canShowPopoverButton = (0, _react.useMemo)(function () {
    if (!popoverButtonBreakpoints) return true;
    if (!currentBreakpoint) return false;
    return popoverButtonBreakpoints.includes(currentBreakpoint);
  }, [currentBreakpoint, popoverButtonBreakpoints]);
  var popoverTrigger = (0, _react.useMemo)(function () {
    if (!popoverButton || !canShowPopoverButton) return;
    return (0, _react2.jsx)("span", {
      className: "euiSelectableTemplateSitewide__popoverTrigger",
      onClick: togglePopover,
      onKeyDown: function onKeyDown(e) {
        return e.stopPropagation();
      }
    }, popoverButton);
  }, [popoverButton, canShowPopoverButton, togglePopover]);
  return (0, _react2.jsx)(_selectable.EuiSelectable, (0, _extends2.default)({
    css: styles.euiSelectableTemplateSitewide,
    className: classes,
    isLoading: isLoading,
    options: formattedOptions,
    renderOption: _selectable_template_sitewide_option.euiSelectableTemplateSitewideRenderOptions,
    singleSelection: true,
    searchProps: _objectSpread(_objectSpread({
      placeholder: searchPlaceholder,
      isClearable: true
    }, searchProps), {}, {
      onFocus: searchOnFocus,
      onBlur: searchOnBlur,
      onInput: onSearchInput,
      onKeyDown: onSearchKeydown,
      className: searchClasses
    }),
    listProps: _objectSpread(_objectSpread({
      rowHeight: 52,
      showIcons: false,
      onFocusBadge: {
        iconSide: 'right',
        children: (0, _react2.jsx)(_i18n.EuiI18n, {
          token: "euiSelectableTemplateSitewide.onFocusBadgeGoTo",
          default: "Go to"
        })
      }
    }, listProps), {}, {
      className: listClasses
    }),
    loadingMessage: loadingMessage,
    emptyMessage: emptyMessage,
    noMatchesMessage: emptyMessage
  }, rest, {
    searchable: true
  }), function (list, search) {
    var _search = !popoverTrigger ? (0, _react2.jsx)(_services.EuiThemeProvider, {
      colorMode: searchColorMode
    }, search) : search;

    // uses standalone subcomponent to ensure scoped style/theme context
    var popover = (0, _react2.jsx)(_selectable_template_sitewide_popover.EuiSelectableTemplateSitewidePopover, (0, _extends2.default)({
      isOpen: popoverIsOpen,
      trigger: popoverTrigger,
      search: _search,
      list: list,
      title: popoverTitle,
      footer: popoverFooter,
      width: popoverWidth,
      panelRef: setPanelRef,
      closePopover: closePopover
    }, popoverRest));
    return (0, _react2.jsx)(_services.EuiThemeProvider, {
      wrapperProps: {
        cloneElement: true
      },
      colorMode: popoverColorMode
    }, popover);
  });
};