"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof3 = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getNodeCopiedAnalyticsPayload = exports.getAnalyticsPayload = exports.copyToClipboard = exports.copyHTMLToClipboardPolyfill = exports.copyHTMLToClipboard = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var clipboard = _interopRequireWildcard(require("clipboard-polyfill"));
var _state = require("@atlaskit/editor-prosemirror/state");
var _analytics = require("../analytics");
var _selection = require("../selection");
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" != _typeof3(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 _t4 in e) "default" !== _t4 && {}.hasOwnProperty.call(e, _t4) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t4)) && (i.get || i.set) ? o(f, _t4, i) : f[_t4] = e[_t4]); 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; } // Ignored via go/ees005
// eslint-disable-next-line import/no-namespace
var isClipboardApiSupported = function isClipboardApiSupported() {
  return !!navigator.clipboard && typeof navigator.clipboard.writeText === 'function';
};
var isIEClipboardApiSupported = function isIEClipboardApiSupported() {
  return (
    // Ignored via go/ees005
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    window.clipboardData && typeof window.clipboardData.setData === 'function'
  );
};
var isExtensionNode = function isExtensionNode(node) {
  if (node === 'extension' || node === 'bodiedExtension' || node === 'inlineExtension' || node === 'multiBodiedExtension') {
    return true;
  }
  return false;
};
var copyToClipboard = exports.copyToClipboard = /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(textToCopy) {
    var _t, _t2;
    return _regenerator.default.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!isClipboardApiSupported()) {
            _context.next = 5;
            break;
          }
          _context.prev = 1;
          _context.next = 2;
          return navigator.clipboard.writeText(textToCopy);
        case 2:
          _context.next = 4;
          break;
        case 3:
          _context.prev = 3;
          _t = _context["catch"](1);
          throw new Error('Clipboard api is not supported');
        case 4:
          _context.next = 11;
          break;
        case 5:
          if (!isIEClipboardApiSupported()) {
            _context.next = 10;
            break;
          }
          _context.prev = 6;
          _context.next = 7;
          return window.clipboardData.setData('text', textToCopy);
        case 7:
          _context.next = 9;
          break;
        case 8:
          _context.prev = 8;
          _t2 = _context["catch"](6);
          throw new Error('IE clipboard api is not supported');
        case 9:
          _context.next = 11;
          break;
        case 10:
          throw new Error('Clipboard api is not supported');
        case 11:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[1, 3], [6, 8]]);
  }));
  return function copyToClipboard(_x) {
    return _ref.apply(this, arguments);
  };
}();

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
var copyHTMLToClipboard = exports.copyHTMLToClipboard = /*#__PURE__*/function () {
  var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(elementToCopy, plainTextToCopy) {
    var data, _t3;
    return _regenerator.default.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (!(isClipboardApiSupported() && typeof ClipboardItem !== 'undefined')) {
            _context2.next = 5;
            break;
          }
          _context2.prev = 1;
          data = new ClipboardItem({
            'text/plain': new Blob([plainTextToCopy || elementToCopy.innerText], {
              type: 'text/plain'
            }),
            'text/html': new Blob([elementToCopy.innerHTML], {
              type: 'text/html'
            })
          }); // @ts-ignore
          _context2.next = 2;
          return navigator.clipboard.write([data]);
        case 2:
          _context2.next = 4;
          break;
        case 3:
          _context2.prev = 3;
          _t3 = _context2["catch"](1);
          throw new Error('Clipboard api is not supported');
        case 4:
          _context2.next = 6;
          break;
        case 5:
          if (!!document && (typeof document === "undefined" ? "undefined" : (0, _typeof2.default)(document)) === 'object') {
            try {
              // ED-17083 extension copy seems have issue with ClipboardItem API
              // Hence of use of this polyfill
              copyHTMLToClipboardPolyfill(elementToCopy, plainTextToCopy);
            } catch (error) {
              // eslint-disable-next-line no-console
              console.log(error);
            }
          }
        case 6:
        case "end":
          return _context2.stop();
      }
    }, _callee2, null, [[1, 3]]);
  }));
  return function copyHTMLToClipboard(_x2, _x3) {
    return _ref2.apply(this, arguments);
  };
}();

