'use strict';

exports.__esModule = true;
exports.Context = undefined;

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; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _reactPopper = require('react-popper');

var _helper = require('./Shared/helper.js');

var _CFade = require('./CFade');

var _CFade2 = _interopRequireDefault(_CFade);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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; }

var Context = exports.Context = _react2.default.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;
}(_react2.default.Component);

CPopperContentWrapper.contextType = Context;

CPopperContentWrapper.childContextTypes = {
  popperManager: _propTypes2.default.object.isRequired
};

//component - CoreUI / CPopperContent

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

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

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

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

  var getContainerNode = function getContainerNode() {
    return (0, _helper.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
  (0, _react.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();
    }
  });

  (0, _react.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 = (0, _helper.mapToCssModules)((0, _classnames2.default)('arrow', _arrowClassName), cssModule);

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

    var popperClassName = (0, _helper.mapToCssModules)((0, _classnames2.default)(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 _react2.default.createElement(
      Context.Provider,
      { value: { popperManager: {
            setTargetNode: setTargetNode,
            getTargetNode: getTargetNode
          } } },
      _react2.default.createElement(
        CPopperContentWrapper,
        null,
        _react2.default.createElement(
          _reactPopper.Popper,
          _extends({ modifiers: extendedModifiers }, attributes, { component: tag, className: popperClassName, 'x-placement': placement || attributes.placement }),
          children,
          !hideArrow && _react2.default.createElement(_reactPopper.Arrow, { className: arrowClassName })
        )
      )
    );
  };

  setTargetNode((0, _helper.getTarget)(props.target));

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

  return null;
};

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

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

exports.default = CPopperContent;