"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _utils = require("../../utils");
var _react = require("react");
var _utils2 = require("../utils");
var _classnames = _interopRequireDefault(require("classnames"));
var _constants = require("../../constants");
var _Button = _interopRequireDefault(require("../Button"));
var _AutoClosable = _interopRequireDefault(require("../AutoClosable"));
var _Popper = _interopRequireDefault(require("../Popper"));
var _Layer = _interopRequireDefault(require("../Layer"));
var _Menu = require("../Menu");
var _Translate = _interopRequireDefault(require("../Translate"));
var _enUS = _interopRequireDefault(require("./locale/en-US"));
var _jsxRuntime = require("react/jsx-runtime");
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

const createTarget = (node, _ref) => {
  let {
    onToggle,
    targetRef
  } = _ref;
  if (!( /*#__PURE__*/(0, _react.isValidElement)(node) && node.type !== _Translate.default)) {
    node = /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
      caret: true,
      children: node
    });
  }
  let isKeyboardEvent = false;
  return /*#__PURE__*/(0, _react.cloneElement)(node, {
    onKeyDown: (0, _utils2.wrapFunction)(node.props.onKeyDown, e => {
      isKeyboardEvent = e.key === ' ' || e.key === 'Enter';
    }),
    onClick: (0, _utils2.wrapFunction)(node.props.onClick, e => {
      targetRef.current = e.currentTarget;
      onToggle(isKeyboardEvent);
      isKeyboardEvent = false;
    }),
    'aria-haspopup': true
  });
};
const computePlacement = placement => {
  const [side, align] = placement.split('-');
  if (align && (0, _utils.isRtl)() && ['top', 'bottom'].indexOf(side) !== -1) {
    return `${side}-${align === 'start' ? 'end' : 'start'}`;
  }
  return placement;
};
const useEnhancedMenu = (menu, _ref2) => {
  let {
    baseClassName,
    onClose,
    overlay,
    locale,
    autoFocus
  } = _ref2;
  const menuRef = (0, _react.useRef)();
  const triggerRef = (0, _react.useRef)();
  (0, _react.useEffect)(() => {
    if (menuRef.current && !overlay) {
      triggerRef.current = document.activeElement;
      setTimeout(() => {
        if (menuRef.current) {
          menuRef.current.focus();
        }
      });
    }
  });
  const handleClose = () => {
    if (triggerRef.current) {
      triggerRef.current.focus();
    }
    onClose();
  };
  const handleKeyDown = e => {
    e.stopPropagation();
    switch (e.key) {
      case 'Enter':
        e.preventDefault();
        document.activeElement.click();
        break;
      case 'Escape':
        e.preventDefault();
        handleClose();
        break;
      case 'Tab':
        handleClose();
        break;
    }
  };
  let {
    children
  } = menu.props;
  if (overlay) {
    children = [...menu.props.children, /*#__PURE__*/(0, _jsxRuntime.jsx)(_Menu.MenuDivider, {
      className: `${baseClassName}__overlay-menu-divider`
    }, "divider"), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Menu.MenuItem, {
      onClick: handleClose,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
        namespace: "Dropdown",
        content: "close",
        translators: locale,
        fallback: _enUS.default.close
      })
    }, "close")];
  }
  const clone = /*#__PURE__*/(0, _react.cloneElement)(menu, {
    onItemClick: (0, _utils2.wrapFunction)(menu.props.onItemClick, handleClose),
    className: (0, _classnames.default)(`${baseClassName}__menu`, menu.props.className),
    overlay,
    ref: menuRef,
    children,
    onKeyDown: handleKeyDown,
    autoFocus
  });
  return {
    enhancedMenu: clone,
    menuRef
  };
};

/**
 * `Dropdown` component is a [Button](#!/Button) that opens a drop-down (nested) [Menu](#!/Menu).
 * Use dropdown for grouping actions that are not used often or are less important than others -- in other words,
 * for stuff that you don't want to show users all the time, especially if you have limited screen space.
 * @since 0.0.57
 */
const Dropdown = _ref3 => {
  let {
    baseClassName,
    className,
    children,
    menu,
    menuPlacement,
    overlay,
    locale,
    ...props
  } = _ref3;
  const [opened, setOpened] = (0, _react.useState)(false);
  const [autoFocus, setAutoFocus] = (0, _react.useState)(false);
  const closeTimerRef = (0, _react.useRef)();
  (0, _react.useEffect)(() => () => {
    clearTimeout(closeTimerRef.current);
  }, []);
  const handleOpen = isKeyboardEvent => {
    setAutoFocus(isKeyboardEvent);
    setOpened(true);
  };
  const handleClose = () => {
    closeTimerRef.current = setTimeout(() => {
      setOpened(false);
    }, 0);
  };
  const {
    enhancedMenu,
    menuRef
  } = useEnhancedMenu(menu, {
    baseClassName,
    onClose: handleClose,
    overlay,
    locale,
    autoFocus
  });
  const targetRef = (0, _react.useRef)();
  const target = createTarget(children, {
    onToggle: handleOpen,
    targetRef
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: (0, _classnames.default)(baseClassName, {
      [`${baseClassName}--opened`]: opened
    }, className),
    ...props,
    children: overlay ? /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [target, opened && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layer.default, {
        level: _constants.Z_INDEX_OVERLAY,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: `${baseClassName}__overlay`,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_AutoClosable.default, {
            onClose: handleClose,
            nodeRef: menuRef,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
              className: `${baseClassName}__overlay-menu`,
              children: enhancedMenu
            })
          })
        })
      })]
    }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_Popper.default, {
      target: target,
      targetRef: targetRef,
      placement: computePlacement(menuPlacement),
      show: opened,
      className: `${baseClassName}__popper`,
      zIndex: _constants.Z_INDEX_DROPDOWN,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_AutoClosable.default, {
        onClose: handleClose,
        nodeRef: menuRef,
        children: enhancedMenu
      })
    })
  });
};
Dropdown.defaultProps = {
  menuPlacement: 'bottom-start',
  children: undefined,
  overlay: false,
  className: undefined,
  baseClassName: `${_constants.CLS_PREFIX}dropdown`,
  locale: undefined
};
var _default = exports.default = Dropdown;