"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DropdownMenu = DropdownMenu;
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _DropdownMenuOption = require("./DropdownMenuOption");
var _DropdownMenuSection = require("./DropdownMenuSection");
var _reactAria = require("../react-aria");
var _usePressEscapeHandler = _interopRequireDefault(require("../utilities/usePressEscapeHandler"));
var _classnames = _interopRequireDefault(require("classnames"));
var _excluded = ["children", "componentClass", "heading", "labelId", "menuId", "rootId", "size", "state"]; // from react-stately
// from react-aria
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function DropdownMenu(_ref) {
  var _props$listBoxRef;
  var children = _ref.children,
    componentClass = _ref.componentClass,
    heading = _ref.heading,
    labelId = _ref.labelId,
    menuId = _ref.menuId,
    rootId = _ref.rootId,
    size = _ref.size,
    state = _ref.state,
    props = _objectWithoutProperties(_ref, _excluded);
  var fallbackListBoxRef = (0, _react.useRef)(null);
  var listBoxRef = (_props$listBoxRef = props.listBoxRef) !== null && _props$listBoxRef !== void 0 ? _props$listBoxRef : fallbackListBoxRef;
  var _useListBox = (0, _reactAria.useListBox)(props, state, listBoxRef),
    listBoxProps = _useListBox.listBoxProps;
  var headingId = "".concat(rootId, "__heading");
  var containerClass = (0, _classnames.default)("".concat(componentClass, "__menu-container"), size && "ds-c-field--".concat(size));
  var containerRef = (0, _react.useRef)();
  (0, _usePressEscapeHandler.default)(containerRef, function () {
    var _props$triggerRef$cur, _props$triggerRef$cur2;
    state.setOpen(false);
    (_props$triggerRef$cur = props.triggerRef.current) === null || _props$triggerRef$cur === void 0 ? void 0 : (_props$triggerRef$cur2 = _props$triggerRef$cur.focus) === null || _props$triggerRef$cur2 === void 0 ? void 0 : _props$triggerRef$cur2.call(_props$triggerRef$cur);
  });

  // Workaround for react/react-aria #1513
  (0, _react.useEffect)(function () {
    var _containerRef$current;
    var listener = function listener(event) {
      event.preventDefault();
    };
    (_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : _containerRef$current.addEventListener('touchend', listener, {
      passive: false
    });
    return function () {
      var _containerRef$current2;
      (_containerRef$current2 = containerRef.current) === null || _containerRef$current2 === void 0 ? void 0 : _containerRef$current2.removeEventListener('touchend', listener);
    };
  }, []);
  function handleTabKey(event) {
    var TAB_KEY = 9;
    if (event.keyCode === TAB_KEY || event.key === 'Tab') {
      if (!state.selectionManager.selectedKeys.has(state.selectionManager.focusedKey)) {
        state.selectionManager.setSelectedKeys([state.selectionManager.focusedKey]);
      }
    }
  }
  var sharedProps = {
    state: state,
    rootId: rootId,
    componentClass: componentClass
  };

  // These must be mutually exclusive, because when we force the menu to render open when
  // react-aria's state doesn't consider it open (state.isOpen), it seems to actually
  // render unexpected items. Currently we don't have a reason to render both at the same
  // time, so this is fine.
  var contents = children !== null && children !== void 0 ? children : _toConsumableArray(state.collection).map(function (item) {
    return item.type === 'section' ? /*#__PURE__*/_react.default.createElement(_DropdownMenuSection.DropdownMenuSection, _extends({
      key: item.key,
      section: item
    }, sharedProps)) : /*#__PURE__*/_react.default.createElement(_DropdownMenuOption.DropdownMenuOption, _extends({
      key: item.key,
      item: item
    }, sharedProps));
  });
  return /*#__PURE__*/_react.default.createElement("div", {
    className: containerClass,
    ref: containerRef,
    onKeyDown: handleTabKey
  }, heading && /*#__PURE__*/_react.default.createElement("h5", {
    className: "ds-c-autocomplete__label",
    id: headingId
  }, heading), /*#__PURE__*/_react.default.createElement("ul", _extends({}, listBoxProps, {
    id: menuId,
    "aria-labelledby": (0, _classnames.default)(labelId, heading && headingId),
    className: "".concat(componentClass, "__menu"),
    ref: listBoxRef
  }), contents));
}
var _default = DropdownMenu;
exports.default = _default;