"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "EuiSuperSelect", {
  enumerable: true,
  get: function get() {
    return _super_select.EuiSuperSelect;
  }
});
exports.OuiSuperSelect = void 0;

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

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

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 _react = _interopRequireWildcard(require("react"));

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

var _classnames = _interopRequireDefault(require("classnames"));

var _accessibility = require("../../accessibility");

var _super_select_control = require("./super_select_control");

var _popover = require("../../popover");

var _context_menu = require("../../context_menu");

var _services = require("../../../services");

var _i18n = require("../../i18n");

var _super_select = require("../../../eui_components/form/super_select/super_select");

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; } } /*
                                                                                                                                                                                                                                                                                                                                      * SPDX-License-Identifier: Apache-2.0
                                                                                                                                                                                                                                                                                                                                      *
                                                                                                                                                                                                                                                                                                                                      * The OpenSearch Contributors require contributions made to
                                                                                                                                                                                                                                                                                                                                      * this file be licensed under the Apache-2.0 license or a
                                                                                                                                                                                                                                                                                                                                      * compatible open source license.
                                                                                                                                                                                                                                                                                                                                      *
                                                                                                                                                                                                                                                                                                                                      * Modifications Copyright OpenSearch Contributors. See
                                                                                                                                                                                                                                                                                                                                      * GitHub history for details.
                                                                                                                                                                                                                                                                                                                                      */ /*
                                                                                                                                                                                                                                                                                                                                          * Licensed to Elasticsearch B.V. under one or more contributor
                                                                                                                                                                                                                                                                                                                                          * license agreements. See the NOTICE file distributed with
                                                                                                                                                                                                                                                                                                                                          * this work for additional information regarding copyright
                                                                                                                                                                                                                                                                                                                                          * ownership. Elasticsearch B.V. licenses this file to you under
                                                                                                                                                                                                                                                                                                                                          * the Apache License, Version 2.0 (the "License"); you may
                                                                                                                                                                                                                                                                                                                                          * not use this file except in compliance with the License.
                                                                                                                                                                                                                                                                                                                                          * You may obtain a copy of the License at
                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                          *    http://www.apache.org/licenses/LICENSE-2.0
                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                          * Unless required by applicable law or agreed to in writing,
                                                                                                                                                                                                                                                                                                                                          * software distributed under the License is distributed on an
                                                                                                                                                                                                                                                                                                                                          * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
                                                                                                                                                                                                                                                                                                                                          * KIND, either express or implied.  See the License for the
                                                                                                                                                                                                                                                                                                                                          * specific language governing permissions and limitations
                                                                                                                                                                                                                                                                                                                                          * under the License.
                                                                                                                                                                                                                                                                                                                                          */

var ShiftDirection;

(function (ShiftDirection) {
  ShiftDirection["BACK"] = "back";
  ShiftDirection["FORWARD"] = "forward";
})(ShiftDirection || (ShiftDirection = {}));

