var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import { Arrow, Popper as ReactPopper } from 'react-popper';
import { getTarget, targetPropType, mapToCssModules, DOMElement, tagPropType } from './Shared/helper.js';
import CFade from './CFade';

export var Context = React.createContext({});

//component - CoreUI / CPopperContentWrapper

var CPopperContentWrapper = function (_React$Component) {
  _inherits(CPopperContentWrapper, _React$Component);

  function CPopperContentWrapper() {
    _classCallCheck(this, CPopperContentWrapper);

    return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
  }

  CPopperContentWrapper.prototype.getChildContext = function getChildContext() {
    return this.context;
  };

  CPopperContentWrapper.prototype.render = function render() {
    return this.props.children;
  };

  return CPopperContentWrapper;
}(React.Component);

CPopperContentWrapper.contextType = Context;

CPopperContentWrapper.childContextTypes = {
  popperManager: PropTypes.object.isRequired
};

//component - CoreUI / CPopperContent

var CPopperContent = function CPopperContent(props) {
  var _useState = useState(),
      placement = _useState[0],
      setPlacement = _useState[1];

  var fields = useRef({
    firstRender: true
  }).current;

  var setTargetNode = function setTargetNode(node) {
    fields.targetNode = node;
  };

  var getTargetNode = function getTargetNode() {
    return fields.targetNode;
  };

  var getContainerNode = function getContainerNode() {
    return getTarget(props.container);
  };

  var getRef = function getRef(ref) {
    fields._element = ref;
    props.innerRef && props.innerRef();
  };

  var handlePlacementChange = function handlePlacementChange(data) {
    if (placement !== data.placement) {
      setPlacement(data.placement);
    }
    return data;
  };

  //effect - update
  useEffect(function () {
    if (fields.firstRender) return;
    if (fields._element && fields._element.childNodes && fields._element.childNodes[0] && fields._element.childNodes[0].focus) {
      fields._element.childNodes[0].focus();
    }
  });

  useEffect(function () {
    fields.firstRender = false;
  }, []);

  //render

  var renderChildren = function renderChildren() {
    var tag = props.tag,
        children = props.children,
        className = props.className,
        cssModule = props.cssModule,
        innerRef = props.innerRef,
        show = props.show,
        flip = props.flip,
        target = props.target,
        offset = props.offset,
        fallbackPlacement = props.fallbackPlacement,
        placementPrefix = props.placementPrefix,
        _arrowClassName = props.arrowClassName,
        hideArrow = props.hideArrow,
        container = props.container,
        modifiers = props.modifiers,
        boundariesElement = props.boundariesElement,
        attributes = _objectWithoutProperties(props, ['tag', 'children', 'className', 'cssModule', 'innerRef', 'show', 'flip', 'target', 'offset', 'fallbackPlacement', 'placementPrefix', 'arrowClassName', 'hideArrow', 'container', 'modifiers', 'boundariesElement']);

    var arrowClassName = mapToCssModules(classNames('arrow', _arrowClassName), cssModule);

    var placement2 = (placement || attributes.placement).split('-')[0];

    var popperClassName = mapToCssModules(classNames(className, //8 _popperClassName
    placementPrefix ? placementPrefix + '-' + placement2 : placement2), props.cssModule);

    var extendedModifiers = _extends({
      offset: { offset: offset },
      flip: { enabled: flip, behavior: fallbackPlacement },
      preventOverflow: { boundariesElement: boundariesElement },
      update: {
        enabled: true,
        order: 950,
        fn: handlePlacementChange
      }
    }, modifiers);

    return React.createElement(
      Context.Provider,
      { value: { popperManager: {
            setTargetNode: setTargetNode,
            getTargetNode: getTargetNode
          } } },
      React.createElement(
        CPopperContentWrapper,
        null,
        React.createElement(
          ReactPopper,
          _extends({ modifiers: extendedModifiers }, attributes, { component: tag, className: popperClassName, 'x-placement': placement || attributes.placement }),
          children,
          !hideArrow && React.createElement(Arrow, { className: arrowClassName })
        )
      )
    );
  };

  setTargetNode(getTarget(props.target));

  if (props.show) {
    return props.container === 'inline' ? renderChildren() : ReactDOM.createPortal(React.createElement(
      'div',
      { ref: getRef },
      renderChildren()
    ), getContainerNode());
  }

  return null;
};

CPopperContent.propTypes = process.env.NODE_ENV !== "production" ? {
  tag: tagPropType,
  children: PropTypes.node.isRequired,
  className: PropTypes.string,
  cssModule: PropTypes.object,
  //
  innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]),
  placement: PropTypes.string,
  placementPrefix: PropTypes.string,
  arrowClassName: PropTypes.string,
  hideArrow: PropTypes.bool,
  show: PropTypes.bool.isRequired,
  offset: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  fallbackPlacement: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  flip: PropTypes.bool,
  container: targetPropType,
  target: targetPropType.isRequired,
  modifiers: PropTypes.object,
  boundariesElement: PropTypes.oneOfType([PropTypes.string, DOMElement])
} : {};

CPopperContent.defaultProps = {
  boundariesElement: 'scrollParent',
  placement: 'auto',
  hideArrow: false,
  show: false,
  offset: 0,
  fallbackPlacement: 'flip',
  flip: true,
  container: 'body',
  modifiers: {}
};

export default CPopperContent;