"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _reactDom = require("react-dom");
var _classnames = _interopRequireDefault(require("classnames"));
var _reactMeasure = _interopRequireDefault(require("react-measure"));
var _constants = require("../../constants");
var _Popper = _interopRequireDefault(require("../Popper"));
var _Button = _interopRequireDefault(require("../Button"));
var _Heading = _interopRequireDefault(require("../Heading"));
var _AutoClosable = _interopRequireDefault(require("../AutoClosable"));
var _Translate = require("../Translate");
var _utils = require("../utils");
var _OnDarkContext = _interopRequireDefault(require("../OnDarkContext"));
var _FocusTrap = _interopRequireDefault(require("../FocusTrap"));
var _react = require("react");
var _jsxRuntime = require("react/jsx-runtime");
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

const PLACEMENT_MAP = {
  'top-left': 'top-end',
  'top-right': 'top-start',
  'right-top': 'right-end',
  'right-bottom': 'right-start',
  'bottom-left': 'bottom-end',
  'bottom-right': 'bottom-start',
  'left-top': 'left-end',
  'left-bottom': 'left-start',
  top: 'top',
  right: 'right',
  bottom: 'bottom',
  left: 'left',
  auto: 'auto'
};
const ARROW_HEIGHT = 26;
const isControlled = props => props.visible !== null;
const normalize = value => String(Number(value)) === String(value) ? `${value}px` : value;
/**
 * `Popover` component is non-modal pop-up window used for providing additional information
 * for an interface element. It also may contain Form with few fields or any other small content.
 * @since 0.0.42
 */