var OuiSuperSelect = /*#__PURE__*/function (_Component) {
  (0, _inherits2.default)(OuiSuperSelect, _Component);

  var _super = _createSuper(OuiSuperSelect);

  function OuiSuperSelect() {
    var _this;

    (0, _classCallCheck2.default)(this, OuiSuperSelect);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "itemNodes", []);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "_isMounted", false);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "state", {
      isPopoverOpen: _this.props.isOpen || false
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "setItemNode", function (node, index) {
      _this.itemNodes[index] = node;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "openPopover", function () {
      _this.setState({
        isPopoverOpen: true
      });

      var focusSelected = function focusSelected() {
        var indexOfSelected = _this.props.options.reduce(function (indexOfSelected, option, index) {
          if (indexOfSelected != null) return indexOfSelected;
          if (option == null) return null;
          return option.value === _this.props.valueOfSelected ? index : null;
        }, null);

        requestAnimationFrame(function () {
          if (!_this._isMounted) {
            return;
          }

          if (_this.props.valueOfSelected != null) {
            if (indexOfSelected != null) {
              _this.focusItemAt(indexOfSelected);
            } else {
              focusSelected();
            }
          }
        });
      };

      requestAnimationFrame(focusSelected);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "closePopover", function () {
      _this.setState({
        isPopoverOpen: false
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "itemClicked", function (value) {
      _this.setState({
        isPopoverOpen: false
      });

      if (_this.props.onChange) {
        _this.props.onChange(value);
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onSelectKeyDown", function (event) {
      if (event.key === _services.keys.ARROW_UP || event.key === _services.keys.ARROW_DOWN) {
        event.preventDefault();
        event.stopPropagation();

        _this.openPopover();
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onItemKeyDown", function (event) {
      switch (event.key) {
        case _services.keys.ESCAPE:
          // close the popover and prevent ancestors from handling
          event.preventDefault();
          event.stopPropagation();

          _this.closePopover();

          break;

        case _services.keys.TAB:
          // no-op
          event.preventDefault();
          event.stopPropagation();
          break;

        case _services.keys.ARROW_UP:
          event.preventDefault();
          event.stopPropagation();

          _this.shiftFocus(ShiftDirection.BACK);

          break;

        case _services.keys.ARROW_DOWN:
          event.preventDefault();
          event.stopPropagation();

          _this.shiftFocus(ShiftDirection.FORWARD);

          break;
      }
    });
    return _this;
  }

  (0, _createClass2.default)(OuiSuperSelect, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this._isMounted = true;

      if (this.props.isOpen) {
        this.openPopover();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this._isMounted = false;
    }
  }, {
    key: "focusItemAt",
    value: function focusItemAt(index) {
      var targetElement = this.itemNodes[index];

      if (targetElement != null) {
        targetElement.focus();
      }
    }
  }, {
    key: "shiftFocus",
    value: function shiftFocus(direction) {
      var currentIndex = this.itemNodes.indexOf(document.activeElement);
      var targetElementIndex;

      if (currentIndex === -1) {
        // somehow the select options has lost focus
        targetElementIndex = 0;
      } else {
        if (direction === ShiftDirection.BACK) {
          targetElementIndex = currentIndex === 0 ? this.itemNodes.length - 1 : currentIndex - 1;
        } else {
          targetElementIndex = currentIndex === this.itemNodes.length - 1 ? 0 : currentIndex + 1;
        }
      }

      this.focusItemAt(targetElementIndex);
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          className = _this$props.className,
          options = _this$props.options,
          valueOfSelected = _this$props.valueOfSelected,
          onChange = _this$props.onChange,
          isOpen = _this$props.isOpen,
          isInvalid = _this$props.isInvalid,
          hasDividers = _this$props.hasDividers,
          itemClassName = _this$props.itemClassName,
          itemLayoutAlign = _this$props.itemLayoutAlign,
          fullWidth = _this$props.fullWidth,
          popoverClassName = _this$props.popoverClassName,
          compressed = _this$props.compressed,
          rest = (0, _objectWithoutProperties2.default)(_this$props, ["className", "options", "valueOfSelected", "onChange", "isOpen", "isInvalid", "hasDividers", "itemClassName", "itemLayoutAlign", "fullWidth", "popoverClassName", "compressed"]);
      var popoverClasses = (0, _classnames.default)('ouiSuperSelect', popoverClassName);
      var buttonClasses = (0, _classnames.default)({
        'ouiSuperSelect--isOpen__button': this.state.isPopoverOpen
      }, className);
      var itemClasses = (0, _classnames.default)('ouiSuperSelect__item', {
        'ouiSuperSelect__item--hasDividers': hasDividers
      }, itemClassName);

      var button = /*#__PURE__*/_react.default.createElement(_super_select_control.OuiSuperSelectControl, (0, _extends2.default)({
        options: options,
        value: valueOfSelected,
        onClick: this.state.isPopoverOpen ? this.closePopover : this.openPopover,
        onKeyDown: this.onSelectKeyDown,
        className: buttonClasses,
        fullWidth: fullWidth,
        isInvalid: isInvalid,
        compressed: compressed
      }, rest));

      var items = options.map(function (option, index) {
        var value = option.value,
            dropdownDisplay = option.dropdownDisplay,
            inputDisplay = option.inputDisplay,
            optionRest = (0, _objectWithoutProperties2.default)(option, ["value", "dropdownDisplay", "inputDisplay"]);
        return /*#__PURE__*/_react.default.createElement(_context_menu.OuiContextMenuItem, (0, _extends2.default)({
          key: index,
          className: itemClasses,
          icon: valueOfSelected === value ? 'check' : 'empty',
          onClick: function onClick() {
            return _this2.itemClicked(value);
          },
          onKeyDown: _this2.onItemKeyDown,
          layoutAlign: itemLayoutAlign,
          buttonRef: function buttonRef(node) {
            return _this2.setItemNode(node, index);
          },
          role: "option",
          id: value,
          "aria-selected": valueOfSelected === value
        }, optionRest), dropdownDisplay || inputDisplay);
      });
      return /*#__PURE__*/_react.default.createElement(_popover.OuiInputPopover, {
        className: popoverClasses,
        input: button,
        isOpen: isOpen || this.state.isPopoverOpen,
        closePopover: this.closePopover,
        panelPaddingSize: "none",
        fullWidth: fullWidth
      }, /*#__PURE__*/_react.default.createElement(_accessibility.OuiScreenReaderOnly, null, /*#__PURE__*/_react.default.createElement("p", {
        role: "alert"
      }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiSuperSelect.screenReaderAnnouncement",
        default: "You are in a form selector of {optionsCount} items and must select a single option. Use the up and down keys to navigate or escape to close.",
        values: {
          optionsCount: options.length
        }
      }))), /*#__PURE__*/_react.default.createElement("div", {
        className: "ouiSuperSelect__listbox",
        role: "listbox",
        "aria-activedescendant": valueOfSelected,
        tabIndex: 0
      }, items));
    }
  }]);
  return OuiSuperSelect;
}(_react.Component);
/* OUI -> EUI Aliases: Build-Time */


exports.OuiSuperSelect = OuiSuperSelect;
(0, _defineProperty2.default)(OuiSuperSelect, "defaultProps", {
  hasDividers: false,
  fullWidth: false,
  compressed: false,
  isInvalid: false,
  isLoading: false
});
OuiSuperSelect.propTypes = {
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  compressed: _propTypes.default.bool,
  fullWidth: _propTypes.default.bool,
  isInvalid: _propTypes.default.bool,
  isLoading: _propTypes.default.bool,
  readOnly: _propTypes.default.bool,
  name: _propTypes.default.string,

  /**
     * Creates an input group with element(s) coming before input.
     * `string` | `ReactElement` or an array of these
     */
  prepend: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.element.isRequired]).isRequired, _propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.element.isRequired]).isRequired).isRequired]),

  /**
     * Creates an input group with element(s) coming after input.
     * `string` | `ReactElement` or an array of these
     */
  append: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.element.isRequired]).isRequired, _propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.element.isRequired]).isRequired).isRequired]),

  /**
       * Pass an array of options that must at least include:
       * `value`: storing unique value of item,
       * `inputDisplay`: what shows inside the form input when selected
       * `dropdownDisplay` (optional): what shows for the item in the dropdown
       */
  options: _propTypes.default.arrayOf(_propTypes.default.shape({
    value: _propTypes.default.any.isRequired,
    inputDisplay: _propTypes.default.node,
    dropdownDisplay: _propTypes.default.node,
    disabled: _propTypes.default.bool,
    "data-test-subj": _propTypes.default.string
  }).isRequired).isRequired,
  valueOfSelected: _propTypes.default.any,

  /**
       * Classes for the context menu item
       */
  itemClassName: _propTypes.default.string,

  /**
       * You must pass an `onChange` function to handle the update of the value
       */
  onChange: _propTypes.default.func,

  /**
       * Change to `true` if you want horizontal lines between options.
       * This is best used when options are multi-line.
       */
  hasDividers: _propTypes.default.bool,

  /**
       * Change `OuiContextMenuItem` layout position of icon
       */
  itemLayoutAlign: _propTypes.default.oneOf(["center", "top", "bottom"]),

  /**
       * Applied to the outermost wrapper (popover)
       */
  popoverClassName: _propTypes.default.string,

  /**
       * Controls whether the options are shown. Default: false
       */
  isOpen: _propTypes.default.bool
};
/* OUI -> EUI Aliases: Build-Time */