'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiToolTip = exports.DELAY = exports.POSITIONS = 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 _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _portal = require('../portal');

var _tool_tip_popover = require('./tool_tip_popover');

var _services = require('../../services');

var _make_id = require('../form/form_row/make_id');

var _make_id2 = _interopRequireDefault(_make_id);

var _mutation_observer = require('../mutation_observer');

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 positionsToClassNameMap = {
  top: 'euiToolTip--top',
  right: 'euiToolTip--right',
  bottom: 'euiToolTip--bottom',
  left: 'euiToolTip--left'
};

var POSITIONS = exports.POSITIONS = Object.keys(positionsToClassNameMap);

var delayToClassNameMap = {
  regular: null,
  long: 'euiToolTip--delayLong'
};

var DELAY = exports.DELAY = Object.keys(delayToClassNameMap);

var DEFAULT_TOOLTIP_STYLES = {
  // position the tooltip content near the top-left
  // corner of the window so it can't create scrollbars
  // 50,50 because who knows what negative margins, padding, etc
  top: 50,
  left: 50,
  // just in case, avoid any potential flicker by hiding
  // the tooltip before it is positioned
  opacity: 0
};

var EuiToolTip = exports.EuiToolTip = function (_Component) {
  _inherits(EuiToolTip, _Component);

  function EuiToolTip(props) {
    _classCallCheck(this, EuiToolTip);

    var _this = _possibleConstructorReturn(this, (EuiToolTip.__proto__ || Object.getPrototypeOf(EuiToolTip)).call(this, props));

    _this.testAnchor = function () {
      // when the tooltip is visible, this checks if the anchor is still part of document
      // this fixes when the react root is removed from the dom without unmounting
      // https://github.com/elastic/eui/issues/1105
      if (document.body.contains(_this.anchor) === false) {
        // the anchor is no longer part of `document`
        _this.hideToolTip();
      } else {
        if (_this.state.visible) {
          // if still visible, keep checking
          requestAnimationFrame(_this.testAnchor);
        }
      }
    };

    _this.setPopoverRef = function (ref) {
      _this.popover = ref;

      // if the popover has been unmounted, clear
      // any previous knowledge about its size
      if (ref == null) {
        _this.setState({
          toolTipStyles: DEFAULT_TOOLTIP_STYLES,
          arrowStyles: {}
        });
      }
    };

    _this.showToolTip = function () {
      _this.setState({ visible: true });
    };

    _this.positionToolTip = function () {
      var requestedPosition = _this.props.position;

      var _findPopoverPosition = (0, _services.findPopoverPosition)({
        anchor: _this.anchor,
        popover: _this.popover,
        position: requestedPosition,
        offset: 16, // offset popover 16px from the anchor
        arrowConfig: {
          arrowWidth: 12,
          arrowBuffer: 4
        }
      }),
          position = _findPopoverPosition.position,
          left = _findPopoverPosition.left,
          top = _findPopoverPosition.top,
          arrow = _findPopoverPosition.arrow;

      var toolTipStyles = {
        top: top,
        left: left
      };

      _this.setState({
        visible: true,
        calculatedPosition: position,
        toolTipStyles: toolTipStyles,
        arrowStyles: arrow
      });
    };

    _this.hideToolTip = function () {
      if (_this._isMounted) {
        _this.setState({ visible: false });
      }
    };

    _this.onFocus = function () {
      _this.setState({
        hasFocus: true
      });
      _this.showToolTip();
    };

    _this.onBlur = function () {
      _this.setState({
        hasFocus: false
      });
      _this.hideToolTip();
    };

    _this.onMouseOut = function (e) {
      // Prevent mousing over children from hiding the tooltip by testing for whether the mouse has
      // left the anchor for a non-child.
      if (_this.anchor === e.relatedTarget || !_this.anchor.contains(e.relatedTarget)) {
        if (!_this.state.hasFocus) {
          _this.hideToolTip();
        }
      }

      if (_this.props.onMouseOut) {
        _this.props.onMouseOut();
      }
    };

    _this.state = {
      visible: false,
      hasFocus: false,
      calculatedPosition: _this.props.position,
      toolTipStyles: DEFAULT_TOOLTIP_STYLES,
      arrowStyles: {},
      id: _this.props.id || (0, _make_id2.default)()
    };
    return _this;
  }

  _createClass(EuiToolTip, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this._isMounted = true;
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this._isMounted = false;
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps, prevState) {
      if (prevState.visible === false && this.state.visible === true) {
        requestAnimationFrame(this.testAnchor);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          children = _props.children,
          className = _props.className,
          anchorClassName = _props.anchorClassName,
          content = _props.content,
          title = _props.title,
          delay = _props.delay,
          rest = _objectWithoutProperties(_props, ['children', 'className', 'anchorClassName', 'content', 'title', 'delay']);

      var _state = this.state,
          arrowStyles = _state.arrowStyles,
          id = _state.id,
          toolTipStyles = _state.toolTipStyles,
          visible = _state.visible;


      var classes = (0, _classnames2.default)('euiToolTip', positionsToClassNameMap[this.state.calculatedPosition], delayToClassNameMap[delay], className);

      var anchorClasses = (0, _classnames2.default)('euiToolTipAnchor', anchorClassName);

      var tooltip = void 0;
      if (visible && (content || title)) {
        tooltip = _react2.default.createElement(
          _portal.EuiPortal,
          null,
          _react2.default.createElement(
            _tool_tip_popover.EuiToolTipPopover,
            _extends({
              className: classes,
              style: toolTipStyles,
              positionToolTip: this.positionToolTip,
              popoverRef: this.setPopoverRef,
              title: title,
              id: id,
              role: 'tooltip'
            }, rest),
            _react2.default.createElement('div', { style: arrowStyles, className: 'euiToolTip__arrow' }),
            _react2.default.createElement(
              _mutation_observer.EuiMutationObserver,
              {
                observerOptions: { subtree: true, childList: true, characterData: true, attributes: true },
                onMutation: this.positionToolTip
              },
              content
            )
          )
        );
      }

      var anchor = _react2.default.createElement(
        'span',
        {
          ref: function ref(anchor) {
            return _this2.anchor = anchor;
          },
          className: anchorClasses,
          onMouseOver: this.showToolTip,
          onMouseOut: this.onMouseOut
        },
        (0, _react.cloneElement)(children, {
          onFocus: this.showToolTip,
          onBlur: this.hideToolTip,
          'aria-describedby': this.state.id
        })
      );

      return _react2.default.createElement(
        _react.Fragment,
        null,
        anchor,
        tooltip
      );
    }
  }]);

  return EuiToolTip;
}(_react.Component);

