"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.VanillaTooltip = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _core = require("@popperjs/core");
var _bindEventListener = require("bind-event-listener");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var startingOffset = {
  name: 'offset',
  options: {
    offset: [0, 4]
  }
};
var endingOffset = {
  name: 'offset',
  options: {
    offset: [0, 8]
  }
};

/**
 * A tooltip component similar to "@atlaskit/tooltip" but built for vanilla scenarios
 *
 * Uses Popover API for accessibility + stacking context: https://developer.mozilla.org/en-US/docs/Web/API/Popover_API
 * Uses popperJS for positioning
 */
var VanillaTooltip = exports.VanillaTooltip = /*#__PURE__*/function () {
  function VanillaTooltip(button, content,
  /**
   * Id associated to the tooltip - must be unique.
   */
  id,
  /**
   * Class Name – used for styling.
   */
  className) {
    var _this = this;
    var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 300;
    var
    /**
     * Optional inline styles to apply directly to the tooltip element.
     * Useful when the tooltip is rendered in the browser's top layer (via Popover API),
     * where ancestor CSS selectors cannot reach it.
     */
    styles = arguments.length > 5 ? arguments[5] : undefined;
    (0, _classCallCheck2.default)(this, VanillaTooltip);
    (0, _defineProperty2.default)(this, "listeners", []);
    (0, _defineProperty2.default)(this, "shouldHidePopover", false);
    (0, _defineProperty2.default)(this, "isDisplayed", false);
    this.button = button;
    this.timeout = timeout;
    var tooltip = document.createElement('span');
    tooltip.role = 'tooltip';
    tooltip.popover = 'hint';
    tooltip.className = className;
    tooltip.id = id;
    tooltip.textContent = content;
    if (styles) {
      Object.assign(tooltip.style, styles);
    }
    this.tooltip = tooltip;

    // Button preparation
    button.appendChild(tooltip);
    // Prepare the button to have the popover target and accessibility properties
    button.setAttribute('popovertarget', tooltip.id);
    button.setAttribute('aria-describedby', tooltip.id);
    var showEvents = ['mouseenter', 'focus'];
    var hideEvents = ['mouseleave', 'blur'];
    showEvents.forEach(function (event) {
      _this.listeners.push((0, _bindEventListener.bind)(button, {
        type: event,
        listener: function listener() {
          return _this.show();
        }
      }));
    });
    hideEvents.forEach(function (event) {
      _this.listeners.push((0, _bindEventListener.bind)(button, {
        type: event,
        listener: function listener() {
          return _this.hide();
        }
      }));
    });
    this.listeners.push((0, _bindEventListener.bind)(window, {
      type: 'keydown',
      listener: function listener(e) {
        if (e.key === 'Escape') {
          _this.hide(true);
        }
      }
    }));

    // Hide the tooltip if the hide transition has completed
    this.tooltip.ontransitionend = function () {
      if (_this.shouldHidePopover) {
        _this.tooltip.hidePopover();
      }
    };
  }
  return (0, _createClass2.default)(VanillaTooltip, [{
    key: "createPopperInstance",
    value: function createPopperInstance() {
      this.popperInstance = (0, _core.createPopper)(this.button, this.tooltip, {
        placement: 'top',
        modifiers: [startingOffset]
      });
    }
  }, {
    key: "destroy",
    value: function destroy() {
      var _this$popperInstance;
      (_this$popperInstance = this.popperInstance) === null || _this$popperInstance === void 0 || _this$popperInstance.destroy();
      this.listeners.forEach(function (listener) {
        listener();
      });
    }
  }, {
    key: "hide",
    value: function hide() {
      var _this2 = this;
      var immediate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      clearTimeout(this.currentTimeoutId);
      this.shouldHidePopover = true;
      // Disable the event listeners
      this.currentTimeoutId = setTimeout(function () {
        var _this2$popperInstance;
        (_this2$popperInstance = _this2.popperInstance) === null || _this2$popperInstance === void 0 || _this2$popperInstance.setOptions(function (options) {
          return _objectSpread(_objectSpread({}, options), {}, {
            modifiers: [startingOffset, {
              name: 'eventListeners',
              enabled: false
            }]
          });
        });
        _this2.tooltip.style.opacity = '0';
        _this2.isDisplayed = false;
        // If transition animations are disabled immediately hide the popover
        if (_this2.tooltip.style.transition === 'none') {
          _this2.tooltip.hidePopover();
        }
      }, immediate ? 0 : this.timeout);
    }
  }, {
    key: "show",
    value: function show() {
      var _this3 = this;
      if (this.isDisplayed) {
        return;
      }
      clearTimeout(this.currentTimeoutId);
      this.shouldHidePopover = false;

      // Make the tooltip visible - but hide until
      this.tooltip.style.visibility = 'hidden';
      this.tooltip.showPopover();

      // Update its position
      if (!this.popperInstance) {
        this.createPopperInstance();
      } else {
        this.popperInstance.update();
      }

      // Enable the event listeners
      this.currentTimeoutId = setTimeout(function () {
        var _this3$popperInstance;
        _this3.tooltip.style.opacity = '1';
        _this3.tooltip.style.visibility = 'visible';
        (_this3$popperInstance = _this3.popperInstance) === null || _this3$popperInstance === void 0 || _this3$popperInstance.setOptions(function (options) {
          return _objectSpread(_objectSpread({}, options), {}, {
            modifiers: [endingOffset, {
              name: 'eventListeners',
              enabled: true
            }]
          });
        });
        _this3.isDisplayed = true;
      }, this.timeout);
    }
  }]);
}();