"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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

require("core-js/modules/es.object.assign.js");

require("core-js/modules/es.array.find.js");

require("core-js/modules/es.array.iterator.js");

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.promise.finally.js");

require("core-js/modules/es.string.iterator.js");

require("core-js/modules/esnext.aggregate-error.js");

require("core-js/modules/esnext.promise.all-settled.js");

require("core-js/modules/esnext.promise.any.js");

require("core-js/modules/esnext.promise.try.js");

require("core-js/modules/web.dom-collections.iterator.js");

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

var _CSSTransition = _interopRequireDefault(require("react-transition-group/CSSTransition"));

var _focusTrapReact = _interopRequireDefault(require("focus-trap-react"));

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

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

var _core = require("@popperjs/core");

var _uniqueId = _interopRequireDefault(require("lodash/uniqueId"));

var _Button = require("../Button");

var _Icons = require("../Icons");

var _usePrevious = _interopRequireDefault(require("../utilities/usePrevious"));

var _excluded = ["activeClassName", "ariaLabel", "children", "className", "component", "dialog", "offset", "onClose", "onOpen", "inversed", "interactiveBorder", "placement", "maxWidth", "title", "transitionDuration", "zIndex", "showCloseButton", "closeButtonLabel", "contentHeading"];

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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _extends() { _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; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var Tooltip = function Tooltip(props) {
  var _props$id;

  var popper = (0, _react.useRef)(null);
  var id = (0, _react.useRef)((_props$id = props.id) !== null && _props$id !== void 0 ? _props$id : (0, _uniqueId.default)('trigger_'));
  var triggerElement = (0, _react.useRef)(null);
  var tooltipElement = (0, _react.useRef)(null);

  var setTriggerElement = function setTriggerElement(elem) {
    triggerElement.current = elem;
  };

  var setTooltipElement = function setTooltipElement(elem) {
    tooltipElement.current = elem;
  };

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      active = _useState2[0],
      setActive = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      isHover = _useState4[0],
      setIsHover = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      isMobile = _useState6[0],
      setIsMobile = _useState6[1];

  var prevActiveStateVar = (0, _usePrevious.default)(active);

  var handleEscapeKey = function handleEscapeKey(event) {
    var ESCAPE_KEY = 27;

    if (active && event.keyCode === ESCAPE_KEY) {
      setActive(false);
    }
  };

  var handleClickOutside = function handleClickOutside(event) {
    if (active && (props.dialog || isMobile)) {
      var _triggerElement$curre, _tooltipElement$curre;

      var clickedTrigger = (_triggerElement$curre = triggerElement.current) === null || _triggerElement$curre === void 0 ? void 0 : _triggerElement$curre.contains(event.target);
      var clickedTooltip = (_tooltipElement$curre = tooltipElement.current) === null || _tooltipElement$curre === void 0 ? void 0 : _tooltipElement$curre.contains(event.target);

      if (!clickedTooltip && !clickedTrigger) {
        setActive(false);
      }
    }
  };

  var handleCloseButtonClick = function handleCloseButtonClick() {
    if (active && (props.dialog || isMobile)) {
      setActive(false);
    }
  };

  var handleBlur = function handleBlur(event) {
    setTimeout(function () {
      var _triggerElement$curre2, _tooltipElement$curre2;

      var focusedInsideTrigger = (_triggerElement$curre2 = triggerElement.current) === null || _triggerElement$curre2 === void 0 ? void 0 : _triggerElement$curre2.contains(event.target);
      var focusedInsideTooltip = (_tooltipElement$curre2 = tooltipElement.current) === null || _tooltipElement$curre2 === void 0 ? void 0 : _tooltipElement$curre2.contains(event.target);

      if (!focusedInsideTrigger && !focusedInsideTooltip && !isHover) {
        setActive(false);
      }
    }, 10);
  };

  var handleTouch = function handleTouch() {
    // On mobile, touch -> mouseenter -> click events can all be fired simultaneously
    // `isMobile` flag is used inside onClick and onMouseEnter handlers, so touch events can be used in isolation on mobile
    // https://stackoverflow.com/a/65055198
    setIsMobile(true);
    setActive(!active);
  };

  (0, _react.useEffect)(function () {
    if (!triggerElement.current || !tooltipElement.current) return;
    popper.current = (0, _core.createPopper)(triggerElement.current, tooltipElement.current, {
      placement: props.placement,
      modifiers: [{
        name: 'offset',
        options: {
          offset: props.offset
        }
      }]
    });
    return function () {
      if (popper.current) popper.current.destroy();
    };
  }, []);
  (0, _react.useEffect)(function () {
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleEscapeKey);
    return function () {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleEscapeKey);
    };
  }, [handleClickOutside, handleEscapeKey]);
  (0, _react.useEffect)(function () {
    if (active) {
      props.onOpen && props.onOpen();
    } else {
      props.onClose && props.onClose(); // if tooltip goes from active to inactive and is the dialog version, focus the trigger

      if (prevActiveStateVar && (props.dialog || isMobile) && props.showCloseButton) {
        if (triggerElement && triggerElement.current) {
          triggerElement.current.focus();
        }
      }
    }
  }, [active]);
  (0, _react.useLayoutEffect)(function () {
    if (popper.current) {
      popper.current.setOptions(props);
      popper.current.forceUpdate();
    }
  });

  var renderTrigger = function renderTrigger(props) {
    var _classNames;

    var activeClassName = props.activeClassName,
        ariaLabel = props.ariaLabel,
        children = props.children,
        className = props.className,
        component = props.component,
        dialog = props.dialog,
        offset = props.offset,
        onClose = props.onClose,
        onOpen = props.onOpen,
        inversed = props.inversed,
        interactiveBorder = props.interactiveBorder,
        placement = props.placement,
        maxWidth = props.maxWidth,
        title = props.title,
        transitionDuration = props.transitionDuration,
        zIndex = props.zIndex,
        showCloseButton = props.showCloseButton,
        closeButtonLabel = props.closeButtonLabel,
        contentHeading = props.contentHeading,
        others = _objectWithoutProperties(props, _excluded);

    var TriggerComponent = component;
    var triggerClasses = (0, _classnames.default)('ds-base', 'ds-c-tooltip__trigger', className, (_classNames = {}, _defineProperty(_classNames, activeClassName, activeClassName && active), _defineProperty(_classNames, 'ds-c-tooltip__trigger--inverse', inversed), _classNames));
    var linkTriggerOverrides = {
      tabIndex: TriggerComponent === 'a' ? 0 : undefined
    };
    var eventHandlers = dialog ? {
      onTouchStart: function onTouchStart() {
        return handleTouch();
      },
      onClick: function onClick() {
        if (!isMobile) {
          setActive(!active);
        }
      }
    } : {
      onTouchStart: function onTouchStart() {
        return handleTouch();
      },
      onClick: function onClick() {
        if (!isMobile) {
          setActive(!active);
        }
      },
      onFocus: function onFocus() {
        return setActive(true);
      },
      onBlur: function onBlur(event) {
        return handleBlur(event);
      }
    };
    return /*#__PURE__*/_react.default.createElement(TriggerComponent, _extends({
      type: TriggerComponent === 'button' ? 'button' : undefined,
      "aria-label": ariaLabel || undefined,
      "aria-describedby": dialog ? undefined : id.current,
      className: triggerClasses,
      ref: setTriggerElement
    }, others, linkTriggerOverrides, eventHandlers), children);
  };

  var renderContent = function renderContent(props) {
    var closeButtonLabel = props.closeButtonLabel,
        dialog = props.dialog,
        contentHeading = props.contentHeading,
        inversed = props.inversed,
        interactiveBorder = props.interactiveBorder,
        placement = props.placement,
        maxWidth = props.maxWidth,
        showCloseButton = props.showCloseButton,
        title = props.title,
        transitionDuration = props.transitionDuration,
        zIndex = props.zIndex;
    var tooltipStyle = {
      maxWidth: maxWidth,
      zIndex: zIndex
    };
    var interactiveBorderStyle = {
      left: "-".concat(interactiveBorder, "px"),
      top: "-".concat(interactiveBorder, "px"),
      border: "".concat(interactiveBorder, "px solid transparent"),
      zIndex: -999 // ensures interactive border doesnt cover tooltip content

    };
    var eventHandlers = dialog ? {} : {
      onBlur: function onBlur(event) {
        return handleBlur(event);
      }
    };

    var tooltipContent = /*#__PURE__*/_react.default.createElement("div", _extends({
      id: id.current,
      tabIndex: dialog ? -1 : null,
      ref: setTooltipElement,
      className: (0, _classnames.default)('ds-c-tooltip', {
        'ds-c-tooltip--inverse': inversed
      }),
      style: tooltipStyle,
      "data-placement": placement,
      "aria-hidden": !active,
      role: dialog ? 'dialog' : 'tooltip'
    }, eventHandlers), /*#__PURE__*/_react.default.createElement("span", {
      className: "ds-c-tooltip__arrow",
      "data-popper-arrow": true
    }), /*#__PURE__*/_react.default.createElement("div", {
      className: "ds-c-tooltip__content ds-base"
    }, contentHeading || showCloseButton ? /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)('ds-c-tooltip__header', {
        'ds-c-tooltip__header--right': !contentHeading
      })
    }, contentHeading, showCloseButton && /*#__PURE__*/_react.default.createElement(_Button.Button, {
      variation: "ghost",
      size: "small",
      className: "ds-c-tooltip__close-button",
      onClick: handleCloseButtonClick,
      "aria-label": closeButtonLabel || 'Close'
    }, /*#__PURE__*/_react.default.createElement(_Icons.CloseIconThin, null))) : null, title), !dialog && /*#__PURE__*/_react.default.createElement("span", {
      className: "ds-c-tooltip__interactive-border",
      style: interactiveBorderStyle
    }));

    return /*#__PURE__*/_react.default.createElement(_CSSTransition.default, {
      in: active,
      classNames: "ds-c-tooltip",
      timeout: transitionDuration
    }, dialog ? /*#__PURE__*/_react.default.createElement(_focusTrapReact.default, {
      active: active,
      focusTrapOptions: {
        initialFocus: function initialFocus() {
          return document.getElementById("".concat(id.current));
        },
        clickOutsideDeactivates: true
      }
    }, tooltipContent) : tooltipContent);
  };

  var mainEventHandlers = props.dialog ? {} : {
    onMouseEnter: function onMouseEnter() {
      if (!isMobile) {
        setIsHover(true);
        setActive(true);
      }
    },
    onMouseLeave: function onMouseLeave() {
      if (!isMobile) {
        setIsHover(false);
        setActive(false);
      }
    }
  };
  return /*#__PURE__*/_react.default.createElement("div", _extends({
    className: "ds-c-tooltip__container"
  }, mainEventHandlers), renderTrigger(props), renderContent(props));
};

