"use strict";

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

var _typeof = require("@babel/runtime/helpers/typeof");

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

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

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

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

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

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

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

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

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

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _box = _interopRequireDefault(require("../box"));

var _Transition = _interopRequireDefault(require("react-transition-group/Transition"));

var _classnames = _interopRequireDefault(require("classnames"));

var _lodash = _interopRequireDefault(require("lodash.omit"));

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

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

var _DocumentObjectProvider = _interopRequireWildcard(require("../hoc/DocumentObjectProvider"));

var _theme = _interopRequireDefault(require("./theme.css"));

var _uiUtilities = _interopRequireDefault(require("@teamleader/ui-utilities"));

var _excluded = ["children", "className", "tooltip", "tooltipColor", "tooltipIcon", "tooltipSize", "tooltipShowDelay", "zIndex", "onClick", "onMouseEnter", "onMouseLeave", "tooltipActive"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var POSITIONS = {
  BOTTOM: 'bottom',
  HORIZONTAL: 'horizontal',
  LEFT: 'left',
  RIGHT: 'right',
  TOP: 'top',
  VERTICAL: 'vertical'
};
var SIZES = {
  large: {
    padding: 4
  },
  medium: {
    padding: 3
  },
  small: {
    paddingHorizontal: 3,
    paddingVertical: 2
  }
};
/** @type {(component: React.ComponentType<any>) => React.ComponentType<any>} */

var Tooltip = function Tooltip(ComposedComponent) {
  var TooltippedComponent = /*#__PURE__*/function (_Component) {
    (0, _inherits2.default)(TooltippedComponent, _Component);

    var _super = _createSuper(TooltippedComponent);

    function TooltippedComponent() {
      var _this;

      (0, _classCallCheck2.default)(this, TooltippedComponent);

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      _this = _super.call.apply(_super, [this].concat(args));
      (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "tooltipRoot", _this.props.documentObject.createElement('div'));
      (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "ref", /*#__PURE__*/_react.default.createRef());
      (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "state", {
        active: false,
        position: _this.props.tooltipPosition
      });
      (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleMouseEnter", function (event) {
        _this.activate(_this.calculatePosition(event.currentTarget));

        if (_this.props.onMouseEnter) {
          _this.props.onMouseEnter(event);
        }
      });
      (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleMouseLeave", function (event) {
        _this.deactivate();

        if (_this.props.onMouseLeave) {
          _this.props.onMouseLeave(event);
        }
      });
      (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleClick", function (event) {
        if (_this.props.tooltipHideOnClick && _this.state.active) {
          _this.deactivate();
        }

        if (_this.props.tooltipShowOnClick && !_this.state.active) {
          _this.activate(_this.calculatePosition(event.currentTarget));
        }

        if (_this.props.onClick) {
          _this.props.onClick(event);
        }
      });
      (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleTransitionExited", function () {
        _this.props.documentObject.body.removeChild(_this.tooltipRoot);
      });
      (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleTransitionEntered", function () {
        var onTooltipEntered = _this.props.onTooltipEntered;
        onTooltipEntered && onTooltipEntered();
      });
      return _this;
    }

    (0, _createClass2.default)(TooltippedComponent, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        var tooltipActive = this.props.tooltipActive;

        if (tooltipActive) {
          this.activate(this.calculatePosition(this.ref.current));
        }
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(_ref) {
        var prevTooltipActive = _ref.tooltipActive;
        var tooltipActive = this.props.tooltipActive;
        var active = this.state.active;

        if (tooltipActive !== prevTooltipActive) {
          if (tooltipActive && !active) {
            this.activate(this.calculatePosition(this.ref.current));
          }

          if (!tooltipActive && active) {
            this.deactivate();
          }
        }
      }
    }, {
      key: "getPosition",
      value: function getPosition(element) {
        var tooltipPosition = this.props.tooltipPosition;

        if (tooltipPosition === POSITIONS.HORIZONTAL) {
          var origin = element.getBoundingClientRect();

          var _getViewport = (0, _utils.getViewport)(),
              windowWidth = _getViewport.width;

          var toRight = origin.left < windowWidth / 2 - origin.width / 2;
          return toRight ? POSITIONS.RIGHT : POSITIONS.LEFT;
        } else if (tooltipPosition === POSITIONS.VERTICAL) {
          var _origin = element.getBoundingClientRect();

          var _getViewport2 = (0, _utils.getViewport)(),
              windowHeight = _getViewport2.height;

          var toBottom = _origin.top < windowHeight / 2 - _origin.height / 2;
          return toBottom ? POSITIONS.BOTTOM : POSITIONS.TOP;
        }

        return tooltipPosition;
      }
    }, {
      key: "activate",
      value: function activate(_ref2) {
        var top = _ref2.top,
            left = _ref2.left,
            position = _ref2.position;
        this.props.documentObject.body.appendChild(this.tooltipRoot);
        this.setState({
          active: true,
          top: top,
          left: left,
          position: position
        });
      }
    }, {
      key: "deactivate",
      value: function deactivate() {
        this.setState({
          active: false
        });
      }
    }, {
      key: "calculatePosition",
      value: function calculatePosition(element) {
        var tooltipPosition = this.props.tooltipPosition;

        if (typeof element.getBoundingClientRect !== 'function') {
          return {
            top: 0,
            left: 0,
            position: tooltipPosition
          };
        }

        var _element$getBoundingC = element.getBoundingClientRect(),
            top = _element$getBoundingC.top,
            left = _element$getBoundingC.left,
            height = _element$getBoundingC.height,
            width = _element$getBoundingC.width;

        var position = this.getPosition(element);
        var xOffset = window.scrollX || window.pageXOffset;
        var yOffset = window.scrollY || window.pageYOffset;

        if (position === POSITIONS.BOTTOM) {
          return {
            top: top + height + yOffset,
            left: left + width / 2 + xOffset,
            position: position
          };
        } else if (position === POSITIONS.TOP) {
          return {
            top: top + yOffset,
            left: left + width / 2 + xOffset,
            position: position
          };
        } else if (position === POSITIONS.LEFT) {
          return {
            top: top + height / 2 + yOffset,
            left: left + xOffset,
            position: position
          };
        } else if (position === POSITIONS.RIGHT) {
          return {
            top: top + height / 2 + yOffset,
            left: left + width + xOffset,
            position: position
          };
        }
      }
    }, {
      key: "render",
      value: function render() {
        var _this$state = this.state,
            active = _this$state.active,
            left = _this$state.left,
            top = _this$state.top,
            position = _this$state.position;
        var _this$props = this.props,
            children = _this$props.children,
            className = _this$props.className,
            tooltip = _this$props.tooltip,
            tooltipColor = _this$props.tooltipColor,
            tooltipIcon = _this$props.tooltipIcon,
            tooltipSize = _this$props.tooltipSize,
            tooltipShowDelay = _this$props.tooltipShowDelay,
            zIndex = _this$props.zIndex,
            onClick = _this$props.onClick,
            onMouseEnter = _this$props.onMouseEnter,
            onMouseLeave = _this$props.onMouseLeave,
            tooltipActive = _this$props.tooltipActive,
            other = (0, _objectWithoutProperties2.default)(_this$props, _excluded);
        var rest = (0, _lodash.default)(other, ['onTooltipEntered', 'tooltipHideOnClick', 'tooltipPosition', 'tooltipShowOnClick', 'tooltipShowDelay', 'documentObject']);

        var childProps = _objectSpread(_objectSpread({}, rest), {}, {
          className: className,
          onClick: onClick,
          onMouseEnter: onMouseEnter,
          onMouseLeave: onMouseLeave,
          ref: this.ref
        });

        if (tooltipActive === null) {
          childProps = _objectSpread(_objectSpread({}, childProps), {}, {
            onClick: this.handleClick,
            onMouseEnter: this.handleMouseEnter,
            onMouseLeave: this.handleMouseLeave
          });
        }

        return /*#__PURE__*/_react.default.createElement(ComposedComponent, childProps, children, /*#__PURE__*/(0, _reactDom.createPortal)( /*#__PURE__*/_react.default.createElement(_Transition.default, {
          in: active,
          onExited: this.handleTransitionExited,
          onEntered: this.handleTransitionEntered,
          timeout: {
            enter: tooltipShowDelay,
            exit: 1000
          }
        }, function (state) {
          var _cx;

          var classNames = (0, _classnames.default)(_uiUtilities.default['box-shadow-200'], _theme.default['tooltip'], _theme.default[tooltipColor], _theme.default[tooltipSize], (_cx = {}, (0, _defineProperty2.default)(_cx, _theme.default['is-entering'], state === 'entering'), (0, _defineProperty2.default)(_cx, _theme.default['is-entered'], state === 'entered'), (0, _defineProperty2.default)(_cx, _theme.default['is-exiting'], state === 'exiting'), (0, _defineProperty2.default)(_cx, _theme.default[position], _theme.default[position]), _cx));
          return /*#__PURE__*/_react.default.createElement("div", {
            className: classNames,
            "data-teamleader-ui": "tooltip",
            style: {
              top: top,
              left: left,
              zIndex: zIndex
            }
          }, /*#__PURE__*/_react.default.createElement(_box.default, (0, _extends2.default)({
            className: _theme.default['inner']
          }, SIZES[tooltipSize]), tooltipIcon && /*#__PURE__*/_react.default.createElement("div", {
            className: _theme.default['icon']
          }, tooltipIcon), /*#__PURE__*/_react.default.createElement("div", {
            className: _theme.default['text']
          }, tooltip)));
        }), this.tooltipRoot));
      }
    }]);
    return TooltippedComponent;
  }(_react.Component);

  TooltippedComponent.defaultProps = {
    className: '',
    tooltipColor: 'white',
    tooltipHideOnClick: true,
    tooltipIcon: null,
    tooltipPosition: POSITIONS.TOP,
    tooltipShowOnClick: false,
    tooltipSize: 'medium',
    tooltipShowDelay: 100,
    zIndex: 700,
    tooltipActive: null
  };
  return (0, _DocumentObjectProvider.default)(function (props) {
    return /*#__PURE__*/_react.default.createElement(_DocumentObjectProvider.Context.Consumer, null, function (documentObject) {
      return /*#__PURE__*/_react.default.createElement(TooltippedComponent, (0, _extends2.default)({}, props, {
        documentObject: documentObject
      }));
    });
  });
};

var _default = Tooltip;
exports.default = _default;