"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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

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

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _menuItem = require("../menu-item");

var _primitives = require("../../../../primitives");

var _branding = require("../../../../mixins/branding");

var _clickOutside = require("../../../behaviors/click-outside");

var _menu = require("../menu.css-rules");

var _breakpoints = require("../../../../breakpoints");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var MenuItemListWrapper = (0, _styledComponents["default"])(_primitives.Box).withConfig({
  displayName: "MenuItemListWrapper",
  componentId: "a6s6y5-0"
})(["position:absolute;min-width:210px;top:100%;z-index:2;box-shadow:0 5px 15px 0 rgba(0,0,0,0.05);border-radius:", " ", " ", " ", ";background:", ";", "{&:first-child{border-radius:", " ", " 0 0;}&:last-child{border-radius:0 0 ", " ", ";}}@media (max-width:", "){width:100vw;min-width:auto;}"], _menu.getTopBorderRadius, _menu.getTopBorderRadius, _menu.getBottomBorderRadius, _menu.getBottomBorderRadius, (0, _branding.getPaletteColor)('white'), _menuItem.MenuItem, _menu.getTopBorderRadius, _menu.getTopBorderRadius, _menu.getBottomBorderRadius, _menu.getBottomBorderRadius, _breakpoints.bpMedium);

var MenuItemList = function MenuItemList(_ref) {
  var children = _ref.children,
      onToggle = _ref.onToggle,
      flatTopCorners = _ref.flatTopCorners;

  var _useState = (0, _react.useState)(0),
      _useState2 = _slicedToArray(_useState, 2),
      focusIndex = _useState2[0],
      setFocusIndex = _useState2[1];

  var _useState3 = (0, _react.useState)(Array.isArray(children) ? new Array(children.length) : [undefined]),
      _useState4 = _slicedToArray(_useState3, 2),
      childRefs = _useState4[0],
      setChildRefs = _useState4[1]; // Focus the first menu item when the popup appears.


  (0, _react.useEffect)(function () {
    var _childRefs$focusIndex;

    (_childRefs$focusIndex = childRefs[focusIndex]) === null || _childRefs$focusIndex === void 0 ? void 0 : _childRefs$focusIndex.focus();
  }, [childRefs, focusIndex]); // Inject some extra behaviour into the children:
  // * keep track of a ref so this parent can update the focused item
  //   from arrow key events
  // * override each item's onClick to close the menu when it is selected.

  var childrenWithRefs = (0, _react.useMemo)(function () {
    return _react.Children.map(children, function (child, i) {
      return /*#__PURE__*/(0, _react.cloneElement)(child, {
        ref: function ref(r) {
          return setChildRefs(function (last) {
            var next = _toConsumableArray(last);

            next[i] = r;
            return next;
          });
        },
        onClick: function onClick(e) {
          var _child$props;

          child === null || child === void 0 ? void 0 : (_child$props = child.props) === null || _child$props === void 0 ? void 0 : _child$props.onClick(e);
          onToggle();
        }
      });
    });
  }, [children, onToggle]); // Update which menu item has the focus when the up or down arrow keys are
  // pressed. Close the menu when the escape key is pressed.

  var handleKeyDown = function handleKeyDown(e) {
    switch (e.key) {
      case 'ArrowDown':
        setFocusIndex(function (last) {
          return (last + 1) % childrenWithRefs.length;
        });
        e.stopPropagation();
        e.preventDefault();
        break;

      case 'ArrowUp':
        setFocusIndex(function (last) {
          var next = (last - 1) % childrenWithRefs.length;
          if (next < 0) return childrenWithRefs.length - 1;
          return next;
        });
        e.stopPropagation();
        e.preventDefault();
        break;

      case 'Escape':
        onToggle();
        e.stopPropagation();
        e.preventDefault();
        break;

      case 'Tab':
        onToggle(); // Allow event to bubble so we can tab out of the menu.

        break;

      default:
    }
  };

  return /*#__PURE__*/_react["default"].createElement(_clickOutside.ClickOutside, {
    onClickOutside: function onClickOutside(e) {
      onToggle();
      e.stopPropagation();
    }
  }, /*#__PURE__*/_react["default"].createElement(MenuItemListWrapper, {
    flatTopCorners: flatTopCorners,
    onKeyDown: handleKeyDown,
    stacked: "column"
  }, childrenWithRefs));
};

exports.MenuItemList = MenuItemList;