"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;exports.__esModule = true;exports.TooltipDataTids = exports.Tooltip = void 0;var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));var _react = _interopRequireDefault(require("react"));
var _warning = _interopRequireDefault(require("warning"));

var _globalObject = require("@skbkontur/global-object");


var _utils = require("../../lib/utils");
var _ThemeFactory = require("../../lib/theming/ThemeFactory");

var _Popup = require("../../internal/Popup");

var _RenderLayer = require("../../internal/RenderLayer");


var _listenFocusOutside = require("../../lib/listenFocusOutside");
var _ThemeContext = require("../../lib/theming/ThemeContext");

var _currentEnvironment = require("../../lib/currentEnvironment");

var _CommonWrapper = require("../../internal/CommonWrapper");

var _rootNode = require("../../lib/rootNode");

var _createPropsGetter = require("../../lib/createPropsGetter");
var _CloseButtonIcon = require("../../internal/CloseButtonIcon/CloseButtonIcon");
var _isInstanceOf = require("../../lib/isInstanceOf");

var _featureFlagsContext = require("../../lib/featureFlagsContext");
var _Emotion = require("../../lib/theming/Emotion");
var _ThemeHelpers = require("../../lib/theming/ThemeHelpers");
var _SizeDecorator = require("../../lib/size/SizeDecorator");

var _Tooltip2 = require("./Tooltip.styles");var _class, _Tooltip;











































































var DEFAULT_DELAY = 100;






var TooltipDataTids = exports.TooltipDataTids = {
  root: 'Tooltip__root',
  content: 'Tooltip__content',
  crossIcon: 'Tooltip__crossIcon'
};

var DefaultPositions = [
'right bottom',
'right middle',
'right top',
'top right',
'top center',
'top left',
'left top',
'left middle',
'left bottom',
'bottom left',
'bottom center',
'bottom right'];














/**
 * `Tooltip` — это подсказка, которая объясняет состояние контрола или даёт контекстную справку.
 *
 * Открывается по клику, фокусом на элемент или по наведению. В отличие от `Hint`, `Tooltip` может содержать
 * изображения, кнопки, ссылки и прочие интерактивные элементы.
 */var



