"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CardWithUrlContent = exports.CardWithUrl = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _analyticsNext = require("@atlaskit/analytics-next");
var _linkExtractors = require("@atlaskit/link-extractors");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _expValEquals = require("@atlaskit/tmp-editor-statsig/exp-val-equals");
var _expValEqualsNoExposure = require("@atlaskit/tmp-editor-statsig/exp-val-equals-no-exposure");
var _experiments = require("@atlaskit/tmp-editor-statsig/experiments");
var _useAnalyticsEvents2 = require("../../common/analytics/generated/use-analytics-events");
var _constants = require("../../constants");
var _state = require("../../state");
var _analytics = require("../../state/analytics");
var _helpers = require("../../state/helpers");
var _useInlineActionNudgeExperiment = _interopRequireDefault(require("../../state/hooks/use-inline-action-nudge-experiment"));
var _useSmartLinkCrossProductUrlWrapper = require("../../state/hooks/use-smart-link-cross-product-url-wrapper");
var _modal = require("../../state/modal");
var _utils = require("../../utils");
var _combineActionOptions = require("../../utils/actions/combine-action-options");
var _click = require("../../utils/analytics/click");
var _SmartLinkAnalyticsContext = require("../../utils/analytics/SmartLinkAnalyticsContext");
var _clickHelpers = require("../../utils/click-helpers");
var _flexible = require("../../utils/flexible");
var measure = _interopRequireWildcard(require("../../utils/performance"));
var _BlockCard = require("../BlockCard");
var _EmbedCard = require("../EmbedCard");
var _FlexibleCard = _interopRequireDefault(require("../FlexibleCard"));
var _InlineCard = require("../InlineCard");
var _useSmartLinkEvents = require("../SmartLinkEvents/useSmartLinkEvents");
var _cardIntersectionObserver = _interopRequireDefault(require("./card-intersection-observer"));
var _experimentMetaEventAttributes = _interopRequireDefault(require("./experiment-meta-event-attributes"));
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); }
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 thirdPartyARIPrefix = 'ari:third-party';
var TRACK_NON_PRIMARY_3P_CLICKS_EXPERIMENT = 'linking_platform_track_non_primary_3p_clicks';
function Component(_ref) {
  var id = _ref.id,
    url = _ref.url,
    isSelected = _ref.isSelected,
    isHovered = _ref.isHovered,
    frameStyle = _ref.frameStyle,
    platform = _ref.platform,
    onClick = _ref.onClick,
    appearance = _ref.appearance,
    onResolve = _ref.onResolve,
    onError = _ref.onError,
    testId = _ref.testId,
    actionOptionsProp = _ref.actionOptions,
    inheritDimensions = _ref.inheritDimensions,
    embedIframeRef = _ref.embedIframeRef,
    embedIframeUrlType = _ref.embedIframeUrlType,
    inlinePreloaderStyle = _ref.inlinePreloaderStyle,
    ui = _ref.ui,
    children = _ref.children,
    showHoverPreview = _ref.showHoverPreview,
    hoverPreviewOptions = _ref.hoverPreviewOptions,
    removeTextHighlightingFromTitle = _ref.removeTextHighlightingFromTitle,
    resolvingPlaceholder = _ref.resolvingPlaceholder,
    truncateInline = _ref.truncateInline,
    CompetitorPrompt = _ref.CompetitorPrompt,
    hideIconLoadingSkeleton = _ref.hideIconLoadingSkeleton,
    disablePreviewPanel = _ref.disablePreviewPanel,
    placeholderData = _ref.placeholderData;
  var _useAnalyticsEventsNe = (0, _analyticsNext.useAnalyticsEvents)(),
    createAnalyticsEvent = _useAnalyticsEventsNe.createAnalyticsEvent;
  var _useAnalyticsEvents = (0, _useAnalyticsEvents2.useAnalyticsEvents)(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var isFlexibleUi = (0, _react.useMemo)(function () {
    return (0, _flexible.isFlexibleUiCard)(children, ui);
  }, [children, ui]);

  // Get state, actions for this card.
  var _useSmartLink = (0, _state.useSmartLink)(id, url),
    state = _useSmartLink.state,
    actions = _useSmartLink.actions,
    config = _useSmartLink.config,
    renderers = _useSmartLink.renderers,
    error = _useSmartLink.error,
    isPreviewPanelAvailable = _useSmartLink.isPreviewPanelAvailable,
    openPreviewPanel = _useSmartLink.openPreviewPanel;
  var ari = (0, _helpers.getObjectAri)(state.details);
  var name = (0, _helpers.getObjectName)(state.details);
  var definitionId = (0, _helpers.getDefinitionId)(state.details);
  var extensionKey = (0, _helpers.getExtensionKey)(state.details);
  var resourceType = (0, _helpers.getResourceType)(state.details);
  var services = (0, _helpers.getServices)(state.details);
  var thirdPartyARI = (0, _helpers.getThirdPartyARI)(state.details);
  var firstPartyIdentifier = (0, _helpers.getFirstPartyIdentifier)();
  var wrapUrlWithCrossProductAnalytics = (0, _useSmartLinkCrossProductUrlWrapper.useSmartLinkCrossProductUrlWrapperGated)({
    details: state.details
  });
  var actionOptions = (0, _combineActionOptions.combineActionOptions)({
    actionOptions: actionOptionsProp,
    platform: platform
  });
  var _useInlineActionNudge = (0, _useInlineActionNudgeExperiment.default)(url, showHoverPreview, actionOptions),
    rovoActionsCtaShown = _useInlineActionNudge.isEnabled;
  var fire3PClickEvent = (0, _platformFeatureFlags.fg)('platform_smartlink_3pclick_analytics') ?
  // eslint-disable-next-line react-hooks/rules-of-hooks
  (0, _useSmartLinkEvents.useFire3PWorkflowsClickEvent)(firstPartyIdentifier, thirdPartyARI) : undefined;

  // Shared scope guard for all 3P-click handlers.
  var shouldFire3PClickEvent = thirdPartyARI && thirdPartyARI.startsWith(thirdPartyARIPrefix) && (0, _helpers.getClickUrl)(url, state.details) === url && fire3PClickEvent && (0, _platformFeatureFlags.fg)('platform_smartlink_3pclick_analytics');

  // Setup UI handlers.
  var handleClickWrapper = (0, _react.useCallback)(function (event) {
    var isModifierKeyPressed = (0, _utils.isSpecialKey)(event) || (0, _utils.isSpecialClick)(event);
    fireEvent('ui.smartLink.clicked', {
      id: id,
      display: isFlexibleUi ? _constants.CardDisplay.Flexible : appearance,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      isModifierKeyPressed: isModifierKeyPressed
    });
    if (shouldFire3PClickEvent) {
      // For questions or concerns about this event,
      // please reach out to the 3P Workflows Team via Slack in #help-3p-connector-workflow
      fire3PClickEvent === null || fire3PClickEvent === void 0 || fire3PClickEvent();
    }
    var isDisablePreviewPanel = disablePreviewPanel && (0, _experiments.editorExperiment)('platform_editor_preview_panel_linking_exp', true, {
      exposure: true
    });

    // If preview panel is available and the user clicked on the link,
    // delegate the click to the preview panel handler
    if (!isModifierKeyPressed && ari && name && openPreviewPanel && isPreviewPanelAvailable !== null && isPreviewPanelAvailable !== void 0 && isPreviewPanelAvailable({
      ari: ari
    }) && !isDisablePreviewPanel) {
      var _extractSmartLinkEmbe;
      event.preventDefault();
      event.stopPropagation();
      openPreviewPanel({
        url: url,
        ari: ari,
        name: name,
        iconUrl: (0, _helpers.getObjectIconUrl)(state.details),
        panelData: {
          embedUrl: (0, _expValEquals.expValEquals)('platform_hover_card_preview_panel', 'cohort', 'test') ? (_extractSmartLinkEmbe = (0, _linkExtractors.extractSmartLinkEmbed)(state.details)) === null || _extractSmartLinkEmbe === void 0 ? void 0 : _extractSmartLinkEmbe.src : undefined
        }
      });
      (0, _click.fireLinkClickedEvent)(createAnalyticsEvent)(event, {
        attributes: {
          clickOutcome: 'previewPanel'
        }
      });
      return;
    } else if (!onClick && !isFlexibleUi) {
      var clickUrl = (0, _helpers.getClickUrl)(url, state.details);

      // Ctrl+left click on mac typically doesn't trigger onClick
      // The event could have potentially had `e.preventDefault()` called on it by now
      // event by smart card internally
      // If it has been called then only then can `isSpecialEvent` be true.
      var target = (0, _utils.isSpecialEvent)(event) ? '_blank' : '_self';
      if ((0, _platformFeatureFlags.fg)('platform_smartlink_xpc_url_wrapping')) {
        var wrappedUrl = wrapUrlWithCrossProductAnalytics(clickUrl);
        window.open(wrappedUrl, target);
      } else {
        window.open(clickUrl, target);
      }
      (0, _click.fireLinkClickedEvent)(createAnalyticsEvent)(event, {
        attributes: {
          clickOutcome: target === '_blank' ? 'clickThroughNewTabOrWindow' : 'clickThrough'
        }
      });
    } else {
      if (onClick) {
        onClick(event);
      }
      (0, _click.fireLinkClickedEvent)(createAnalyticsEvent)(event);
    }
  }, [fireEvent, id, isFlexibleUi, appearance, definitionId, onClick, url, wrapUrlWithCrossProductAnalytics, state.details, ari, name, fire3PClickEvent, shouldFire3PClickEvent, isPreviewPanelAvailable, openPreviewPanel, createAnalyticsEvent, disablePreviewPanel]);

  // Exposure fires once per eligible mount; click-time reads use no-exposure variant.
  (0, _react.useEffect)(function () {
    if (shouldFire3PClickEvent) {
      (0, _expValEquals.expValEquals)(TRACK_NON_PRIMARY_3P_CLICKS_EXPERIMENT, 'isEnabled', true);
    }
  }, [shouldFire3PClickEvent]);

  // Middle-click handler to trigger fire3PClickEvent on middle-clicks.
  // Scope is limited to 3P click analytics to keep the experiment focused.
  var handleFrameAuxClick = (0, _react.useCallback)(function (event) {
    // isAuxClick filters Windows right-clicks (button === 2) that also fire onAuxClick.
    if ((0, _clickHelpers.isAuxClick)(event) && shouldFire3PClickEvent && (0, _expValEqualsNoExposure.expValEqualsNoExposure)(TRACK_NON_PRIMARY_3P_CLICKS_EXPERIMENT, 'isEnabled', true)) {
      fire3PClickEvent === null || fire3PClickEvent === void 0 || fire3PClickEvent({
        isAuxClick: true
      });
    }
  }, [fire3PClickEvent, shouldFire3PClickEvent]);

  // Right-click handler to trigger fire3PClickEvent on right-clicks.
  // Scope is limited to 3P click analytics to keep the experiment focused.
  var handleFrameContextMenu = (0, _react.useCallback)(function (_event) {
    if (shouldFire3PClickEvent && (0, _expValEqualsNoExposure.expValEqualsNoExposure)(TRACK_NON_PRIMARY_3P_CLICKS_EXPERIMENT, 'isEnabled', true)) {
      fire3PClickEvent === null || fire3PClickEvent === void 0 || fire3PClickEvent({
        isContextMenu: true
      });
    }
  }, [fire3PClickEvent, shouldFire3PClickEvent]);
  var handleAuthorize = (0, _react.useCallback)(function () {
    return actions.authorize(appearance);
  }, [actions, appearance]);
  var handleRetry = (0, _react.useCallback)(function () {
    actions.reload();
  }, [actions]);
  var handleInvoke = (0, _react.useCallback)(function (opts) {
    return actions.invoke(opts, appearance);
  }, [actions, appearance]);
  var experimentMetaEventAttributes = (0, _experimentMetaEventAttributes.default)({
    appearance: appearance,
    state: state
  });

  // NB: for each status change in a Smart Link, a performance mark is created.
  // Measures are sent relative to the first mark, matching what a user sees.
  (0, _react.useEffect)(function () {
    measure.mark(id, state.status);
    if (state.status !== 'pending' && state.status !== 'resolving') {
      var _state$error, _state$error2, _state$error3;
      measure.create(id, state.status);
      if (state.status === 'resolved') {
        var _measure$getMeasure$d, _measure$getMeasure;
        fireEvent('operational.smartLink.resolved', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          duration: (_measure$getMeasure$d = (_measure$getMeasure = measure.getMeasure(id, state.status)) === null || _measure$getMeasure === void 0 ? void 0 : _measure$getMeasure.duration) !== null && _measure$getMeasure$d !== void 0 ? _measure$getMeasure$d : null
        });
      } else if (((_state$error = state.error) === null || _state$error === void 0 ? void 0 : _state$error.type) !== 'ResolveUnsupportedError' && ((_state$error2 = state.error) === null || _state$error2 === void 0 ? void 0 : _state$error2.type) !== 'UnsupportedError' && ((_state$error3 = state.error) === null || _state$error3 === void 0 ? void 0 : _state$error3.name) !== 'InvalidUrlError') {
        fireEvent('operational.smartLink.unresolved', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          reason: state.status,
          error: state.error === undefined ? null : {
            name: state.error.name,
            kind: state.error.kind,
            type: state.error.type
          }
        });
      }
    }
  }, [id, appearance, state.status, state.error, definitionId, extensionKey, resourceType, fireEvent]);

  // NB: once the smart-card has rendered into an end state, we capture
  // this as a successful render. These can be one of:
  // - the resolved state: when metadata is shown;
  // - the unresolved states: viz. forbidden, not_found, unauthorized, errored.
  (0, _react.useEffect)(function () {
    if ((0, _helpers.isFinalState)(state.status)) {
      (0, _analytics.succeedUfoExperience)('smart-link-rendered', id || 'NULL', {
        extensionKey: extensionKey,
        display: isFlexibleUi ? 'flexible' : appearance
      });

      // UFO will disregard this if authentication experience has not yet been started
      (0, _analytics.succeedUfoExperience)('smart-link-authenticated', id || 'NULL', {
        display: isFlexibleUi ? 'flexible' : appearance
      });
      fireEvent('ui.smartLink.renderSuccess', _objectSpread(_objectSpread({
        display: isFlexibleUi ? 'flexible' : appearance
      }, appearance === 'inline' && {
        rovoActionsCtaShown: rovoActionsCtaShown
      }), experimentMetaEventAttributes && {
        experimentMeta: experimentMetaEventAttributes
      }));
    }
  }, [appearance, extensionKey, fireEvent, id, isFlexibleUi, rovoActionsCtaShown, state.status, experimentMetaEventAttributes]);
  var onIframeDwell = (0, _react.useCallback)(function (dwellTime, dwellPercentVisible) {
    fireEvent('ui.smartLinkIframe.dwelled', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      dwellPercentVisible: dwellPercentVisible,
      dwellTime: dwellTime
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  var onIframeFocus = (0, _react.useCallback)(function () {
    fireEvent('ui.smartLinkIframe.focused', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      interactionType: 'focus'
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  var onIframeMouseEnter = (0, _react.useCallback)(function () {
    fireEvent('ui.smartLinkIframe.focused', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      interactionType: 'mouseenter'
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  var onIframeMouseLeave = (0, _react.useCallback)(function () {
    fireEvent('ui.smartLinkIframe.focused', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      interactionType: 'mouseleave'
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  if (isFlexibleUi) {
    var cardState = state;
    if (error) {
      if ((error === null || error === void 0 ? void 0 : error.name) === 'APIError') {
        cardState = {
          status: 'errored'
        };
      } else {
        throw error;
      }
    }
    return /*#__PURE__*/_react.default.createElement(_FlexibleCard.default, {
      id: id,
      cardState: cardState,
      placeholderData: placeholderData,
      onAuthorize: services.length && handleAuthorize || undefined,
      onClick: handleClickWrapper,
      onAuxClick: handleFrameAuxClick,
      onContextMenu: handleFrameContextMenu,
      origin: "smartLinkCard",
      renderers: renderers,
      ui: ui,
      showHoverPreview: showHoverPreview,
      hoverPreviewOptions: hoverPreviewOptions,
      actionOptions: actionOptions,
      url: url,
      testId: testId,
      onResolve: onResolve,
      onError: onError
    }, children);
  }

  // We have to keep this last to prevent hook order from being violated
  if (error) {
    throw error;
  }
  switch (appearance) {
    case 'inline':
      return /*#__PURE__*/_react.default.createElement(_InlineCard.InlineCard, {
        id: id,
        url: url,
        renderers: renderers,
        cardState: state,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleFrameClick: handleClickWrapper,
        handleFrameAuxClick: handleFrameAuxClick,
        handleFrameContextMenu: handleFrameContextMenu,
        isSelected: isSelected,
        isHovered: isHovered,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        inlinePreloaderStyle: inlinePreloaderStyle,
        showHoverPreview: showHoverPreview,
        hoverPreviewOptions: hoverPreviewOptions,
        actionOptions: actionOptions,
        removeTextHighlightingFromTitle: removeTextHighlightingFromTitle,
        resolvingPlaceholder: resolvingPlaceholder,
        truncateInline: truncateInline,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
    case 'block':
      return /*#__PURE__*/_react.default.createElement(_BlockCard.BlockCard, {
        id: id,
        url: url,
        renderers: renderers,
        authFlow: config && config.authFlow,
        cardState: state,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleFrameClick: handleClickWrapper,
        handleFrameAuxClick: handleFrameAuxClick,
        handleFrameContextMenu: handleFrameContextMenu,
        isSelected: isSelected,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        actionOptions: actionOptions,
        CompetitorPrompt: CompetitorPrompt,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
    case 'embed':
      return /*#__PURE__*/_react.default.createElement(_EmbedCard.EmbedCard, {
        id: id,
        url: url,
        renderers: renderers,
        cardState: state,
        iframeUrlType: embedIframeUrlType,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleErrorRetry: handleRetry,
        handleFrameClick: handleClickWrapper,
        handleFrameAuxClick: handleFrameAuxClick,
        handleFrameContextMenu: handleFrameContextMenu,
        handleInvoke: handleInvoke,
        isSelected: isSelected,
        frameStyle: frameStyle,
        platform: platform,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        inheritDimensions: inheritDimensions,
        actionOptions: actionOptions,
        ref: embedIframeRef,
        onIframeDwell: onIframeDwell,
        onIframeFocus: onIframeFocus,
        onIframeMouseEnter: onIframeMouseEnter,
        onIframeMouseLeave: onIframeMouseLeave,
        CompetitorPrompt: CompetitorPrompt,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
  }
}
var CardWithUrlContent = exports.CardWithUrlContent = function CardWithUrlContent(props) {
  var display = (0, _flexible.isFlexibleUiCard)(props.children, props === null || props === void 0 ? void 0 : props.ui) ? _constants.CardDisplay.Flexible : props.appearance;
  return /*#__PURE__*/_react.default.createElement(_modal.SmartLinkModalProvider, null, /*#__PURE__*/_react.default.createElement(_SmartLinkAnalyticsContext.SmartLinkAnalyticsContext, {
    url: props.url,
    id: props.id,
    display: display
  }, /*#__PURE__*/_react.default.createElement(Component, props)));
};
var CardWithUrl = exports.CardWithUrl = (0, _cardIntersectionObserver.default)(CardWithUrlContent);