class Popover extends _react.Component {
  constructor() {
    super(...arguments);
    (0, _defineProperty2.default)(this, "state", {
      show: this.props.defaultVisible,
      arrowInHeader: false
    });
    (0, _defineProperty2.default)(this, "contentRef", /*#__PURE__*/(0, _react.createRef)());
    (0, _defineProperty2.default)(this, "targetRef", /*#__PURE__*/(0, _react.createRef)());
    (0, _defineProperty2.default)(this, "prevFocusElement", void 0);
    (0, _defineProperty2.default)(this, "popperData", void 0);
    (0, _defineProperty2.default)(this, "headerBounds", void 0);
    (0, _defineProperty2.default)(this, "checkArrowPosition", () => {
      const {
        title
      } = this.props;
      const {
        show,
        arrowInHeader
      } = this.state;
      if (!show || !this.popperData) {
        return;
      }
      const {
        actualPlacement,
        arrowStyle
      } = this.popperData;
      const top = parseInt(arrowStyle?.top || '');
      const [direction] = actualPlacement?.split('-') || [];
      let newArrowInHeader = false;
      const directionBottomOrPopoverLowEnough = direction === 'bottom' || top !== null && this.headerBounds && top < this.headerBounds.height - ARROW_HEIGHT / 2;
      const rightDirection = direction !== 'top' && directionBottomOrPopoverLowEnough;
      if (title && this.headerBounds && rightDirection) {
        newArrowInHeader = true;
      }
      if (arrowInHeader !== newArrowInHeader) {
        this.setState({
          arrowInHeader: newArrowInHeader
        });
      }
    });
    (0, _defineProperty2.default)(this, "hotkeyHandler", e => {
      if (!e.isDefaultPrevented() && e.key === 'Escape') {
        this.handleClose();
        e.preventDefault();
      }
    });
    (0, _defineProperty2.default)(this, "handleTargetClick", e => {
      const {
        show
      } = this.state;
      const {
        canCloseOnOutsideClick
      } = this.props;
      if (show && !canCloseOnOutsideClick) {
        return;
      }
      this.targetRef.current = e.currentTarget;
      this.setState(prevState => ({
        show: !prevState.show
      }));
    });
    (0, _defineProperty2.default)(this, "handleClose", () => {
      const {
        show
      } = this.state;
      if (!show) {
        return;
      }
      const {
        onClose,
        canCloseOnEscapePress,
        autoFocus
      } = this.props;
      const isNeedFocus = autoFocus && canCloseOnEscapePress && this.prevFocusElement && (!document.activeElement || this.contentRef.current?.contains(document.activeElement));
      if (onClose) {
        onClose();
      } else {
        this.setState({
          show: false
        });
      }
      if (isNeedFocus) {
        this.prevFocusElement?.focus();
      }
    });
    (0, _defineProperty2.default)(this, "handleHeaderResize", contentRect => {
      this.headerBounds = contentRect.bounds;
      this.checkArrowPosition();
    });
    (0, _defineProperty2.default)(this, "handlePopperUpdate", popperData => {
      this.popperData = popperData;
      this.checkArrowPosition();
    });
    (0, _defineProperty2.default)(this, "getIgnoreNodes", () => {
      const {
        targetRef
      } = this.props;
      if (targetRef || this.targetRef.current) {
        return [targetRef, this.targetRef];
      }
      return [(0, _reactDom.findDOMNode)(this)];
    });
  }
  static getDerivedStateFromProps(props, state) {
    return {
      show: isControlled(props) ? props.visible : state.show
    };
  }
  componentDidUpdate(_, prevState) {
    const {
      canCloseOnEscapePress,
      autoFocus
    } = this.props;
    const {
      show
    } = this.state;
    if (autoFocus && canCloseOnEscapePress && !prevState.show && show) {
      setTimeout(() => this.focus(), 0);
    }
  }
  focus() {
    if (this.contentRef.current === null || document.activeElement === null || !this.state.show) {
      return;
    }
    this.prevFocusElement = document.activeElement;
    const isFocusOutside = !this.contentRef.current.contains(document.activeElement);
    if (isFocusOutside) {
      const autofocusElement = this.contentRef.current.querySelector('[autofocus]');
      if (autofocusElement !== null) {
        autofocusElement.focus();
      } else if (this.contentRef.current) {
        this.contentRef.current.focus();
      }
    }
  }
  render() {
    const {
      baseClassName,
      className,
      visible,
      defaultVisible,
      title,
      placement,
      canCloseOnOutsideClick,
      canCloseOnEscapePress,
      target,
      targetRef,
      intent,
      wide,
      width,
      height,
      extra,
      onClose,
      children,
      ...props
    } = this.props;
    const {
      show,
      arrowInHeader
    } = this.state;
    let behavior;
    if (placement !== 'auto') {
      const [direction] = placement?.split('-') || [];
      if (direction === 'top') {
        behavior = ['top', 'bottom', 'right', 'left'];
      } else if (direction === 'right') {
        behavior = ['right', 'left', 'bottom', 'top'];
      } else if (direction === 'bottom') {
        behavior = ['bottom', 'top', 'left', 'right'];
      } else if (direction === 'left') {
        behavior = ['left', 'right', 'top', 'bottom'];
      }
    }
    const close = /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
      className: (0, _classnames.default)(`${baseClassName}__close`, title && `${baseClassName}__close--heading`),
      onClick: this.handleClose,
      ghost: true,
      icon: {
        name: 'cross-mark',
        size: title ? 16 : 12
      }
    });
    const heading = title && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactMeasure.default, {
      onResize: this.handleHeaderResize,
      bounds: true,
      children: _ref => {
        let {
          measureRef
        } = _ref;
        return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          ref: measureRef,
          className: `${baseClassName}__heading`,
          children: [(0, _Translate.isLikeText)(title) ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Heading.default, {
            level: 5,
            className: `${baseClassName}__title`,
            children: title
          }) : title, /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            className: `${baseClassName}__extra`,
            children: [extra, close]
          })]
        });
      }
    });
    const trigger = isControlled(this.props) ? target : /*#__PURE__*/(0, _react.cloneElement)(target, {
      className: (0, _classnames.default)(target.props.className, `${baseClassName}__target`),
      onClick: (0, _utils.wrapFunction)(target.props.onClick, this.handleTargetClick)
    });
    const popperPlacement = placement ? PLACEMENT_MAP[placement] : undefined;
    let wrapperStyle;
    if (height) {
      wrapperStyle = {
        height: normalize(height)
      };
    }
    const content = /*#__PURE__*/(0, _jsxRuntime.jsxs)(_FocusTrap.default, {
      ref: this.contentRef,
      onKeyUp: canCloseOnEscapePress && show ? this.hotkeyHandler : undefined,
      className: `${baseClassName}__inner`,
      style: wrapperStyle,
      children: [height ? heading : heading || close, /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: `${baseClassName}__content`,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: `${baseClassName}__content-inner`,
          children: typeof children === 'function' ? children({
            onClose: this.handleClose
          }) : children
        })
      })]
    });
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Popper.default, {
      target: trigger,
      targetRef: targetRef ? targetRef : this.targetRef,
      arrow: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        className: (0, _classnames.default)(`${baseClassName}__arrow`, arrowInHeader && `${baseClassName}__arrow--heading`)
      }),
      placement: popperPlacement,
      onUpdate: this.handlePopperUpdate,
      className: (0, _classnames.default)({
        [`${baseClassName}--heading`]: title,
        [`${baseClassName}--${intent}`]: intent,
        [`${baseClassName}--wide`]: wide || width,
        [`${baseClassName}--width-${width}`]: width,
        [`${baseClassName}--on-dark`]: this.context === true
      }, className),
      baseClassName: baseClassName,
      behavior: behavior,
      zIndex: _constants.Z_INDEX_POPOVER,
      show: show,
      ...props,
      children: canCloseOnOutsideClick ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_AutoClosable.default, {
        onClose: this.handleClose,
        ignoreNodes: this.getIgnoreNodes,
        nodeRef: this.contentRef,
        children: content
      }) : content
    });
  }
}
// eslint-disable-next-line react/sort-comp
(0, _defineProperty2.default)(Popover, "contextType", _OnDarkContext.default);
(0, _defineProperty2.default)(Popover, "defaultProps", {
  visible: null,
  defaultVisible: false,
  title: undefined,
  onClose: undefined,
  placement: 'auto',
  canCloseOnOutsideClick: true,
  canCloseOnEscapePress: true,
  children: undefined,
  intent: undefined,
  wide: undefined,
  width: undefined,
  height: undefined,
  extra: undefined,
  className: undefined,
  baseClassName: `${_constants.CLS_PREFIX}popover`,
  boundariesElement: undefined,
  autoFocus: true,
  targetRef: undefined
});
var _default = exports.default = Popover;