Tooltip = exports.Tooltip = (0, _rootNode.rootNode)(_class = (0, _SizeDecorator.withSize)(_class = (_Tooltip = /*#__PURE__*/function (_React$PureComponent) {function Tooltip() {var _this;for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}_this = _React$PureComponent.call.apply(_React$PureComponent, [this].concat(args)) || this;_this.










    getProps = (0, _createPropsGetter.createPropsGetter)(Tooltip.defaultProps);_this.










    state = { opened: false, focused: false };_this.





    contentElement = null;_this.
    clickedOutside = true;_this.



    popupRef = /*#__PURE__*/_react.default.createRef();_this.


























































    renderContent = function () {
      var content = _this.props.render ? _this.props.render() : null;
      if ((0, _utils.isNullable)(content)) {
        return null;
      }

      return /*#__PURE__*/(
        _react.default.createElement("div", {
          ref: _this.refContent,
          className: (0, _Emotion.cx)(_Tooltip2.styles.tooltipContent(_this.theme), _this.sizeVariables.contentStyle),
          "data-tid": TooltipDataTids.content },

        content,
        _this.renderCloseButton()
        ));

    };_this.































    getAnchorElement = function () {var _this$popupRef$curren;
      return (_this$popupRef$curren = _this.popupRef.current) == null ? void 0 : _this$popupRef$curren.anchorElement;
    };_this.














































































    getPositions = function () {return (
        _this.props.allowedPositions ?
        _this.props.allowedPositions.filter(function (item) {return DefaultPositions.includes(item);}) :
        DefaultPositions);};_this.

    refContent = function (node) {
      _this.contentElement = node;
    };_this.






















































































    open = function () {return _this.setState({ opened: true });};_this.

    close = function () {return _this.setState({ opened: false });};_this.








    handleMouseEnter = function (event) {
      var isHoverAnchor = _this.getProps().trigger === 'hoverAnchor';
      if (isHoverAnchor && event.target === _this.contentElement) {
        return;
      }

      _this.clearHoverTimeout();
      _this.hoverTimeout = _globalObject.globalObject.setTimeout(_this.open, _this.getProps().delayBeforeShow);
    };_this.

    handleMouseLeave = function (event) {
      var trigger = _this.getProps().trigger;
      if (
      trigger === 'hover&focus' && _this.state.focused ||
      trigger === 'hover' && event.relatedTarget === _this.contentElement)
      {
        return;
      }

      _this.clearHoverTimeout();

      if (trigger === 'hoverAnchor') {
        _this.close();
      } else {
        _this.hoverTimeout = _globalObject.globalObject.setTimeout(_this.close, Tooltip.delay);
      }
    };_this.

    handleClick = function () {
      _this.open();
    };_this.

    handleClickOutsideAnchor = function (event) {
      _this.clickedOutside = _this.isClickOutsideContent(event);
      if (_this.clickedOutside) {
        if (_this.props.onCloseRequest) {
          _this.props.onCloseRequest(event);
        }
        _this.close();
      }
    };_this.









    handleFocus = function () {
      _this.setState({ focused: true });
      _this.open();
    };_this.

    handleBlur = function () {
      var trigger = _this.getProps().trigger;
      if (trigger === 'hover&focus' && _this.clickedOutside) {
        _this.close();
      }

      if (trigger === 'focus') {
        _this.close();
      }

      _this.clickedOutside = true;
      _this.setState({ focused: false });
    };_this.

    handleCloseButtonClick = function (event) {
      event.stopPropagation();

      if (_this.props.onCloseClick) {
        _this.props.onCloseClick(event);
      }

      if (event.defaultPrevented) {
        return;
      }

      if (_this.props.onCloseRequest) {
        _this.props.onCloseRequest(event);
      }

      _this.close();
    };_this.

    getSizeVariables = function () {
      switch (_this.size) {
        case 'small':
          return {
            closeButtonStyle: _Tooltip2.styles.closeButtonSmall(_this.theme),
            contentStyle: _Tooltip2.styles.tooltipContentSmall(_this.theme),
            borderRadius: _this.theme.tooltipBorderRadiusSmall,
            pinSize: _this.theme.tooltipPinSizeSmall,
            pinOffsetX: _this.theme.tooltipPinOffsetXSmall,
            pinOffsetY: _this.theme.tooltipPinOffsetYSmall,
            margin: _this.theme.tooltipMarginSmall
          };
        case 'medium':
          return {
            closeButtonStyle: _Tooltip2.styles.closeButtonMedium(_this.theme),
            contentStyle: _Tooltip2.styles.tooltipContentMedium(_this.theme),
            borderRadius: _this.theme.tooltipBorderRadiusMedium,
            pinSize: _this.theme.tooltipPinSizeMedium,
            pinOffsetX: _this.theme.tooltipPinOffsetXMedium,
            pinOffsetY: _this.theme.tooltipPinOffsetYMedium,
            margin: _this.theme.tooltipMarginMedium
          };
        case 'large':
          return {
            closeButtonStyle: _Tooltip2.styles.closeButtonLarge(_this.theme),
            contentStyle: _Tooltip2.styles.tooltipContentLarge(_this.theme),
            borderRadius: _this.theme.tooltipBorderRadiusLarge,
            pinSize: _this.theme.tooltipPinSizeLarge,
            pinOffsetX: _this.theme.tooltipPinOffsetXLarge,
            pinOffsetY: _this.theme.tooltipPinOffsetYLarge,
            margin: _this.theme.tooltipMarginLarge
          };
        default:
          console.error("Can't get size variables: invalid value in size prop '" + _this.size + "'. Returning default");
          return {
            closeButtonStyle: _Tooltip2.styles.closeButtonSmall(_this.theme),
            contentStyle: _Tooltip2.styles.tooltipContentSmall(_this.theme),
            borderRadius: _this.theme.tooltipBorderRadiusSmall,
            pinSize: _this.theme.tooltipPinSizeSmall,
            pinOffsetX: _this.theme.tooltipPinOffsetXSmall,
            pinOffsetY: _this.theme.tooltipPinOffsetYSmall,
            margin: _this.theme.tooltipMarginSmall
          };
      }
    };return _this;}(0, _inheritsLoose2.default)(Tooltip, _React$PureComponent);var _proto = Tooltip.prototype;_proto.validateProps = function validateProps(props) {(0, _warning.default)(props.children || props.anchorElement, "[Tooltip]: you must provide either 'children' or 'anchorElement' prop for Tooltip to work properly");};_proto.getAllowedPositions = function getAllowedPositions() {return this.props.allowedPositions ? this.props.allowedPositions : DefaultPositions;};_proto.componentDidMount = function componentDidMount() {this.validateProps(this.getProps());};_proto.componentDidUpdate = function componentDidUpdate() {var _this$getProps = this.getProps(),trigger = _this$getProps.trigger;this.validateProps(this.getProps());if (trigger === 'closed' && this.state.opened) {this.close();}};_proto.componentWillUnmount = function componentWillUnmount() {this.clearHoverTimeout();};_proto.render = function render() {var _this2 = this;return /*#__PURE__*/_react.default.createElement(_featureFlagsContext.ReactUIFeatureFlagsContext.Consumer, null, function (flags) {_this2.featureFlags = (0, _featureFlagsContext.getFullReactUIFlagsContext)(flags);return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Consumer, null, function (theme) {_this2.theme = theme;_this2.sizeVariables = _this2.getSizeVariables();return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Provider, { value: _ThemeFactory.ThemeFactory.create({ popupBackground: theme.tooltipBg, popupBorder: theme.tooltipBorder, popupBorderRadius: _this2.sizeVariables.borderRadius, popupPinSize: _this2.sizeVariables.pinSize, popupPinOffsetX: _this2.sizeVariables.pinOffsetX, popupPinOffsetY: _this2.sizeVariables.pinOffsetY, popupMargin: _this2.sizeVariables.margin }, theme) }, _this2.renderMain());});});};_proto.renderCloseButton = function renderCloseButton() {var hasCross = this.props.closeButton === undefined ? !Tooltip.triggersWithoutCloseButton.includes(this.getProps().trigger) : this.props.closeButton;if (!hasCross) {return null;}var icon = /*#__PURE__*/_react.default.createElement(_CloseButtonIcon.CloseButtonIcon, { tabbable: false, side: parseInt(this.theme.tooltipCloseBtnSide), color: this.theme.tooltipCloseBtnColor, colorHover: this.theme.tooltipCloseBtnHoverColor });return /*#__PURE__*/_react.default.createElement("div", { className: (0, _Emotion.cx)(_Tooltip2.styles.closeButton(this.theme), this.sizeVariables.closeButtonStyle), onClick: this.handleCloseButtonClick, "data-tid": TooltipDataTids.crossIcon }, icon);}; /**
   * Программно открывает тултип.
   * <p>Не действует если проп *trigger* `'opened'` или `'closed'`.</p>
   * @public
   */_proto.show = function show() {if (this.state.opened) {return;}var trigger = this.getProps().trigger;if (trigger === 'opened' || trigger === 'closed') {(0, _warning.default)(true, "Function 'show' is not supported with trigger specified '" + trigger + "'");return;}this.open();} /**
   * Программно закрывает тултип.
   * <p>Не действует если проп *trigger* `'opened'` или `'closed'`.</p>
   * @public
   */;_proto.hide = function hide() {var trigger = this.getProps().trigger;if (trigger === 'opened' || trigger === 'closed') {(0, _warning.default)(true, "Function 'hide' is not supported with trigger specified '" + trigger + "'");return;}this.close();};_proto.renderMain = function renderMain() {var props = this.props;var content = this.renderContent();var _this$getPopupAndLaye = this.getPopupAndLayerProps(),popupProps = _this$getPopupAndLaye.popupProps,_this$getPopupAndLaye2 = _this$getPopupAndLaye.layerProps,layerProps = _this$getPopupAndLaye2 === void 0 ? { active: false } : _this$getPopupAndLaye2;var anchorElement = props.children || props.anchorElement;var popup = this.renderPopup(anchorElement, popupProps, content);return /*#__PURE__*/_react.default.createElement(_RenderLayer.RenderLayer, (0, _extends2.default)({}, layerProps, { getAnchorElement: this.getAnchorElement }), popup);};_proto.renderPopup = function renderPopup(anchorElement, popupProps, content) {var _this$getProps2 = this.getProps(),disableAnimations = _this$getProps2.disableAnimations,trigger = _this$getProps2.trigger;return /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, (0, _extends2.default)({ rootNodeRef: this.setRootNode }, this.props), /*#__PURE__*/_react.default.createElement(_Popup.Popup, (0, _extends2.default)({ "data-tid": TooltipDataTids.root, anchorElement: anchorElement, hasPin: true, hasShadow: true, maxWidth: "none", opened: this.state.opened, disableAnimations: disableAnimations, positions: (0, _ThemeHelpers.isThemeGTE)(this.theme, '5.4') ? this.getPositions() : this.props.allowedPositions, pos: this.props.pos, ignoreHover: trigger === 'hoverAnchor', onOpen: this.props.onOpen, onClose: this.props.onClose, tryPreserveFirstRenderedPosition: true, ref: this.popupRef, withoutMobile: true }, popupProps), content));};_proto.getPopupAndLayerProps = function getPopupAndLayerProps() {var props = this.props;var useWrapper = !!props.children && this.getProps().useWrapper;var trigger = this.getProps().trigger;switch (trigger) {case 'opened':return { layerProps: { active: true, onClickOutside: this.handleClickOutsideAnchor }, popupProps: { opened: true, useWrapper: useWrapper } };case 'closed':return { popupProps: { opened: false, useWrapper: useWrapper } };case 'hoverAnchor':case 'hover':return { popupProps: { onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave, useWrapper: useWrapper } };case 'manual':return { popupProps: { useWrapper: useWrapper } };case 'click':return { layerProps: { active: this.state.opened, onClickOutside: this.handleClickOutsideAnchor }, popupProps: { onClick: this.handleClick, useWrapper: useWrapper } };case 'focus':return { popupProps: { onFocus: this.handleFocus, onBlur: this.handleBlur, useWrapper: useWrapper } };case 'hover&focus':return { layerProps: { active: this.state.opened, onClickOutside: this.handleClickOutsideAnchor }, popupProps: { onFocus: this.handleFocus, onBlur: this.handleBlur, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave, useWrapper: useWrapper } };default:throw new Error('Unknown trigger specified: ' + trigger);}};_proto.clearHoverTimeout = function clearHoverTimeout() {if (this.hoverTimeout) {_globalObject.globalObject.clearTimeout(this.hoverTimeout);this.hoverTimeout = null;}};_proto.isClickOutsideContent = function isClickOutsideContent(event) {if (this.contentElement && (0, _isInstanceOf.isInstanceOf)(event.target, _globalObject.globalObject.Element)) {return !(0, _listenFocusOutside.containsTargetOrRenderContainer)(event.target)(this.contentElement);}return true;};return Tooltip;}(_react.default.PureComponent), _Tooltip.__KONTUR_REACT_UI__ = 'Tooltip', _Tooltip.displayName = 'Tooltip', _Tooltip.defaultProps = { trigger: 'hover', disableAnimations: _currentEnvironment.isTestEnv, useWrapper: false, delayBeforeShow: DEFAULT_DELAY }, _Tooltip.delay = DEFAULT_DELAY, _Tooltip.triggersWithoutCloseButton = ['hover', 'hoverAnchor', 'focus', 'hover&focus'], _Tooltip)) || _class) || _class;