"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 _objectDestructuringEmpty2 = _interopRequireDefault(require("@babel/runtime/helpers/objectDestructuringEmpty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _react2 = require("@emotion/react");
var _classnames = _interopRequireDefault(require("classnames"));
var _file = _interopRequireDefault(require("@atlaskit/icon/glyph/editor/file"));
var _hooks = require("../../hooks");
var _MultiBodiedExtension = require("../../ui/MultiBodiedExtension");
var _utils = require("../../utils");
var _withPluginState = require("../../with-plugin-state");
var _Lozenge = _interopRequireDefault(require("../Extension/Lozenge"));
var _actionApi = require("./action-api");
var _styles = require("./styles");
var _excluded = ["url"];
/* eslint-disable @atlaskit/design-system/prefer-primitives */
/** @jsx jsx */
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
var getContainerCssExtendedStyles = function getContainerCssExtendedStyles(activeChildIndex, showMacroInteractionDesignUpdates) {
  return (0, _react2.css)(_MultiBodiedExtension.sharedMultiBodiedExtensionStyles.mbeExtensionContainer, (0, _defineProperty2.default)({}, ".multiBodiedExtension-content-dom-wrapper > [data-extension-frame='true']:nth-of-type(".concat(activeChildIndex + 1, ")"), (0, _react2.css)(_MultiBodiedExtension.sharedMultiBodiedExtensionStyles.extensionFrameContent, showMacroInteractionDesignUpdates && _MultiBodiedExtension.removeMarginsAndBorder)));
};
var imageStyles = (0, _react2.css)({
  maxHeight: '24px',
  maxWidth: '24px'
});
// Similar to the one in platform/packages/editor/editor-common/src/extensibility/Extension/Lozenge.tsx
var getWrapperTitleContent = function getWrapperTitleContent(imageData, title, showMacroInteractionDesignUpdates) {
  if (showMacroInteractionDesignUpdates) {
    return null;
  }
  if (imageData) {
    var url = imageData.url,
      rest = (0, _objectWithoutProperties2.default)(imageData, _excluded);
    return (0, _react2.jsx)("div", {
      className: "extension-title"
    }, (0, _react2.jsx)("img", (0, _extends2.default)({
      css: imageStyles,
      src: url
    }, rest, {
      alt: title
    })), title);
  }
  return (0, _react2.jsx)("div", {
    className: "extension-title",
    "data-testid": 'multiBodiedExtension-default-lozenge'
  }, (0, _react2.jsx)(_file.default, {
    label: title
  }), title);
};
var MultiBodiedExtensionWithWidth = function MultiBodiedExtensionWithWidth(_ref) {
  var node = _ref.node,
    handleContentDOMRef = _ref.handleContentDOMRef,
    getPos = _ref.getPos,
    tryExtensionHandler = _ref.tryExtensionHandler,
    editorView = _ref.editorView,
    eventDispatcher = _ref.eventDispatcher,
    widthState = _ref.widthState,
    editorAppearance = _ref.editorAppearance,
    showMacroInteractionDesignUpdates = _ref.showMacroInteractionDesignUpdates,
    isNodeSelected = _ref.isNodeSelected,
    isNodeHovered = _ref.isNodeHovered,
    isNodeNested = _ref.isNodeNested,
    setIsNodeHovered = _ref.setIsNodeHovered;
  var _node$attrs = node.attrs,
    parameters = _node$attrs.parameters,
    extensionKey = _node$attrs.extensionKey;
  var title = parameters && parameters.extensionTitle || parameters && parameters.macroMetadata && parameters.macroMetadata.title || extensionKey || node.type.name;
  var imageData = (0, _utils.getExtensionLozengeData)({
    node: node,
    type: 'image'
  });
  var _useState = (0, _react.useState)(0),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    activeChildIndex = _useState2[0],
    setActiveChildIndex = _useState2[1];
  // Adding to avoid aliasing `this` for the callbacks
  var updateActiveChild = _react.default.useCallback(function (index) {
    if (typeof index !== 'number') {
      setActiveChildIndex(0);
      throw new Error('Index is not valid');
    }
    setActiveChildIndex(index);
    return true;
  }, [setActiveChildIndex]);
  var actions = (0, _actionApi.useMultiBodiedExtensionActions)({
    updateActiveChild: updateActiveChild,
    editorView: editorView,
    getPos: getPos,
    eventDispatcher: eventDispatcher,
    node: node
  });
  var extensionHandlerResult = _react.default.useMemo(function () {
    return tryExtensionHandler(actions);
  }, [tryExtensionHandler, actions]);
  var articleRef = _react.default.useCallback(function (node) {
    return handleContentDOMRef(node);
  }, [handleContentDOMRef]);
  var shouldBreakout =
  // Extension should breakout when the layout is set to 'full-width' or 'wide'.
  ['full-width', 'wide'].includes(node.attrs.layout) &&
  // Extension breakout state should not be respected when the editor appearance is full-width mode
  editorAppearance !== 'full-width';
  var mbeWrapperStyles = {};
  if (shouldBreakout) {
    var _calculateBreakoutSty = (0, _utils.calculateBreakoutStyles)({
        mode: node.attrs.layout,
        widthStateLineLength: widthState === null || widthState === void 0 ? void 0 : widthState.lineLength,
        widthStateWidth: widthState === null || widthState === void 0 ? void 0 : widthState.width
      }),
      breakoutStyles = (0, _extends2.default)({}, ((0, _objectDestructuringEmpty2.default)(_calculateBreakoutSty), _calculateBreakoutSty));
    mbeWrapperStyles = breakoutStyles;
  }
  var wrapperClassNames = (0, _classnames.default)('multiBodiedExtension--wrapper', 'extension-container', 'block', {
    'with-margin-styles': showMacroInteractionDesignUpdates && !isNodeNested,
    'with-border': showMacroInteractionDesignUpdates,
    'with-hover-border': showMacroInteractionDesignUpdates && isNodeHovered,
    'with-danger-overlay': showMacroInteractionDesignUpdates
  });
  var containerClassNames = (0, _classnames.default)('multiBodiedExtension--container', {
    'remove-padding': showMacroInteractionDesignUpdates
  });
  var navigationClassNames = (0, _classnames.default)('multiBodiedExtension--navigation', {
    'remove-margins': showMacroInteractionDesignUpdates,
    'remove-border': showMacroInteractionDesignUpdates
  });
  var handleMouseEvent = function handleMouseEvent(didHover) {
    if (setIsNodeHovered) {
      setIsNodeHovered(didHover);
    }
  };
  return (0, _react2.jsx)(_react.Fragment, null, showMacroInteractionDesignUpdates && (0, _react2.jsx)(_Lozenge.default, {
    isNodeSelected: isNodeSelected,
    node: node,
    showMacroInteractionDesignUpdates: true,
    customContainerStyles: mbeWrapperStyles,
    isNodeHovered: isNodeHovered
  }), (0, _react2.jsx)("div", {
    className: wrapperClassNames,
    css: _styles.mbeExtensionWrapperCSSStyles,
    "data-testid": "multiBodiedExtension--wrapper",
    style: mbeWrapperStyles,
    onMouseEnter: function onMouseEnter() {
      return handleMouseEvent(true);
    },
    onMouseLeave: function onMouseLeave() {
      return handleMouseEvent(false);
    }
  }, (0, _react2.jsx)("div", {
    css: _styles.overlayStyles,
    className: "multiBodiedExtension--overlay"
  }), getWrapperTitleContent(imageData, title, showMacroInteractionDesignUpdates), (0, _react2.jsx)("div", {
    className: containerClassNames,
    css: getContainerCssExtendedStyles(activeChildIndex, showMacroInteractionDesignUpdates),
    "data-testid": "multiBodiedExtension--container",
    "data-active-child-index": activeChildIndex
  }, (0, _react2.jsx)("nav", {
    className: navigationClassNames,
    css: _MultiBodiedExtension.sharedMultiBodiedExtensionStyles.mbeNavigation,
    "data-testid": "multiBodiedExtension-navigation"
  }, extensionHandlerResult), (0, _react2.jsx)("article", {
    className: "multiBodiedExtension--frames",
    "data-testid": "multiBodiedExtension--frames",
    ref: articleRef
  }))));
};
var MultiBodiedExtensionWithSharedState = function MultiBodiedExtensionWithSharedState(props) {
  var pluginInjectionApi = props.pluginInjectionApi;
  var _useSharedPluginState = (0, _hooks.useSharedPluginState)(pluginInjectionApi, ['width']),
    widthState = _useSharedPluginState.widthState;
  return (0, _react2.jsx)(MultiBodiedExtensionWithWidth, (0, _extends2.default)({
    widthState: widthState
  }, props));
};

