import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
/** @jsx jsx */

import { Component } from 'react';
import { css, jsx } from '@emotion/react';
import { createAndFireEvent, withAnalyticsContext, withAnalyticsEvents } from '@atlaskit/analytics-next';
import { N0, N50A, N60A, N900 } from '@atlaskit/theme/colors';
import Layer from '../Layer';
var packageName = "@atlaskit/editor-common";
var packageVersion = "78.33.1";
var halfFocusRing = 1;
var dropOffset = '0, 8';
var DropList = /*#__PURE__*/function (_Component) {
  _inherits(DropList, _Component);
  var _super = _createSuper(DropList);
  function DropList() {
    var _this;
    _classCallCheck(this, DropList);
    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));
    _defineProperty(_assertThisInitialized(_this), "wrapperStyles", css({
      display: _this.props.shouldFitContainer ? 'block' : 'inline-flex',
      flex: _this.props.shouldFitContainer ? '1 1 auto' : undefined,
      transitionDuration: '0.2s',
      transition: 'box-shadow 0.15s cubic-bezier(0.47, 0.03, 0.49, 1.38)'
    }));
    _defineProperty(_assertThisInitialized(_this), "triggerStyles", css({
      transitionDuration: '0.2s',
      transition: 'box-shadow 0.15s cubic-bezier(0.47, 0.03, 0.49, 1.38)',
      display: _this.props.shouldFitContainer ? 'block' : 'inline-flex',
      boxSizing: _this.props.shouldFitContainer ? 'border-box' : undefined
    }));
    /* eslint-disable @atlaskit/design-system/ensure-design-token-usage */
    _defineProperty(_assertThisInitialized(_this), "menuWrapper", function () {
      return css({
        color: "var(--ds-text, ".concat(N900, ")"),
        backgroundColor: "var(--ds-surface-overlay, ".concat(N0, ")"),
        borderRadius: "var(--ds-border-radius, 3px)",
        boxShadow: "var(--ds-shadow-overlay, ".concat("0 4px 8px calc(-1 * 2px) ".concat(N50A, ", 0 0 1px ").concat(N60A), ")"),
        boxSizing: 'border-box',
        overflow: 'auto',
        padding: "var(--ds-space-050, 4px)".concat(" 0"),
        maxHeight: '90vh'
      });
    });
    /* eslint-enable @atlaskit/design-system/ensure-design-token-usage */
    _defineProperty(_assertThisInitialized(_this), "componentDidMount", function () {
      _this.setContentWidth();
      // We use a captured event here to avoid a radio or checkbox dropdown item firing its
      // click event first, which would cause a re-render of the element and prevent DropList
      // from detecting the actual source of this original click event.
      document.addEventListener('click', _this.handleClickOutside, true);
      document.addEventListener('keydown', _this.handleEsc);
    });
    _defineProperty(_assertThisInitialized(_this), "componentDidUpdate", function () {
      if (_this.props.isOpen) {
        _this.setContentWidth();
      }
    });
    _defineProperty(_assertThisInitialized(_this), "componentWillUnmount", function () {
      document.removeEventListener('click', _this.handleClickOutside, true);
      document.removeEventListener('keydown', _this.handleEsc);
    });
    _defineProperty(_assertThisInitialized(_this), "setContentWidth", function () {
      var _assertThisInitialize = _assertThisInitialized(_this),
        dropContentRef = _assertThisInitialize.dropContentRef,
        triggerRef = _assertThisInitialize.triggerRef;
      var shouldFitContainer = _this.props.shouldFitContainer;

      // We need to manually set the content width to match the trigger width
      if (shouldFitContainer && dropContentRef && triggerRef) {
        dropContentRef.style.width = "".concat(triggerRef.offsetWidth - halfFocusRing * 2, "px");
      }
    });
    _defineProperty(_assertThisInitialized(_this), "handleEsc", function (event) {
      if ((event.key === 'Escape' || event.key === 'Esc') && _this.props.isOpen) {
        _this.close(event);
      }
    });
    _defineProperty(_assertThisInitialized(_this), "handleClickOutside", function (event) {
      if (_this.props.isOpen) {
        if (event.target instanceof Node) {
          // Rather than check for the target within the entire DropList, we specify the trigger/content.
          // This aids with future effort in scroll-locking DropList when isMenuFixed is enabled; the scroll
          // blanket which stretches to the viewport should not stop 'close' from being triggered.
          var withinTrigger = _this.triggerRef && _this.triggerRef.contains(event.target);
          var withinContent = _this.dropContentRef && _this.dropContentRef.contains(event.target);
          if (!withinTrigger && !withinContent) {
            _this.close(event);
          }
        }
      }
    });
    _defineProperty(_assertThisInitialized(_this), "close", function (event) {
      if (_this.props.onOpenChange) {
        _this.props.onOpenChange({
          isOpen: false,
          event: event
        });
      }
    });
    _defineProperty(_assertThisInitialized(_this), "handleContentRef", function (ref) {
      _this.dropContentRef = ref;

      // If the dropdown has just been opened, we focus on the containing element so the
      // user can tab to the first dropdown item. We will only receive this ref if isOpen
      // is true or null, so no need to check for truthiness here.
      if (ref) {
        ref.focus();
      }
    });
    _defineProperty(_assertThisInitialized(_this), "handleTriggerRef", function (ref) {
      _this.triggerRef = ref;
    });
    return _this;
  }
  _createClass(DropList, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
        children = _this$props.children,
        isOpen = _this$props.isOpen,
        position = _this$props.position,
        trigger = _this$props.trigger,
        onPositioned = _this$props.onPositioned,
        testId = _this$props.testId,
        id = _this$props.id;
      var layerContent = isOpen ? jsx("div", {
        css: this.menuWrapper,
        "data-role": "droplistContent",
        "data-testid": testId && "".concat(testId, "--content"),
        ref: this.handleContentRef,
        id: id,
        role: "presentation"
      }, children) : null;
      return jsx("div", {
        css: this.wrapperStyles
      }, jsx(Layer, {
        content: layerContent,
        offset: dropOffset,
        position: position,
        onPositioned: onPositioned
      }, jsx("div", {
        css: this.triggerStyles,
        ref: this.handleTriggerRef
      }, trigger)));
    }
  }]);
  return DropList;
}(Component);
var createAndFireEventOnAtlaskit = createAndFireEvent('atlaskit');
export default withAnalyticsContext({
  componentName: 'droplist',
  packageName: packageName,
  packageVersion: packageVersion
})(withAnalyticsEvents({
  onOpenChange: createAndFireEventOnAtlaskit({
    action: 'toggled',
    actionSubject: 'droplist',
    attributes: {
      componentName: 'droplist',
      packageName: packageName,
      packageVersion: packageVersion
    }
  })
})(DropList));