"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

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

var _bem = require("@zarm-design/bem");

var _reactDomInteractions = require("@floating-ui/react-dom-interactions");

var _transition = _interopRequireDefault(require("../transition"));

var _dom = require("../utils/dom");

var _configProvider = require("../config-provider");

var _utils = require("./utils");

var _mergeRefs = _interopRequireDefault(require("../utils/mergeRefs"));

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

var directionMap = {
  top: 'top',
  'top-left': 'top-start',
  'top-right': 'top-end',
  right: 'right',
  'right-top': 'right-start',
  'right-bottom': 'right-end',
  bottom: 'bottom',
  'bottom-left': 'bottom-start',
  'bottom-right': 'bottom-end',
  left: 'left',
  'left-top': 'left-start',
  'left-bottom': 'left-end'
};
var Popper = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _React$useContext = _react.default.useContext(_configProvider.ConfigContext),
      prefixCls = _React$useContext.prefixCls,
      globalMountContainer = _React$useContext.mountContainer;

  var visible = props.visible,
      mountContainer = props.mountContainer,
      direction = props.direction,
      destroy = props.destroy,
      trigger = props.trigger,
      animationDuration = props.animationDuration,
      hasArrow = props.hasArrow,
      animationType = props.animationType,
      content = props.content,
      children = props.children,
      arrowPointAtCenter = props.arrowPointAtCenter,
      onVisibleChange = props.onVisibleChange;
  var bem = (0, _bem.createBEM)('popper', {
    prefixCls: prefixCls
  });
  var isVisible = trigger === 'manual' && visible;

  var _useState = (0, _react.useState)(isVisible),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      open = _useState2[0],
      setOpen = _useState2[1];

  var arrowRef = (0, _react.useRef)(null);
  var middleware = [(0, _reactDomInteractions.offset)(function (_ref) {
    var placement = _ref.placement;

    var _getElementSize = (0, _dom.getElementSize)(arrowRef.current),
        width = _getElementSize.width,
        height = _getElementSize.height;

    var side = placement.split('-')[0];
    var value = side === 'bottom' || side === 'top' ? height : width;
    return value;
  }), (0, _reactDomInteractions.flip)(), (0, _reactDomInteractions.shift)()];

  if (hasArrow) {
    middleware.push((0, _reactDomInteractions.arrow)({
      element: arrowRef
    }));
  }

  var _useFloating = (0, _reactDomInteractions.useFloating)({
    open: open,
    onOpenChange: function onOpenChange(state) {
      setOpen(state);
      onVisibleChange === null || onVisibleChange === void 0 ? void 0 : onVisibleChange(state);
    },
    middleware: middleware,
    placement: directionMap[direction],
    whileElementsMounted: _reactDomInteractions.autoUpdate
  }),
      x = _useFloating.x,
      y = _useFloating.y,
      reference = _useFloating.reference,
      floating = _useFloating.floating,
      strategy = _useFloating.strategy,
      context = _useFloating.context,
      _update = _useFloating.update;

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      update: function update() {
        _update();
      }
    };
  });

  function computeArrowStyle(ctx) {
    var _ctx$middlewareData;

    var _ref2 = (ctx === null || ctx === void 0 ? void 0 : (_ctx$middlewareData = ctx.middlewareData) === null || _ctx$middlewareData === void 0 ? void 0 : _ctx$middlewareData.arrow) || {},
        arrowX = _ref2.x,
        arrowY = _ref2.y;

    if (arrowRef.current) {
      var postion = ctx.placement.split('-');

      if (!postion[1] || arrowPointAtCenter) {
        return {
          left: x != null ? "".concat(arrowX, "px") : '',
          top: y != null ? "".concat(arrowY, "px") : ''
        };
      }

      return {};
    }
  }

  var _useInteractions = (0, _reactDomInteractions.useInteractions)([(0, _reactDomInteractions.useHover)(context, {
    restMs: 100,
    enabled: trigger === 'hover',
    delay: {
      open: props.mouseEnterDelay,
      close: props.mouseLeaveDelay
    }
  }), (0, _reactDomInteractions.useClick)(context, {
    enabled: trigger === 'click'
  }), (0, _reactDomInteractions.useFocus)(context, {
    enabled: trigger === 'focus'
  }), (0, _reactDomInteractions.useDismiss)(context, {
    enabled: trigger !== 'manual'
  })]),
      getReferenceProps = _useInteractions.getReferenceProps,
      getFloatingProps = _useInteractions.getFloatingProps;

  var transitionName = (0, _utils.getTransitionName)(prefixCls, directionMap[direction], animationType);
  (0, _react.useEffect)(function () {
    setOpen(isVisible);
  }, [isVisible]);

  var hidden = function hidden() {
    setOpen(false);
  };

  var toolTip = /*#__PURE__*/_react.default.createElement(_transition.default, {
    nodeRef: floating,
    duration: animationDuration,
    visible: open,
    onLeaveEnd: hidden,
    tranisitionName: transitionName,
    destroy: destroy
  }, function (_ref3, setNodeRef) {
    var style = _ref3.style,
        className = _ref3.className;
    return (0, _dom.renderToContainer)(mountContainer !== null && mountContainer !== void 0 ? mountContainer : globalMountContainer, /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({}, getFloatingProps({
      ref: setNodeRef,
      className: bem([(0, _defineProperty2.default)({}, "".concat(direction), true), props.className, className]),
      style: _objectSpread(_objectSpread(_objectSpread({}, props.style), style), {}, {
        position: strategy,
        top: y !== null && y !== void 0 ? y : 0,
        left: x !== null && x !== void 0 ? x : 0,
        // animationDuration: `${animationDuration}ms`,
        transformOrigin: (0, _utils.getTransformOrigin)(context.placement),
        WebkitTransformOrigin: (0, _utils.getTransformOrigin)(context.placement)
      })
    }), {
      "data-popper-placement": context.placement
    }), /*#__PURE__*/_react.default.createElement("div", {
      className: bem('content')
    }, content, hasArrow && /*#__PURE__*/_react.default.createElement("span", {
      className: bem('arrow'),
      ref: arrowRef,
      style: computeArrowStyle(context)
    }))));
  });

  var newRef = (0, _react.useMemo)(function () {
    return (0, _mergeRefs.default)([reference, children.ref]);
  }, [reference, children]);
  var child = /*#__PURE__*/_react.default.isValidElement(children) ? children : /*#__PURE__*/_react.default.createElement("span", null, children);

  var childrenProps = _objectSpread(_objectSpread({}, children && children.props), trigger === 'contextMenu' && {
    onContextMenu: function onContextMenu(e) {
      e.preventDefault();
      setOpen(true);
    }
  });

  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, toolTip, /*#__PURE__*/(0, _react.cloneElement)(child, getReferenceProps(_objectSpread({
    ref: newRef
  }, childrenProps))));
});
Popper.defaultProps = {
  hasArrow: false,
  destroy: false,
  arrowPointAtCenter: false,
  trigger: (_dom.canUseDOM && /(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent) ? 'click' : 'hover') || 'click',
  direction: 'top',
  mouseEnterDelay: 150,
  mouseLeaveDelay: 100,
  visible: false,
  animationType: 'zoom-fade',
  onVisibleChange: function onVisibleChange() {}
};
var _default = Popper;
exports.default = _default;