exports.Tooltip = Tooltip;
Tooltip.propTypes = {
  /**
     * Classes applied to the tooltip trigger when the tooltip is active
     */
  activeClassName: _propTypes.default.string,

  /**
     * Helpful description of the tooltip for screenreaders
     */
  ariaLabel: _propTypes.default.string,

  /**
     * Tooltip trigger content
     */
  children: _propTypes.default.node.isRequired,

  /**
     * Classes applied to the tooltip trigger
     */
  className: _propTypes.default.string,

  /**
     * Configurable text for the aria-label of the tooltip's close button
     */
  closeButtonLabel: _propTypes.default.string,

  /**
     * When provided, will render the passed in component for the tooltip trigger. Typically will be a `button`, `a`, or rarely an `input` element.
     */
  component: _propTypes.default.any,

  /**
     * Heading for the tooltip content. This will show above 'title' content and inline with 'closeButton' if closeButton is set
     */
  contentHeading: _propTypes.default.node,

  /**
     * Tooltip that behaves like a dialog, i.e. a tooltip that only appears on click, traps focus, and contains interactive content. For more information, see Deque's [tooltip dialog documentation](https://dequeuniversity.com/library/aria/tooltip-dialog)
     */
  dialog: _propTypes.default.bool,

  /**
     * `id` applied to tooltip body container element. If not provided, a unique id will be automatically generated and used.
     */
  id: _propTypes.default.string,

  /**
     * Sets the size of the invisible border around interactive tooltips that prevents it from immediately hiding when the cursor leaves the tooltip.
     */
  interactiveBorder: _propTypes.default.number,
  inversed: _propTypes.default.bool,

  /**
     * Called when the tooltip is hidden
     */
  onClose: _propTypes.default.func,

  /**
     * Called when the tooltip is shown
     */
  onOpen: _propTypes.default.func,

  /**
     * `maxWidth` styling applied to the tooltip body
     */
  maxWidth: _propTypes.default.string,

  /**
     * Determines if close button is shown in tooltip. It is recommended that the close button is only used if `dialog=true`
     */
  showCloseButton: _propTypes.default.bool,

  /**
     * Content inside the tooltip body or popover. If contains interactive elements use the `dialog` prop.
     */
  title: _propTypes.default.node.isRequired,

  /**
     * Duration of the `react-transition-group` CSSTransition. See the [`timeout` option](http://reactcommunity.org/react-transition-group/transition#Transition-prop-timeout) for more info.
     */
  transitionDuration: _propTypes.default.number,

  /**
     * `zIndex` styling applied to the tooltip body
     */
  zIndex: _propTypes.default.number
};
Tooltip.defaultProps = {
  component: 'button',
  interactiveBorder: 15,
  maxWidth: '300px',
  offset: [0, 5],
  placement: 'top',
  transitionDuration: 250,
  // Equivalent to $animation-speed-1
  zIndex: 9999
};
var _default = Tooltip;
exports.default = _default;