'use strict';

var _extends = require('@babel/runtime/helpers/extends');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/web.dom-collections.for-each.js');
var React = require('react');
var PropTypes = require('prop-types');
var classnames = require('classnames');
var react = require('@carbon/react');
var colors = require('@carbon/colors');
var headerConstants = require('../headerConstants.js');
var componentUtilityFunctions = require('../../../utils/componentUtilityFunctions.js');
var HeaderPropTypes = require('../HeaderPropTypes.js');
var suiteHeaderUtils = require('../../SuiteHeader/suiteHeaderUtils.js');
var iconsReact = require('@carbon/icons-react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _extends__default = /*#__PURE__*/_interopDefault(_extends);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

var _excluded = ["element"];
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) { _defineProperty__default.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; }

// const { prefix: carbonPrefix } = settings; // need to upgrade carbon 11
var carbonPrefix = 'bx';
var propTypes = _objectSpread(_objectSpread({}, HeaderPropTypes.HeaderActionPropTypes), {}, {
  /** unique id for the action panel */
  id: PropTypes__default.default.string.isRequired,
  /** Ref object to be attached to the parent that should receive focus when a menu is closed */
  focusRef: PropTypes__default.default.oneOfType([
  // Either a function
  PropTypes__default.default.func,
  // Or the instance of a DOM native element (see the note about SSR)
  PropTypes__default.default.shape({
    current: typeof Element === 'undefined' ? PropTypes__default.default.any : PropTypes__default.default.instanceOf(Element)
  })]).isRequired
});
var defaultProps = {
  // disabled b/c these are pulled in via the HeaderActionPropTypes above.
  /* eslint-disable react/default-props-match-prop-types */
  isExpanded: false,
  renderLabel: false,
  i18n: {
    closeMenu: 'close menu'
  },
  showCloseIconWhenPanelExpanded: false
  /* eslint-enable react/default-props-match-prop-types */
};

/**
 * This component renders both a Header Action and it's child Header Panel
 * It has no local state.
 * It calls the onToggleExpansion when it should be opened or closed
 */
var HeaderActionPanel = function HeaderActionPanel(_ref) {
  var item = _ref.item,
    index = _ref.index,
    onToggleExpansion = _ref.onToggleExpansion,
    isExpanded = _ref.isExpanded,
    focusRef = _ref.focusRef,
    renderLabel = _ref.renderLabel,
    i18n = _ref.i18n,
    inOverflow = _ref.inOverflow,
    showCloseIconWhenPanelExpanded = _ref.showCloseIconWhenPanelExpanded,
    id = _ref.id;
  var panelRef = React.useRef();
  var mergedI18n = React.useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);

  /**
   * This workaround is needed because blur event is not triggered
   * on button in Safari. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#clicking_and_focus
   */
  React.useEffect(function () {
    if (!suiteHeaderUtils.isSafari()) {
      return;
    }
    var handleOutsidePanelClick = function handleOutsidePanelClick(event) {
      if (panelRef.current && panelRef.current.contains(event.target) || focusRef.current && focusRef.current.contains(event.target)) {
        return;
      }
      if (isExpanded) {
        onToggleExpansion();
      }
    };
    document.addEventListener('click', handleOutsidePanelClick, {
      capture: true
    });

    // eslint-disable-next-line consistent-return
    return function () {
      return document.removeEventListener('click', handleOutsidePanelClick, {
        capture: true
      });
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isExpanded, onToggleExpansion]);
  return /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(react.HeaderGlobalAction, {
    className: "".concat(carbonPrefix, "--header-action-btn action-btn__trigger"),
    key: "menu-item-".concat(item.label, "-global"),
    "aria-label": item.label,
    "aria-haspopup": "menu",
    "aria-expanded": isExpanded,
    onClick: function onClick() {
      return onToggleExpansion();
    },
    ref: focusRef,
    id: id
  }, renderLabel ? item.label : isExpanded && (inOverflow || showCloseIconWhenPanelExpanded) ? /*#__PURE__*/React__default.default.createElement(iconsReact.Close, {
    fill: colors.white,
    description: mergedI18n.closeMenu
  }) : item.btnContent), /*#__PURE__*/React__default.default.createElement(react.HeaderPanel, {
    "data-testid": "action-btn__panel",
    ref: panelRef,
    tabIndex: "-1",
    key: "panel-".concat(index),
    className: item.label !== headerConstants.APP_SWITCHER ? classnames__default.default('action-btn__headerpanel', {
      'action-btn__headerpanel--closed': !isExpanded
    }) : classnames__default.default("".concat(carbonPrefix, "--app-switcher"), _defineProperty__default.default(_defineProperty__default.default({}, item.childContent[0].className, item.childContent[0].className), item.childContent[0].metaData.className, item.childContent[0].metaData.className)),
    expanded: isExpanded
  }, /*#__PURE__*/React__default.default.createElement("ul", {
    "aria-label": item.label
  }, item.childContent.map(function (childItem, k) {
    var _childItem$metaData;
    var _ref2 = (_childItem$metaData = childItem === null || childItem === void 0 ? void 0 : childItem.metaData) !== null && _childItem$metaData !== void 0 ? _childItem$metaData : {},
      element = _ref2.element,
      metaData = _objectWithoutProperties__default.default(_ref2, _excluded);
    var ChildElement = element || 'a';
    var onKeyDownClick = function onKeyDownClick(e) {
      return e.target.click();
    };

    // if the item is an A and doesn't have an onClick event
    // do nothing. An A tag doesn't need an onClick handler.
    var onClick = ChildElement === 'a' && !(metaData !== null && metaData !== void 0 && metaData.onClick) ? undefined :
    // otherwise, if an onClick exists use that, or fallback to a noop.
    (metaData === null || metaData === void 0 ? void 0 : metaData.onClick) || function () {};

    // if item has onKeyDown use that otherwise, fallback to onClick if it exists
    // or create a custom handler to trigger the click
    var onKeyDown = metaData !== null && metaData !== void 0 && metaData.onKeyDown ? metaData.onKeyDown : onClick || onKeyDownClick;
    return /*#__PURE__*/React__default.default.createElement("li", {
      key: "listitem-".concat(item.label, "-").concat(k),
      className: "action-btn__headerpanel-li"
    }, /*#__PURE__*/React__default.default.createElement(ChildElement, _extends__default.default({
      key: "headerpanelmenu-item-".concat(item.label, "-").concat(index, "-child-").concat(k)
    }, metaData, {
      onClick: onClick,
      onKeyDown: componentUtilityFunctions.handleSpecificKeyDown(['Enter', ' '], onKeyDown)
    }),
    // if we're working with an actual react component (not an html element) pass
    // the isExpanded prop, so we can control tab-navigation on the closed AppSwitcher
    /*#__PURE__*/React__default.default.isValidElement(childItem.content) && typeof childItem.content.type !== 'string' ? /*#__PURE__*/React__default.default.cloneElement(childItem.content, {
      isExpanded: isExpanded
    }) : childItem.content));
  }))));
};
HeaderActionPanel.propTypes = propTypes;
HeaderActionPanel.defaultProps = defaultProps;
var HeaderActionPanel$1 = /*#__PURE__*/React__default.default.forwardRef(function (props, ref) {
  return /*#__PURE__*/React__default.default.createElement(HeaderActionPanel, _extends__default.default({}, props, {
    focusRef: ref
  }));
});

module.exports = HeaderActionPanel$1;
