"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 _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _modalDialog = _interopRequireWildcard(require("@atlaskit/modal-dialog"));
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _useThemeObserver = require("@atlaskit/tokens/use-theme-observer");
var _constants = require("../../constants");
var _useInvokeClientAction = _interopRequireDefault(require("../../state/hooks/use-invoke-client-action"));
var _utils = require("../../utils");
var _common = require("../FlexibleCard/components/elements/common");
var _analytics = _interopRequireDefault(require("./components/analytics"));
var _embedContent = _interopRequireDefault(require("./components/embed-content"));
var _errorBoundary = _interopRequireDefault(require("./components/error-boundary"));
var _linkInfo = _interopRequireDefault(require("./components/link-info"));
var _constants2 = require("./constants");
var _types = require("./types");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
var toSize = function toSize(width) {
  return width === _constants2.MAX_MODAL_SIZE ? _types.EmbedModalSize.Large : _types.EmbedModalSize.Small;
};
var toWidth = function toWidth(size) {
  return size === _types.EmbedModalSize.Large ? _constants2.MAX_MODAL_SIZE : _constants2.MIN_MODAL_SIZE;
};
var EmbedModal = function EmbedModal(_ref) {
  var invokeDownloadAction = _ref.invokeDownloadAction,
    fireEvent = _ref.fireEvent,
    iframeName = _ref.iframeName,
    isSupportTheming = _ref.isSupportTheming,
    _ref$isTrusted = _ref.isTrusted,
    isTrusted = _ref$isTrusted === void 0 ? false : _ref$isTrusted,
    linkIcon = _ref.linkIcon,
    onClose = _ref.onClose,
    onOpen = _ref.onOpen,
    onResize = _ref.onResize,
    providerName = _ref.providerName,
    showModal = _ref.showModal,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? _types.EmbedModalSize.Large : _ref$size,
    src = _ref.src,
    _ref$testId = _ref.testId,
    testId = _ref$testId === void 0 ? 'smart-embed-preview-modal' : _ref$testId,
    title = _ref.title,
    invokeViewAction = _ref.invokeViewAction,
    extensionKey = _ref.extensionKey,
    isBlanketHidden = _ref.isBlanketHidden;
  var defaultWidth = toWidth(size);
  var _useState = (0, _react.useState)(showModal),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var _useState3 = (0, _react.useState)(defaultWidth),
    _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
    width = _useState4[0],
    setWidth = _useState4[1];
  var openAt = (0, _react.useRef)();
  var invoke = (0, _useInvokeClientAction.default)({
    fireEvent: fireEvent
  });
  var handleOnOpenComplete = (0, _react.useCallback)(function () {
    openAt.current = Date.now();
    if (onOpen) {
      onOpen({
        size: size
      });
    }
  }, [onOpen, size]);
  var handleOnClose = (0, _react.useCallback)(function () {
    return setIsOpen(false);
  }, []);
  var handleOnCloseComplete = (0, _react.useCallback)(function () {
    if (onClose) {
      var duration = openAt.current ? Date.now() - openAt.current : undefined;
      onClose({
        duration: duration,
        size: toSize(width)
      });
    }
  }, [onClose, width]);
  var handleOnResizeClick = (0, _react.useCallback)(function () {
    var newWidth = width === _constants2.MIN_MODAL_SIZE ? _constants2.MAX_MODAL_SIZE : _constants2.MIN_MODAL_SIZE;
    setWidth(newWidth);
    if (onResize) {
      onResize({
        size: toSize(newWidth)
      });
    }
    if (invokeViewAction) {
      var visitedDisplay = invokeViewAction.display && invokeViewAction.display !== 'url' ? invokeViewAction.display : null;
      if (visitedDisplay) {
        var _invokeViewAction$id, _invokeViewAction$def;
        fireEvent === null || fireEvent === void 0 || fireEvent('track.smartLink.visited', {
          id: (_invokeViewAction$id = invokeViewAction.id) !== null && _invokeViewAction$id !== void 0 ? _invokeViewAction$id : iframeName,
          display: visitedDisplay,
          definitionId: (_invokeViewAction$def = invokeViewAction.definitionId) !== null && _invokeViewAction$def !== void 0 ? _invokeViewAction$def : null
        });
      }
    }
  }, [fireEvent, iframeName, invokeViewAction, onResize, width]);
  var themeState = (0, _useThemeObserver.useThemeObserver)();
  var previewUrl = src;
  var handleOnViewActionClick = (0, _react.useCallback)(function () {
    if (invokeViewAction) {
      invoke(invokeViewAction);
      var visitedDisplay = invokeViewAction.display && invokeViewAction.display !== 'url' ? invokeViewAction.display : null;
      if (visitedDisplay) {
        var _invokeViewAction$id2, _invokeViewAction$def2;
        fireEvent === null || fireEvent === void 0 || fireEvent('track.smartLink.visited', {
          id: (_invokeViewAction$id2 = invokeViewAction.id) !== null && _invokeViewAction$id2 !== void 0 ? _invokeViewAction$id2 : iframeName,
          display: visitedDisplay,
          definitionId: (_invokeViewAction$def2 = invokeViewAction.definitionId) !== null && _invokeViewAction$def2 !== void 0 ? _invokeViewAction$def2 : null
        });
      }
    }
  }, [fireEvent, iframeName, invoke, invokeViewAction]);
  var handleOnDownloadActionClick = (0, _react.useCallback)(function () {
    invokeDownloadAction && invoke(invokeDownloadAction);
  }, [invokeDownloadAction, invoke]);
  if (previewUrl && isSupportTheming) {
    previewUrl = (0, _utils.getPreviewUrlWithTheme)(previewUrl, themeState);
  }
  var focusRef = (0, _react.useRef)(null);
  var hasRestoredFocus = (0, _react.useRef)(false);
  (0, _react.useEffect)(function () {
    if (!isOpen || !(0, _platformFeatureFlags.fg)('navx-4719-a11y-embed-modal-focus-states')) {
      hasRestoredFocus.current = false;
      return;
    }
    var handleWindowBlur = function handleWindowBlur() {
      if (hasRestoredFocus.current) return;
      setTimeout(function () {
        var _focusRef$current;
        // document.hasFocus() returns true when focus moved to an
        // iframe on the same page, false when the window itself
        // lost focus (e.g. user switched browser tabs)
        if (!document.hasFocus()) return;
        hasRestoredFocus.current = true;
        (_focusRef$current = focusRef.current) === null || _focusRef$current === void 0 || _focusRef$current.focus();
      }, 0);
    };
    window.addEventListener('blur', handleWindowBlur);
    return function () {
      window.removeEventListener('blur', handleWindowBlur);
    };
  }, [isOpen]);
  return /*#__PURE__*/_react.default.createElement(_modalDialog.ModalTransition, null, isOpen && /*#__PURE__*/_react.default.createElement(_modalDialog.default, {
    height: "100%",
    onClose: handleOnClose,
    onCloseComplete: handleOnCloseComplete,
    onOpenComplete: handleOnOpenComplete,
    testId: testId,
    width: width,
    label: title,
    isBlanketHidden: isBlanketHidden
  }, /*#__PURE__*/_react.default.createElement(_linkInfo.default, (0, _extends2.default)({
    icon: linkIcon && {
      icon: /*#__PURE__*/_react.default.createElement(_common.BaseIconElement, (0, _extends2.default)({}, linkIcon, {
        size: _constants.SmartLinkSize.Large
      })),
      isFlexibleUi: true
    },
    providerName: providerName,
    onViewButtonClick: invokeViewAction ? handleOnViewActionClick : undefined,
    onDownloadButtonClick: invokeDownloadAction ? handleOnDownloadActionClick : undefined,
    onResizeButtonClick: handleOnResizeClick,
    size: width,
    title: title,
    testId: testId
  }, (0, _platformFeatureFlags.fg)('navx-4719-a11y-embed-modal-focus-states') ? {
    focusRef: focusRef
  } : {})), /*#__PURE__*/_react.default.createElement(_modalDialog.ModalBody, null, /*#__PURE__*/_react.default.createElement(_embedContent.default, {
    isTrusted: isTrusted,
    name: iframeName,
    src: previewUrl,
    testId: testId,
    ariaLabel: title,
    extensionKey: extensionKey
  }))));
};
var _default_1 = (0, _analytics.default)((0, _errorBoundary.default)(EmbedModal));
var _default = exports.default = _default_1;