// At the time of development, Firefox doesn't support ClipboardItem API
// Hence of use of this polyfill
// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
var copyHTMLToClipboardPolyfill = exports.copyHTMLToClipboardPolyfill = /*#__PURE__*/function () {
  var _ref3 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3(elementToCopy, plainTextToCopy) {
    var dt;
    return _regenerator.default.wrap(function (_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          dt = new clipboard.ClipboardItem({
            'text/html': new Blob([elementToCopy.innerHTML], {
              type: 'text/html'
            }),
            'text/plain': new Blob([plainTextToCopy || elementToCopy.innerText], {
              type: 'text/plain'
            })
          });
          _context3.next = 1;
          return clipboard.write([dt]);
        case 1:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return function copyHTMLToClipboardPolyfill(_x4, _x5) {
    return _ref3.apply(this, arguments);
  };
}();

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
var getAnalyticsPayload = exports.getAnalyticsPayload = function getAnalyticsPayload(state, action) {
  var selection = state.selection,
    doc = state.doc;
  var selectionAnalyticsPayload = (0, _selection.getNodeSelectionAnalyticsPayload)(selection) || (0, _selection.getRangeSelectionAnalyticsPayload)(selection, doc) || (0, _selection.getAllSelectionAnalyticsPayload)(selection) || (0, _selection.getCellSelectionAnalyticsPayload)(state);
  if (selectionAnalyticsPayload) {
    var _attributes;
    var selectionActionSubjectId = selectionAnalyticsPayload.actionSubjectId;
    var node = (_attributes = selectionAnalyticsPayload.attributes) === null || _attributes === void 0 ? void 0 : _attributes.node;
    var content = [];
    var extensionType;
    var extensionKey;
    switch (selectionActionSubjectId) {
      case _analytics.ACTION_SUBJECT_ID.NODE:
        if (node) {
          content.push(node);
          if (isExtensionNode(node)) {
            extensionType = selection.node.attrs.extensionType;
            extensionKey = selection.node.attrs.extensionKey;
          }
        }
        break;
      case _analytics.ACTION_SUBJECT_ID.RANGE:
        // Ignored via go/ees005
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        content.push.apply(content, (0, _toConsumableArray2.default)(selectionAnalyticsPayload.attributes.nodes));
        break;
      case _analytics.ACTION_SUBJECT_ID.ALL:
        content.push('all');
        break;
      case _analytics.ACTION_SUBJECT_ID.CELL:
        {
          // Ignored via go/ees005
          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
          var _ref4 = selectionAnalyticsPayload.attributes,
            selectedCells = _ref4.selectedCells;
          content.push.apply(content, (0, _toConsumableArray2.default)(Array(selectedCells).fill('tableCell')));
          break;
        }
    }
    if (isExtensionNode(node)) {
      return {
        eventType: _analytics.EVENT_TYPE.TRACK,
        action: action,
        actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
        attributes: {
          content: content,
          extensionKey: extensionKey,
          extensionType: extensionType
        }
      };
    }
    return {
      eventType: _analytics.EVENT_TYPE.TRACK,
      action: action,
      actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
      attributes: {
        content: content
      }
    };
  }
  if (selection instanceof _state.TextSelection && selection.$cursor) {
    return {
      eventType: _analytics.EVENT_TYPE.TRACK,
      action: action,
      actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
      attributes: {
        content: ['caret']
      }
    };
  }
};

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
var getNodeCopiedAnalyticsPayload = exports.getNodeCopiedAnalyticsPayload = function getNodeCopiedAnalyticsPayload(node, inputMethod) {
  var nodeType = node.type.name;
  var extensionType;
  var extensionKey;
  if (isExtensionNode(nodeType)) {
    extensionType = node.attrs.extensionType;
    extensionKey = node.attrs.extensionKey;
  }
  var payload = {
    eventType: _analytics.EVENT_TYPE.TRACK,
    action: _analytics.ACTION.COPIED,
    actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
    attributes: _objectSpread(_objectSpread({
      content: [nodeType],
      inputMethod: inputMethod,
      nodeType: nodeType
    }, extensionType ? {
      extensionType: extensionType
    } : {}), extensionKey ? {
      extensionKey: extensionKey
    } : {})
  };
  return payload;
};