@atlaskit/editor-plugin-paste
Version:
Paste plugin for @atlaskit/editor-core
655 lines (620 loc) • 38.7 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createPlugin = createPlugin;
exports.isInsideBlockQuote = void 0;
exports.isSharePointUrl = isSharePointUrl;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _uuid = _interopRequireDefault(require("uuid"));
var _analytics = require("@atlaskit/editor-common/analytics");
var _card = require("@atlaskit/editor-common/card");
var _coreUtils = require("@atlaskit/editor-common/core-utils");
var _extensions = require("@atlaskit/editor-common/extensions");
var _nesting = require("@atlaskit/editor-common/nesting");
var _paste = require("@atlaskit/editor-common/paste");
var _measureRender = require("@atlaskit/editor-common/performance/measure-render");
var _safePlugin = require("@atlaskit/editor-common/safe-plugin");
var _syncBlock = require("@atlaskit/editor-common/sync-block");
var _transforms = require("@atlaskit/editor-common/transforms");
var _utils = require("@atlaskit/editor-common/utils");
var _editorMarkdownTransformer = require("@atlaskit/editor-markdown-transformer");
var _model = require("@atlaskit/editor-prosemirror/model");
var _utils2 = require("@atlaskit/editor-prosemirror/utils");
var _utils3 = require("@atlaskit/editor-tables/utils");
var _insm = require("@atlaskit/insm");
var _mediaCommon = require("@atlaskit/media-common");
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 _actions = require("../editor-actions/actions");
var _commands = require("../editor-commands/commands");
var _media = require("../pm-plugins/media");
var _analytics2 = require("./analytics");
var _createClipboardTextSerializer = require("./create-clipboard-text-serializer");
var _pluginFactory = require("./plugin-factory");
var _util = require("./util");
var _handleVSCodeBlock = require("./util/edge-cases/handleVSCodeBlock");
var _handlers = require("./util/handlers");
var _syncBlock2 = require("./util/sync-block");
var _tinyMCE = require("./util/tinyMCE");
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } // eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
var isInsideBlockQuote = exports.isInsideBlockQuote = function isInsideBlockQuote(state) {
var blockquote = state.schema.nodes.blockquote;
return (0, _utils2.hasParentNodeOfType)(blockquote)(state.selection);
};
var enableNewDomainCheckToImproveSmartLinkResolveRate = function enableNewDomainCheckToImproveSmartLinkResolveRate(hostname) {
return (0, _expValEquals.expValEquals)('improve_3p_smart_link_resolve_rate', 'isEnabled', true) && (
// OneDrive Shortlinks
hostname.endsWith('1drv.ms') ||
// MS Teams links
hostname.endsWith('teams.live.com') || hostname.endsWith('teams.cloud.microsoft') || hostname.endsWith('teams.microsoft.com'));
};
var PASTE = 'Editor Paste Plugin Paste Duration';
function isSharePointUrl(url) {
if (!url) {
return false;
}
try {
var urlObj = new URL(url);
var hostname = urlObj.hostname.toLowerCase();
var protocol = urlObj.protocol.toLowerCase();
// Only accept HTTPS URLs for security
if (protocol !== 'https:') {
return false;
}
// Check if hostname ends with the trusted domains (not just contains them)
return hostname.endsWith('sharepoint.com') || hostname.endsWith('onedrive.com') || hostname.endsWith('onedrive.live.com') || enableNewDomainCheckToImproveSmartLinkResolveRate(hostname);
} catch (_unused) {
// If URL parsing fails, return false for safety
return false;
}
}
function createPlugin(schema, dispatchAnalyticsEvent, dispatch, featureFlags, pluginInjectionApi, getIntl, cardOptions, sanitizePrivateContent, providerFactory, pasteWarningOptions) {
var _pluginInjectionApi$a;
var editorAnalyticsAPI = pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$a = pluginInjectionApi.analytics) === null || _pluginInjectionApi$a === void 0 ? void 0 : _pluginInjectionApi$a.actions;
var atlassianMarkDownParser = new _editorMarkdownTransformer.MarkdownTransformer(schema, _paste.md);
function getMarkdownSlice(text, openStart, openEnd) {
var escapedTextInput = (0, _util.escapeBackslashAndLinksExceptCodeBlock)(text);
var doc = atlassianMarkDownParser.parse(escapedTextInput);
if (doc && doc.content) {
return new _model.Slice(doc.content, openStart, openEnd);
}
return;
}
var extensionAutoConverter;
function setExtensionAutoConverter(_x, _x2) {
return _setExtensionAutoConverter.apply(this, arguments);
}
function _setExtensionAutoConverter() {
_setExtensionAutoConverter = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(name, extensionProviderPromise) {
return _regenerator.default.wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (!(name !== 'extensionProvider' || !extensionProviderPromise)) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
_context.prev = 2;
_context.next = 5;
return (0, _extensions.getExtensionAutoConvertersFromProvider)(extensionProviderPromise);
case 5:
extensionAutoConverter = _context.sent;
_context.next = 11;
break;
case 8:
_context.prev = 8;
_context.t0 = _context["catch"](2);
// eslint-disable-next-line no-console
console.error(_context.t0);
case 11:
case "end":
return _context.stop();
}
}, _callee, null, [[2, 8]]);
}));
return _setExtensionAutoConverter.apply(this, arguments);
}
if (providerFactory) {
providerFactory.subscribe('extensionProvider', setExtensionAutoConverter);
}
var mostRecentPasteEvent;
var pastedFromBitBucket = false;
return new _safePlugin.SafePlugin({
key: _pluginFactory.pluginKey,
state: (0, _pluginFactory.createPluginState)(dispatch, {
activeFlag: null,
pastedMacroPositions: {},
lastContentPasted: null
}),
props: {
// For serialising to plain text
clipboardTextSerializer: (0, _createClipboardTextSerializer.createClipboardTextSerializer)(getIntl()),
handleDOMEvents: {
// note
paste: function paste(view, event) {
mostRecentPasteEvent = event;
if ((0, _expValEquals.expValEquals)('cc_editor_interactivity_monitoring', 'isEnabled', true) && event.clipboardData) {
_insm.insm.startHeavyTask('paste');
}
return false;
}
},
// note
handlePaste: function handlePaste(view, rawEvent, slice) {
var _text, _schema$nodes, _schema$nodes2, _schema$nodes3, _pluginInjectionApi$m, _schema$nodes$table;
var event = rawEvent;
if (!event.clipboardData) {
return false;
}
var text = event.clipboardData.getData('text/plain');
var html = event.clipboardData.getData('text/html');
var uriList = event.clipboardData.getData('text/uri-list');
// Extract clientId values from pasted HTML for media cross-product copy/paste
// This must be done before ProseMirror parses the HTML, as clientId is not stored in ADF
if ((0, _platformFeatureFlags.fg)('platform_media_cross_client_copy_with_auth')) {
(0, _mediaCommon.extractClientIdsFromHtml)(html);
}
// Links copied from iOS Safari share button only have the text/uri-list data type
// ProseMirror don't do anything with this type so we want to make our own open slice
// with url as text content so link is pasted inline
if (uriList && !text && !html) {
text = uriList;
slice = new _model.Slice(_model.Fragment.from(schema.text(text)), 1, 1);
}
if ((_text = text) !== null && _text !== void 0 && _text.includes('\r')) {
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
text = text.replace(/\r/g, '');
}
// Strip Legacy Content Macro (LCM) extensions on paste
if (!(0, _platformFeatureFlags.fg)('platform_editor_legacy_content_macro_insert')) {
slice = (0, _transforms.transformSliceToRemoveLegacyContentMacro)(slice, schema);
}
var isPastedFile = (0, _paste.isPastedFile)(event);
var isPlainText = text && !html;
var isRichText = !!html;
// Bail if copied content has files
if (isPastedFile) {
if (!html) {
if ((0, _expValEquals.expValEquals)('cc_editor_interactivity_monitoring', 'isEnabled', true)) {
_insm.insm.endHeavyTask('paste');
}
/**
* Microsoft Office, Number, Pages, etc. adds an image to clipboard
* with other mime-types so we don't let the event reach media.
* The detection ration here is that if the payload has both `html` and
* `files`, then it could be one of above or an image copied from web.
* Here, we don't have html, so we return true to allow default event behaviour
*/
return true;
}
/**
* We want to return false for external copied image to allow
* it to be uploaded by the client.
*
* Scenario where we are pasting an external image inside a block quote
* is skipped and handled in handleRichText
*/
if ((0, _util.htmlContainsSingleFile)(html) && !isInsideBlockQuote(view.state)) {
if ((0, _expValEquals.expValEquals)('cc_editor_interactivity_monitoring', 'isEnabled', true)) {
_insm.insm.endHeavyTask('paste');
}
return true;
}
/**
* https://product-fabric.atlassian.net/browse/ED-21993
* stopImmediatePropagation will run the first event attached to the same element
* Which chould have race condition issue
*/
event.stopPropagation();
}
var state = view.state;
var content = (0, _analytics2.getContentNodeTypes)(slice.content);
// eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
var pasteId = (0, _uuid.default)();
var measureName = "".concat(PASTE, "_").concat(pasteId);
(0, _measureRender.measureRender)(measureName, function (_ref) {
var duration = _ref.duration,
distortedDuration = _ref.distortedDuration;
var payload = (0, _analytics2.createPasteMeasurePayload)({
view: view,
duration: duration,
content: content,
distortedDuration: distortedDuration
});
if (payload) {
dispatchAnalyticsEvent(payload);
}
if ((0, _expValEquals.expValEquals)('cc_editor_interactivity_monitoring', 'isEnabled', true)) {
_insm.insm.endHeavyTask('paste');
}
});
var getLastPastedSlice = function getLastPastedSlice(tr) {
var slice;
var _iterator = _createForOfIteratorHelper(tr.steps),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var step = _step.value;
var stepSlice = (0, _utils.extractSliceFromStep)(step);
if (stepSlice) {
slice = stepSlice;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return slice;
};
// creating a custom dispatch because we want to add a meta whenever we do a paste.
var dispatch = function dispatch(tr) {
var _state$doc$resolve$no;
// https://product-fabric.atlassian.net/browse/ED-12633
// don't add closeHistory call if we're pasting a text inside placeholder text as we want the whole action
// to be atomic
var placeholder = state.schema.nodes.placeholder;
var isPastingTextInsidePlaceholderText = ((_state$doc$resolve$no = state.doc.resolve(state.selection.$anchor.pos).nodeAfter) === null || _state$doc$resolve$no === void 0 ? void 0 : _state$doc$resolve$no.type) === placeholder;
// Don't add closeHistory if we're pasting over layout columns, as we will appendTransaction
// to cleanup the layout's structure and we want to keep the paste and re-structuring as
// one event.
var isPastingOverLayoutColumns = (0, _utils2.hasParentNodeOfType)(state.schema.nodes.layoutColumn)(state.selection);
// don't add closeHistory call if we're pasting a table, as some tables may involve additional
// appendedTransactions to repair them (if they're partial or incomplete) and we don't want
// to split those repairing transactions in prosemirror-history when they're being added to the
// "done" stack
var isPastingTable = tr.steps.some(function (step) {
var _slice$content;
var slice = (0, _utils.extractSliceFromStep)(step);
var tableExists = false;
slice === null || slice === void 0 || (_slice$content = slice.content) === null || _slice$content === void 0 || _slice$content.forEach(function (node) {
if (node.type === state.schema.nodes.table) {
tableExists = true;
}
});
return tableExists;
});
// Don't flag as a paste event (add closeHistory) when the paste affects a list and
// the list plugin's appendTransaction will normalise the structure, and we want the
// paste + normalisation to be a single undo step.
// Pasting into an existing list — selection is inside a list node.
var isPastingIntoList = false;
// Pasting list content from an external source — slice top-level contains a list node.
var isPastingListContent = false;
if ((0, _expValEqualsNoExposure.expValEqualsNoExposure)('platform_editor_flexible_list_schema', 'isEnabled', true)) {
var listNodeTypes = [state.schema.nodes.bulletList, state.schema.nodes.orderedList, state.schema.nodes.taskList].filter(function (n) {
return Boolean(n);
});
isPastingIntoList = (0, _utils2.hasParentNodeOfType)(listNodeTypes)(state.selection);
for (var i = 0; i < slice.content.childCount; i++) {
if (listNodeTypes.includes(slice.content.child(i).type)) {
isPastingListContent = true;
break;
}
}
}
if (!isPastingTextInsidePlaceholderText && !isPastingTable && !isPastingOverLayoutColumns && !isPastingIntoList && !isPastingListContent && pluginInjectionApi !== null && pluginInjectionApi !== void 0 && pluginInjectionApi.betterTypeHistory) {
var _pluginInjectionApi$b;
tr = pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$b = pluginInjectionApi.betterTypeHistory) === null || _pluginInjectionApi$b === void 0 ? void 0 : _pluginInjectionApi$b.actions.flagPasteEvent(tr);
}
var isDocChanged = tr.docChanged;
(0, _card.addLinkMetadata)(view.state.selection, tr, {
action: isPlainText ? _analytics.ACTION.PASTED_AS_PLAIN : _analytics.ACTION.PASTED,
inputMethod: _analytics.INPUT_METHOD.CLIPBOARD
});
// handleMacroAutoConvert dispatches twice
// we make sure to call paste options toolbar
// only for a valid paste action
if (isDocChanged) {
var pastedSlice = getLastPastedSlice(tr);
if (pastedSlice) {
var _input;
var pasteStartPos = state.selection.from;
var pasteEndPos = tr.selection.to;
var contentPasted = {
pasteStartPos: pasteStartPos,
pasteEndPos: pasteEndPos,
text: text,
isShiftPressed: Boolean(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
view.shiftKey || ((_input = view.input) === null || _input === void 0 ? void 0 : _input.shiftKey)),
isPlainText: Boolean(isPlainText),
pastedSlice: pastedSlice,
pastedAt: Date.now(),
pasteSource: (0, _util.getPasteSource)(event)
};
tr.setMeta(_pluginFactory.pluginKey, {
type: _actions.PastePluginActionTypes.ON_PASTE,
contentPasted: contentPasted
});
}
}
// the handlePaste definition overrides the generic prosemirror behaviour which would previously
// include a uiEvent meta of paste. To align with the docs (https://prosemirror.net/docs/ref/#state.Transaction)
// This will re-add the uiEvent meta.
view.dispatch(tr.setMeta('uiEvent', 'paste'));
};
slice = (0, _handlers.handleParagraphBlockMarks)(state, slice);
slice = (0, _handleVSCodeBlock.handleVSCodeBlock)({
state: state,
slice: slice,
event: event,
text: text
});
if ((0, _experiments.editorExperiment)('platform_synced_block', true)) {
slice = (0, _syncBlock2.handleSyncBlocksPaste)(slice, schema, (0, _util.getPasteSource)(event), html, pasteWarningOptions, pluginInjectionApi);
}
var plainTextPasteSlice = (0, _utils.linkifyContent)(state.schema)(slice);
if ((0, _analytics2.handlePasteAsPlainTextWithAnalytics)(editorAnalyticsAPI)(view, event, plainTextPasteSlice)(state, dispatch, view)) {
return true;
}
if ((0, _analytics2.handlePasteIntoCaptionWithAnalytics)(editorAnalyticsAPI)(view, event, slice, _analytics.PasteTypes.richText)(state, dispatch)) {
// Create a custom handler to avoid handling with handleRichText method
// As SafeInsert is used inside handleRichText which caused some bad UX like this:
// https://product-fabric.atlassian.net/browse/MEX-1520
// Converting caption to plain text needs to be handled before transformSliceForMedia
// as createChecked will fail when trying to create a mediaSingle node with a caption
// that is not plain text.
return true;
}
// transform slices based on destination
slice = (0, _media.transformSliceForMedia)(slice, schema, pluginInjectionApi)(state.selection);
var markdownSlice;
if (isPlainText) {
var _markdownSlice;
markdownSlice = getMarkdownSlice(text, slice.openStart, slice.openEnd);
// https://product-fabric.atlassian.net/browse/ED-15134
// Lists are not allowed within Blockquotes at this time. Attempting to
// paste a markdown list ie. ">- foo" will yeild a markdownSlice of size 0.
// Rather then blocking the paste action with no UI feedback, this will instead
// force a "paste as plain text" action by clearing the markdownSlice.
markdownSlice = !((_markdownSlice = markdownSlice) !== null && _markdownSlice !== void 0 && _markdownSlice.size) ? undefined : markdownSlice;
if (markdownSlice) {
var _pluginInjectionApi$c, _pluginInjectionApi$e;
// linkify text prior to converting to macro
if ((0, _analytics2.handlePasteLinkOnSelectedTextWithAnalytics)(editorAnalyticsAPI)(view, event, markdownSlice, _analytics.PasteTypes.markdown)(state, dispatch)) {
return true;
}
// run macro autoconvert prior to other conversions
if ((0, _handlers.handleMacroAutoConvert)(text, markdownSlice, pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$c = pluginInjectionApi.card) === null || _pluginInjectionApi$c === void 0 || (_pluginInjectionApi$c = _pluginInjectionApi$c.actions) === null || _pluginInjectionApi$c === void 0 ? void 0 : _pluginInjectionApi$c.queueCardsFromChangedTr, pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$e = pluginInjectionApi.extension) === null || _pluginInjectionApi$e === void 0 || (_pluginInjectionApi$e = _pluginInjectionApi$e.actions) === null || _pluginInjectionApi$e === void 0 ? void 0 : _pluginInjectionApi$e.runMacroAutoConvert, cardOptions, extensionAutoConverter)(state, dispatch, view)) {
// TODO: ED-26959 - handleMacroAutoConvert dispatch twice, so we can't use the helper
(0, _analytics2.sendPasteAnalyticsEvent)(editorAnalyticsAPI)(view, event, markdownSlice, {
type: _analytics.PasteTypes.markdown
});
return true;
}
}
}
slice = (0, _util.transformUnsupportedBlockCardToInline)(slice, state, cardOptions);
// Handles edge case so that when copying text from the top level of the document
// it can be pasted into nodes like panels/actions/decisions without removing them.
// Overriding openStart to be 1 when only pasting a paragraph makes the preferred
// depth favour the text, rather than the paragraph node.
// https://github.com/ProseMirror/prosemirror-transform/blob/master/src/replace.js#:~:text=Transform.prototype.-,replaceRange,-%3D%20function(from%2C%20to
var selectionDepth = state.selection.$head.depth;
var selectionParentNode = state.selection.$head.node(selectionDepth - 1);
var selectionParentType = selectionParentNode === null || selectionParentNode === void 0 ? void 0 : selectionParentNode.type;
var edgeCaseNodeTypes = [(_schema$nodes = schema.nodes) === null || _schema$nodes === void 0 ? void 0 : _schema$nodes.panel, (_schema$nodes2 = schema.nodes) === null || _schema$nodes2 === void 0 ? void 0 : _schema$nodes2.taskList, (_schema$nodes3 = schema.nodes) === null || _schema$nodes3 === void 0 ? void 0 : _schema$nodes3.decisionList];
if (slice.openStart === 0 && slice.openEnd !== 1 && selectionParentNode && edgeCaseNodeTypes.includes(selectionParentType)) {
// @ts-ignore - [unblock prosemirror bump] assigning to readonly prop
slice.openStart = 1;
}
// If we're in a code block, append the text contents of clipboard inside it
if ((0, _analytics2.handleCodeBlockWithAnalytics)(editorAnalyticsAPI)(view, event, slice, text)(state, dispatch)) {
return true;
}
if ((0, _analytics2.handleMediaSingleWithAnalytics)(editorAnalyticsAPI)(view, event, slice, isPastedFile ? _analytics.PasteTypes.binary : _analytics.PasteTypes.richText, pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$m = pluginInjectionApi.media) === null || _pluginInjectionApi$m === void 0 ? void 0 : _pluginInjectionApi$m.actions.insertMediaAsMediaSingle)(state, dispatch, view)) {
return true;
}
if ((0, _analytics2.handleSelectedTableWithAnalytics)(editorAnalyticsAPI)(view, event, slice)(state, dispatch)) {
return true;
}
var isNestedMarkdownTable = false;
// if paste a markdown table inside a table cell, we should treat it as a table slice
var isParentNodeTdOrTh = selectionParentType === schema.nodes.tableCell || selectionParentType === schema.nodes.tableHeader;
isNestedMarkdownTable = !!(markdownSlice && isPlainText && isParentNodeTdOrTh && (0, _analytics2.getContentNodeTypes)(markdownSlice.content).includes((_schema$nodes$table = schema.nodes.table) === null || _schema$nodes$table === void 0 ? void 0 : _schema$nodes$table.name));
slice = isNestedMarkdownTable ? markdownSlice : slice;
// get editor-tables to handle pasting tables if it can
// otherwise, just the replace the selection with the content
if ((0, _utils3.handlePaste)(view, event, slice, {
pasteSource: (0, _util.getPasteSource)(event)
})) {
(0, _analytics2.sendPasteAnalyticsEvent)(editorAnalyticsAPI)(view, event, slice, {
type: _analytics.PasteTypes.richText
});
return true;
}
// handle paste of nested tables to ensure nesting limits are respected
if ((0, _analytics2.handleNestedTablePasteWithAnalytics)(editorAnalyticsAPI, (0, _nesting.isNestedTablesSupported)(state.schema))(view, event, slice)(state, dispatch)) {
return true;
}
if ((0, _analytics2.handlePasteIntoTaskAndDecisionWithAnalytics)(view, event, slice, isPlainText ? _analytics.PasteTypes.plain : _analytics.PasteTypes.richText, pluginInjectionApi)(state, dispatch)) {
return true;
}
// If the clipboard only contains plain text, attempt to parse it as Markdown
if (isPlainText && markdownSlice && !isNestedMarkdownTable) {
if ((0, _analytics2.handlePastePreservingMarksWithAnalytics)(view, event, markdownSlice, _analytics.PasteTypes.markdown, pluginInjectionApi)(state, dispatch)) {
return true;
}
return (0, _analytics2.handleMarkdownWithAnalytics)(view, event, markdownSlice, pluginInjectionApi)(state, dispatch);
}
if (isRichText && isInsideBlockQuote(state)) {
//If pasting inside blockquote
//Skip the blockquote node and keep remaining nodes as they are
//prevent doing this if there is list inside blockquote as the list is pasted incorrectly inside blockquote due to wrong openStart and openEnd
var blockquote = schema.nodes.blockquote;
var children = [];
(0, _utils.mapChildren)(slice.content, function (node) {
if (node.type === blockquote && !(0, _utils2.contains)(node, state.schema.nodes.listItem)) {
for (var i = 0; i < node.childCount; i++) {
children.push(node.child(i));
}
} else {
children.push(node);
}
});
slice = new _model.Slice(_model.Fragment.fromArray(children), slice.openStart, slice.openEnd);
}
// finally, handle rich-text copy-paste
if (isRichText || isNestedMarkdownTable) {
var _pluginInjectionApi$c2, _pluginInjectionApi$e2, _pluginInjectionApi$l;
// linkify the text where possible
slice = (0, _utils.linkifyContent)(state.schema)(slice);
if ((0, _analytics2.handlePasteLinkOnSelectedTextWithAnalytics)(editorAnalyticsAPI)(view, event, slice, _analytics.PasteTypes.richText)(state, dispatch)) {
return true;
}
// run macro autoconvert prior to other conversions
if ((0, _handlers.handleMacroAutoConvert)(text, slice, pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$c2 = pluginInjectionApi.card) === null || _pluginInjectionApi$c2 === void 0 || (_pluginInjectionApi$c2 = _pluginInjectionApi$c2.actions) === null || _pluginInjectionApi$c2 === void 0 ? void 0 : _pluginInjectionApi$c2.queueCardsFromChangedTr, pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$e2 = pluginInjectionApi.extension) === null || _pluginInjectionApi$e2 === void 0 || (_pluginInjectionApi$e2 = _pluginInjectionApi$e2.actions) === null || _pluginInjectionApi$e2 === void 0 ? void 0 : _pluginInjectionApi$e2.runMacroAutoConvert, cardOptions, extensionAutoConverter)(state, dispatch, view)) {
// TODO: ED-26959 - handleMacroAutoConvert dispatch twice, so we can't use the helper
(0, _analytics2.sendPasteAnalyticsEvent)(editorAnalyticsAPI)(view, event, slice, {
type: _analytics.PasteTypes.richText
});
return true;
}
// Special handling for SharePoint URLs generated from Share button
// eslint-disable-next-line @atlaskit/platform/no-preconditioning
if (isSharePointUrl(text) && ((0, _platformFeatureFlags.fg)('platform_editor_sharepoint_url_smart_card_fallback') || (0, _platformFeatureFlags.fg)('platform_editor_sharepoint_url_smart_card_jira'))) {
// Create an inline card directly for SharePoint URLs to show the "Connect" button
var inlineCardNode = schema.nodes.inlineCard.create({
url: text
});
var cardSlice = new _model.Slice(_model.Fragment.from(inlineCardNode), 0, 0);
if (dispatch) {
dispatch(state.tr.replaceSelection(cardSlice));
}
return true;
}
// handle the case when copy content from a table cell inside bodied extension
if ((0, _handlers.handleTableContentPasteInBodiedExtension)(slice)(state, dispatch)) {
return true;
}
// remove annotation marks from the pasted data if they are not present in the document
// for the cases when they are pasted from external pages
if (slice.content.size && (0, _utils.containsAnyAnnotations)(slice, state)) {
var _pluginInjectionApi$a2;
pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$a2 = pluginInjectionApi.annotation) === null || _pluginInjectionApi$a2 === void 0 || _pluginInjectionApi$a2.actions.stripNonExistingAnnotations(slice, state);
}
if ((0, _analytics2.handlePastePreservingMarksWithAnalytics)(view, event, slice, _analytics.PasteTypes.richText, pluginInjectionApi)(state, dispatch)) {
return true;
}
// Check that we are pasting in a location that does not accept
// breakout marks, if so we strip the mark and paste. Note that
// breakout marks are only valid in the root document.
if (selectionParentType !== state.schema.nodes.doc) {
var sliceCopy = _model.Slice.fromJSON(state.schema, slice.toJSON() || {});
sliceCopy.content.descendants(function (node) {
// @ts-ignore - [unblock prosemirror bump] assigning to readonly prop
node.marks = node.marks.filter(function (mark) {
return mark.type.name !== 'breakout';
});
// as breakout marks should only be on top level nodes,
// we don't traverse the entire document
return false;
});
slice = sliceCopy;
}
if ((0, _analytics2.handleExpandWithAnalytics)(editorAnalyticsAPI)(view, event, slice)(state, dispatch)) {
return true;
}
if (!(0, _coreUtils.insideTable)(state)) {
slice = (0, _transforms.transformSliceNestedExpandToExpand)(slice, state.schema);
}
if ((0, _analytics2.handlePastePanelOrDecisionIntoListWithAnalytics)(editorAnalyticsAPI)(view, event, slice, pluginInjectionApi === null || pluginInjectionApi === void 0 || (_pluginInjectionApi$l = pluginInjectionApi.list) === null || _pluginInjectionApi$l === void 0 ? void 0 : _pluginInjectionApi$l.actions.findRootParentListNode)(state, dispatch)) {
return true;
}
if ((0, _analytics2.handlePasteNonNestableBlockNodesIntoListWithAnalytics)(editorAnalyticsAPI)(view, event, slice)(state, dispatch)) {
return true;
}
return (0, _analytics2.handleRichTextWithAnalytics)(view, event, slice, pluginInjectionApi)(state, dispatch);
}
return false;
},
transformPasted: function transformPasted(slice) {
var _pluginInjectionApi$e3;
if (sanitizePrivateContent) {
slice = (0, _handlers.handleMention)(slice, schema);
}
/* Bitbucket copies diffs as multiple adjacent code blocks
* so we merge ALL adjacent code blocks to support paste here */
if (pastedFromBitBucket) {
slice = (0, _transforms.transformSliceToJoinAdjacentCodeBlocks)(slice);
}
// Filter out expand nodes if allowExpand is false
if (!(pluginInjectionApi !== null && pluginInjectionApi !== void 0 && (_pluginInjectionApi$e3 = pluginInjectionApi.expand) !== null && _pluginInjectionApi$e3 !== void 0 && (_pluginInjectionApi$e3 = _pluginInjectionApi$e3.sharedState) !== null && _pluginInjectionApi$e3 !== void 0 && (_pluginInjectionApi$e3 = _pluginInjectionApi$e3.currentState()) !== null && _pluginInjectionApi$e3 !== void 0 && _pluginInjectionApi$e3.allowInsertion) && (0, _expValEquals.expValEquals)('platform_editor_expand_paste_in_comment_editor', 'isEnabled', true)) {
slice = (0, _handlers.handlePasteExpand)(slice);
}
slice = (0, _transforms.transformSingleLineCodeBlockToCodeMark)(slice, schema);
slice = (0, _media.transformSliceToCorrectMediaWrapper)(slice, schema);
slice = (0, _media.transformSliceToMediaSingleWithNewExperience)(slice, schema, pluginInjectionApi);
slice = (0, _transforms.transformSliceToDecisionList)(slice, schema);
// splitting linebreaks into paragraphs must happen before upgrading text to lists
slice = (0, _commands.splitParagraphs)(slice, schema);
slice = (0, _commands.upgradeTextToLists)(slice, schema);
// Ignored via go/ees005
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (slice.content.childCount && slice.content.lastChild.type === schema.nodes.codeBlock) {
slice = new _model.Slice(slice.content, 0, 0);
}
if (!(0, _experiments.editorExperiment)('single_column_layouts', true)) {
slice = (0, _transforms.transformSingleColumnLayout)(slice, schema);
}
slice = (0, _transforms.transformSliceToRemoveMacroId)(slice, schema);
if ((0, _expValEquals.expValEquals)('platform_editor_flexible_list_schema', 'isEnabled', true) && !(0, _expValEquals.expValEquals)('platform_editor_flexible_list_indentation', 'isEnabled', true)) {
// Prevent pasted externally-authored flexible list HTML from producing flexible list structures
// Only when schema support is enabled but indentation behaviour is not, meaning editor gracefully
// handles the structure, but ideally does not produce it
slice = (0, _transforms.transformSliceEnsureListItemParagraphFirst)(slice, schema);
}
return slice;
},
transformPastedHTML: function transformPastedHTML(html) {
// Fix for issue ED-4438
// text from google docs should not be pasted as inline code
if (html.indexOf('id="docs-internal-guid-') >= 0) {
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
html = html.replace(/white-space:pre/g, '');
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
html = html.replace(/white-space:pre-wrap/g, '');
}
// Partial fix for ED-7331: During a copy/paste from the legacy tinyMCE
// confluence editor, if we encounter an incomplete table (e.g. table elements
// not wrapped in <table>), we try to rebuild a complete, valid table if possible.
if (mostRecentPasteEvent && (0, _tinyMCE.isPastedFromTinyMCEConfluence)(mostRecentPasteEvent, html) && (0, _tinyMCE.htmlHasIncompleteTable)(html)) {
var completeTableHtml = (0, _tinyMCE.tryRebuildCompleteTableHtml)(html);
if (completeTableHtml) {
html = completeTableHtml;
}
}
if (!(0, _util.isPastedFromWord)(html) && !(0, _util.isPastedFromExcel)(html) && html.indexOf('<img ') >= 0) {
html = (0, _media.unwrapNestedMediaElements)(html);
}
// https://product-fabric.atlassian.net/browse/ED-11714
// Checking for edge case when copying a list item containing links from Notion
// The html from this case is invalid with duplicate nested links
if ((0, _util.htmlHasInvalidLinkTags)(html)) {
html = (0, _util.removeDuplicateInvalidLinks)(html);
}
// Fix for ED-13568: Code blocks being copied/pasted when next to each other get merged
pastedFromBitBucket = html.indexOf('data-qa="code-line"') >= 0;
// Remove breakout marks HTML around sync block renderer nodes
// so the breakout mark doesn't get applied to the wrong nodes
if (html.indexOf(_syncBlock.SyncBlockRendererDataAttributeName) >= 0 && (0, _experiments.editorExperiment)('platform_synced_block', true)) {
html = (0, _transforms.removeBreakoutFromRendererSyncBlockHTML)(html);
}
mostRecentPasteEvent = null;
return html;
}
}
});
}