EuiToolTip.propTypes = {
  /**
   * The in-view trigger for your tooltip.
   */
  children: _propTypes2.default.element.isRequired,
  /**
   * The main content of your tooltip.
   */
  content: _propTypes2.default.node,

  /**
   * An optional title for your tooltip.
   */
  title: _propTypes2.default.node,

  /**
   * Suggested position. If there is not enough room for it this will be changed.
   */
  position: _propTypes2.default.oneOf(POSITIONS),

  /**
   * Delay before showing tooltip. Good for repeatable items.
   */
  delay: _propTypes2.default.oneOf(DELAY),

  /**
   * Passes onto the tooltip itself, not the trigger.
   */
  className: _propTypes2.default.string,

  /**
   * Unless you provide one, this will be randomly generated.
   */
  id: _propTypes2.default.string
};

EuiToolTip.defaultProps = {
  position: 'top',
  delay: 'regular'
};
EuiToolTip.__docgenInfo = [{
  'description': '',
  'displayName': 'EuiToolTip',
  'methods': [{
    'name': 'testAnchor',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'setPopoverRef',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'ref',
      'type': null
    }],
    'returns': null
  }, {
    'name': 'showToolTip',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'positionToolTip',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'hideToolTip',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'onFocus',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'onBlur',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'onMouseOut',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'e',
      'type': null
    }],
    'returns': null
  }],
  'props': {
    'children': {
      'type': {
        'name': 'element'
      },
      'required': true,
      'description': 'The in-view trigger for your tooltip.'
    },
    'content': {
      'type': {
        'name': 'node'
      },
      'required': false,
      'description': 'The main content of your tooltip.'
    },
    'title': {
      'type': {
        'name': 'node'
      },
      'required': false,
      'description': 'An optional title for your tooltip.'
    },
    'position': {
      'type': {
        'name': 'enum',
        'value': [{
          'value': '"top"',
          'computed': false
        }, {
          'value': '"right"',
          'computed': false
        }, {
          'value': '"bottom"',
          'computed': false
        }, {
          'value': '"left"',
          'computed': false
        }]
      },
      'required': false,
      'description': 'Suggested position. If there is not enough room for it this will be changed.',
      'defaultValue': {
        'value': '\'top\'',
        'computed': false
      }
    },
    'delay': {
      'type': {
        'name': 'enum',
        'value': [{
          'value': '"regular"',
          'computed': false
        }, {
          'value': '"long"',
          'computed': false
        }]
      },
      'required': false,
      'description': 'Delay before showing tooltip. Good for repeatable items.',
      'defaultValue': {
        'value': '\'regular\'',
        'computed': false
      }
    },
    'className': {
      'type': {
        'name': 'string'
      },
      'required': false,
      'description': 'Passes onto the tooltip itself, not the trigger.'
    },
    'id': {
      'type': {
        'name': 'string'
      },
      'required': false,
      'description': 'Unless you provide one, this will be randomly generated.'
    }
  }
}];