// Workaround taken from platform/packages/editor/editor-core/src/plugins/extension/ui/Extension/Extension/index.tsx
var MultiBodiedExtension = function MultiBodiedExtension(props) {
  // TODO: ED-17836 This code is here because confluence injects
  // the `editor-referentiality` plugin via `dangerouslyAppendPlugins`
  // which cannot access the `pluginInjectionApi`. When we move
  // Confluence to using presets we can remove this workaround.
  var pluginInjectionApi = props.pluginInjectionApi;
  return pluginInjectionApi === undefined ? (0, _react2.jsx)(MultiBodiedExtensionDeprecated, props) : (0, _react2.jsx)(MultiBodiedExtensionWithSharedState, props);
};

// TODO: ED-17836 This code is here because Confluence injects
// the `editor-referentiality` plugin via `dangerouslyAppendPlugins`
// which cannot access the `pluginInjectionApi`. When we move
// Confluence to using presets we can remove this workaround.
// @ts-ignore
var widthPluginKey = {
  key: 'widthPlugin$',
  getState: function getState(state) {
    return state['widthPlugin$'];
  }
};
var MultiBodiedExtensionDeprecated = function MultiBodiedExtensionDeprecated(props) {
  return (
    // @ts-ignore - 'WithPluginState' cannot be used as a JSX component.
    // This error was introduced after upgrading to TypeScript 5
    (0, _react2.jsx)(_withPluginState.WithPluginState, {
      editorView: props.editorView,
      plugins: {
        widthState: widthPluginKey
      },
      render: function render(_ref2) {
        var widthState = _ref2.widthState;
        return (0, _react2.jsx)(MultiBodiedExtensionWithWidth, (0, _extends2.default)({
          widthState: widthState
        }, props));
      }
    })
  );
};
/**
 * End workaround
 */
var _default = exports.default = MultiBodiedExtension;