@atlaskit/editor-plugin-synced-block
Version:
SyncedBlock plugin for @atlaskit/editor-core
411 lines (400 loc) • 21.8 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unsync = exports.removeSyncedBlockAtPos = exports.removeSyncedBlock = exports.editSyncedBlockSource = exports.createSyncedBlock = exports.copySyncedBlockReferenceToClipboardEditorCommand = exports.copySyncedBlockReferenceToClipboard = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _schemaDefault = require("@atlaskit/adf-schema/schema-default");
var _analytics = require("@atlaskit/editor-common/analytics");
var _copyButton = require("@atlaskit/editor-common/copy-button");
var _model = require("@atlaskit/editor-prosemirror/model");
var _state = require("@atlaskit/editor-prosemirror/state");
var _utils = require("@atlaskit/editor-prosemirror/utils");
var _utils2 = require("@atlaskit/editor-synced-block-provider/utils");
var _fg = require("@atlaskit/platform-feature-flags/fg");
var _expValEqualsNoExposure = require("@atlaskit/tmp-editor-statsig/exp-val-equals-no-exposure");
var _main = require("../pm-plugins/main");
var _utils3 = require("../pm-plugins/utils/utils");
var _types = require("../types");
var _utils4 = require("./utils");
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; }
/**
* Place the caret on the first editable position inside the newly created bodied
* sync block, identified by its unique localId.
*
* - Empty selection: lands inside the block's empty paragraph.
* - Converted content: lands at the start of the first editable child.
*
* `createSyncedBlock` builds the node but neither `safeInsert` (empty case) nor
* `replaceWith` (convert case) leaves the selection inside the new block, so
* without this the caret ends up outside/adjacent to the block after creation
* from the block menu or toolbar (EDITOR-7949). The typeahead path avoids this
* because `typeAheadInsert` positions the caret for us.
*
* Note: when created from the block menu, block-controls' selection preservation
* is active and will restore a whole-node NodeSelection over this caret. The
* caller (block-menu item) is responsible for calling `stopPreservingSelection`
* in the same flow so the caret survives — mirroring the block-menu delete item.
*/
var placeCaretInsideBodiedSyncBlock = function placeCaretInsideBodiedSyncBlock(tr, localId) {
var bodiedSyncBlockType = tr.doc.type.schema.nodes.bodiedSyncBlock;
var blockPos;
tr.doc.descendants(function (node, pos) {
if (blockPos !== undefined) {
return false;
}
if (node.type === bodiedSyncBlockType && node.attrs.localId === localId) {
blockPos = pos;
return false;
}
return true;
});
if (blockPos === undefined) {
return tr;
}
// Find the first valid text position at or after the block's start. `findFrom`
// with textOnly=true descends into the first editable child (empty paragraph or
// start of the converted content), which is exactly what we want for both cases.
var selection = _state.Selection.findFrom(tr.doc.resolve(blockPos), 1, true);
if (selection) {
tr.setSelection(selection).scrollIntoView();
} else {
// Fallback: `bodiedSyncBlock` is always created with a paragraph as its first
// child, so a text position should always be found above. This guards against
// future schema changes where the first child isn't immediately text-editable
// — place the caret just inside the block rather than leaving it outside.
// `blockPos + 1` is the position immediately after the block's opening token,
// which is a node boundary rather than a valid text position, so use
// `TextSelection.near` to snap forward to the nearest selectable cursor. It
// also clamps to the document bounds internally, so no explicit end-of-doc
// check is required.
tr.setSelection(_state.TextSelection.near(tr.doc.resolve(blockPos + 1), 1)).scrollIntoView();
}
return tr;
};
var createSyncedBlock = exports.createSyncedBlock = function createSyncedBlock(_ref) {
var tr = _ref.tr,
syncBlockStore = _ref.syncBlockStore,
typeAheadInsert = _ref.typeAheadInsert,
fireAnalyticsEvent = _ref.fireAnalyticsEvent,
inputMethod = _ref.inputMethod;
var _tr$doc$type$schema$n = tr.doc.type.schema.nodes,
bodiedSyncBlock = _tr$doc$type$schema$n.bodiedSyncBlock,
paragraph = _tr$doc$type$schema$n.paragraph;
// Capture createdEmpty before any insertion mutates the selection. The meta is
// set on the final transaction before returning (see below), since the
// typeahead path may reassign `tr` and drop meta set here.
var createdEmpty = tr.selection.empty;
// If the selection is empty, we want to insert the sync block on a new line
if (tr.selection.empty) {
var attrs = syncBlockStore.sourceManager.generateBodiedSyncBlockAttrs();
var paragraphNode = paragraph.createAndFill({});
var newBodiedSyncBlockNode = bodiedSyncBlock.createAndFill(attrs, paragraphNode ? [paragraphNode] : []);
if (!newBodiedSyncBlockNode) {
fireAnalyticsEvent === null || fireAnalyticsEvent === void 0 || fireAnalyticsEvent({
action: _analytics.ACTION.ERROR,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_CREATE,
attributes: {
error: 'Create and fill for empty content failed'
},
eventType: _analytics.EVENT_TYPE.OPERATIONAL
});
return false;
}
if (typeAheadInsert) {
tr = typeAheadInsert(newBodiedSyncBlockNode);
} else {
tr = (0, _utils.safeInsert)(newBodiedSyncBlockNode)(tr).scrollIntoView();
// safeInsert does not move the selection into the new block, so place the
// caret inside the block's empty paragraph so typing continues inside the
// synced block (EDITOR-7949).
tr = placeCaretInsideBodiedSyncBlock(tr, newBodiedSyncBlockNode.attrs.localId);
}
} else {
var conversionInfo = (0, _utils3.canBeConvertedToSyncBlock)(tr.selection);
if (!conversionInfo) {
fireAnalyticsEvent === null || fireAnalyticsEvent === void 0 || fireAnalyticsEvent({
action: _analytics.ACTION.ERROR,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_CREATE,
attributes: {
error: 'Content cannot be converted to sync block'
},
eventType: _analytics.EVENT_TYPE.OPERATIONAL
});
return false;
}
var _attrs = syncBlockStore.sourceManager.generateBodiedSyncBlockAttrs();
var _newBodiedSyncBlockNode = bodiedSyncBlock.createAndFill(_attrs, conversionInfo.contentToInclude, (0, _fg.fg)('platform_editor_blocks_patch_8') && conversionInfo.breakoutMark ? [conversionInfo.breakoutMark] : undefined);
if (!_newBodiedSyncBlockNode) {
fireAnalyticsEvent === null || fireAnalyticsEvent === void 0 || fireAnalyticsEvent({
action: _analytics.ACTION.ERROR,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_CREATE,
attributes: {
error: 'Create and fill for content failed'
},
eventType: _analytics.EVENT_TYPE.OPERATIONAL
});
return false;
}
tr.replaceWith(conversionInfo.from, conversionInfo.to, _newBodiedSyncBlockNode).scrollIntoView();
// Place the caret on the first editable position inside the converted
// content so typing continues inside the synced block (EDITOR-7949).
tr = placeCaretInsideBodiedSyncBlock(tr, _newBodiedSyncBlockNode.attrs.localId);
}
// Stash creation-type signals on the final transaction (after any typeahead
// reassignment). Set unconditionally — the store manager only reads it behind
// the feature gate.
tr.setMeta(_main.creationMetaKey, {
createdEmpty: createdEmpty,
inputMethod: inputMethod
});
return tr;
};
var copySyncedBlockReferenceToClipboardEditorCommand = exports.copySyncedBlockReferenceToClipboardEditorCommand = function copySyncedBlockReferenceToClipboardEditorCommand(syncBlockStore, inputMethod, api, isLivePage) {
return function (_ref2) {
var tr = _ref2.tr;
if (copySyncedBlockReferenceToClipboardInternal(tr.doc.type.schema, tr.selection, syncBlockStore, inputMethod, api, isLivePage)) {
return tr;
}
return null;
};
};
var copySyncedBlockReferenceToClipboard = exports.copySyncedBlockReferenceToClipboard = function copySyncedBlockReferenceToClipboard(syncBlockStore, inputMethod, api, isLivePage) {
return function (state, _dispatch, _view) {
return copySyncedBlockReferenceToClipboardInternal(state.tr.doc.type.schema, state.tr.selection, syncBlockStore, inputMethod, api, isLivePage);
};
};
var copySyncedBlockReferenceToClipboardInternal = function copySyncedBlockReferenceToClipboardInternal(schema, selection, syncBlockStore, inputMethod, api, isLivePage) {
var _syncBlockStore$refer;
var syncBlockFindResult = (0, _utils3.findSyncBlockOrBodiedSyncBlock)(schema, selection);
if (!syncBlockFindResult) {
var _api$analytics;
api === null || api === void 0 || (_api$analytics = api.analytics) === null || _api$analytics === void 0 || (_api$analytics = _api$analytics.actions) === null || _api$analytics === void 0 || _api$analytics.fireAnalyticsEvent({
eventType: _analytics.EVENT_TYPE.OPERATIONAL,
action: _analytics.ACTION.ERROR,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_COPY,
attributes: {
error: 'No sync block found in selection',
inputMethod: inputMethod
}
});
return false;
}
var isBodiedSyncBlock = (0, _utils3.isBodiedSyncBlockNode)(syncBlockFindResult.node, schema.nodes.bodiedSyncBlock);
var referenceSyncBlockNode = null;
if (isBodiedSyncBlock) {
var syncBlock = schema.nodes.syncBlock;
// create sync block reference node
referenceSyncBlockNode = syncBlock.createAndFill({
resourceId: syncBlockStore.referenceManager.generateResourceIdForReference(syncBlockFindResult.node.attrs.resourceId)
});
if (!referenceSyncBlockNode) {
var _api$analytics2;
api === null || api === void 0 || (_api$analytics2 = api.analytics) === null || _api$analytics2 === void 0 || (_api$analytics2 = _api$analytics2.actions) === null || _api$analytics2 === void 0 || _api$analytics2.fireAnalyticsEvent({
eventType: _analytics.EVENT_TYPE.OPERATIONAL,
action: _analytics.ACTION.ERROR,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_COPY,
attributes: {
error: 'Failed to create reference sync block node',
resourceId: syncBlockFindResult.node.attrs.resourceId,
inputMethod: inputMethod
}
});
return false;
}
} else {
referenceSyncBlockNode = syncBlockFindResult.node;
}
if (!referenceSyncBlockNode) {
var _api$analytics3;
api === null || api === void 0 || (_api$analytics3 = api.analytics) === null || _api$analytics3 === void 0 || (_api$analytics3 = _api$analytics3.actions) === null || _api$analytics3 === void 0 || _api$analytics3.fireAnalyticsEvent({
eventType: _analytics.EVENT_TYPE.OPERATIONAL,
action: _analytics.ACTION.ERROR,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_COPY,
attributes: {
error: 'No reference sync block node available',
inputMethod: inputMethod
}
});
return false;
}
var domNode = (0, _copyButton.toDOM)(referenceSyncBlockNode, schema);
// Bare-uuid join key shared with the create/delete events: for a source
// bodiedSyncBlock its `localId` is the source uuid (copy was page-form only).
var sourceJoinKey = isBodiedSyncBlock ? syncBlockFindResult.node.attrs.localId : undefined;
var isSourceContentUnpublished = isBodiedSyncBlock ? syncBlockStore.sourceManager.getStatus(syncBlockFindResult.node.attrs.resourceId) !== 'active' : ((_syncBlockStore$refer = syncBlockStore.referenceManager.getFromCache(referenceSyncBlockNode.attrs.resourceId)) === null || _syncBlockStore$refer === void 0 || (_syncBlockStore$refer = _syncBlockStore$refer.data) === null || _syncBlockStore$refer === void 0 ? void 0 : _syncBlockStore$refer.status) === 'unpublished';
var sourceProduct = (0, _utils2.getSourceProductFromResourceIdSafe)(referenceSyncBlockNode.attrs.resourceId);
var copyResult = (0, _copyButton.copyDomNodeWithResult)(domNode, referenceSyncBlockNode.type, selection);
if (copyResult === false) {
var _api$analytics4;
api === null || api === void 0 || (_api$analytics4 = api.analytics) === null || _api$analytics4 === void 0 || (_api$analytics4 = _api$analytics4.actions) === null || _api$analytics4 === void 0 || _api$analytics4.fireAnalyticsEvent({
eventType: _analytics.EVENT_TYPE.OPERATIONAL,
action: _analytics.ACTION.ERROR,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_COPY,
attributes: {
error: 'Failed to copy synced block to clipboard',
resourceId: referenceSyncBlockNode.attrs.resourceId,
inputMethod: inputMethod
}
});
return false;
}
(0, _utils3.deferDispatch)(function () {
api === null || api === void 0 || api.core.actions.execute(function (_ref3) {
var _api$analytics5;
var tr = _ref3.tr;
api === null || api === void 0 || (_api$analytics5 = api.analytics) === null || _api$analytics5 === void 0 || (_api$analytics5 = _api$analytics5.actions) === null || _api$analytics5 === void 0 || _api$analytics5.fireAnalyticsEvent({
eventType: _analytics.EVENT_TYPE.OPERATIONAL,
action: _analytics.ACTION.COPIED,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_COPY,
attributes: _objectSpread({
resourceId: referenceSyncBlockNode.attrs.resourceId,
inputMethod: inputMethod
}, sourceJoinKey && {
blockInstanceId: sourceJoinKey
})
});
return tr.setMeta(_main.syncedBlockPluginKey, {
activeFlag: {
id: _types.FLAG_ID.SYNC_BLOCK_COPIED,
isLivePage: isLivePage,
isSourceContentUnpublished: isSourceContentUnpublished,
sourceProduct: sourceProduct
}
});
});
});
return true;
};
var editSyncedBlockSource = exports.editSyncedBlockSource = function editSyncedBlockSource(syncBlockStore, api) {
return function (state, dispatch, _view) {
var _syncBlock$node, _syncBlockStore$refer2;
var syncBlock = (0, _utils3.findSyncBlock)(state.schema, state.selection);
var resourceId = syncBlock === null || syncBlock === void 0 || (_syncBlock$node = syncBlock.node) === null || _syncBlock$node === void 0 || (_syncBlock$node = _syncBlock$node.attrs) === null || _syncBlock$node === void 0 ? void 0 : _syncBlock$node.resourceId;
if (!resourceId) {
return false;
}
var syncBlockURL = syncBlockStore.referenceManager.getSyncBlockURL(resourceId);
var syncBlockData = (_syncBlockStore$refer2 = syncBlockStore.referenceManager.getFromCache(resourceId)) === null || _syncBlockStore$refer2 === void 0 ? void 0 : _syncBlockStore$refer2.data;
var isOnSameDocument = (syncBlockData === null || syncBlockData === void 0 ? void 0 : syncBlockData.onSameDocument) === true;
var sourceBlock = isOnSameDocument && syncBlockData ? (0, _utils4.findBodiedSyncBlockByLocalId)(state, syncBlockData.blockInstanceId) : undefined;
if (syncBlockURL) {
var _api$analytics6;
api === null || api === void 0 || (_api$analytics6 = api.analytics) === null || _api$analytics6 === void 0 || _api$analytics6.actions.fireAnalyticsEvent({
eventType: _analytics.EVENT_TYPE.OPERATIONAL,
action: _analytics.ACTION.SYNCED_BLOCK_EDIT_SOURCE,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_SOURCE_URL,
attributes: {
resourceId: resourceId,
sameDocument: isOnSameDocument
}
});
if (sourceBlock) {
var tr = state.tr.setSelection(_state.NodeSelection.create(state.doc, sourceBlock.pos)).scrollIntoView();
dispatch === null || dispatch === void 0 || dispatch(tr);
return true;
}
window.open(syncBlockURL, '_blank');
} else {
var _api$analytics7;
var _tr = state.tr;
api === null || api === void 0 || (_api$analytics7 = api.analytics) === null || _api$analytics7 === void 0 || (_api$analytics7 = _api$analytics7.actions) === null || _api$analytics7 === void 0 || _api$analytics7.attachAnalyticsEvent({
eventType: _analytics.EVENT_TYPE.OPERATIONAL,
action: _analytics.ACTION.ERROR,
actionSubject: _analytics.ACTION_SUBJECT.SYNCED_BLOCK,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.SYNCED_BLOCK_SOURCE_URL,
attributes: {
error: 'No URL resolved for synced block'
}
})(_tr);
dispatch === null || dispatch === void 0 || dispatch(_tr);
}
return true;
};
};
var removeSyncedBlock = exports.removeSyncedBlock = function removeSyncedBlock(api) {
return function (state, dispatch, _view) {
var nodes = state.schema.nodes,
tr = state.tr;
if (!dispatch) {
return false;
}
var removeTr = tr;
if ((0, _utils.findSelectedNodeOfType)(nodes.syncBlock)(tr.selection) || (0, _utils.findSelectedNodeOfType)(nodes.bodiedSyncBlock)(tr.selection)) {
removeTr = (0, _utils.removeSelectedNode)(tr);
} else {
removeTr = (0, _utils.removeParentNodeOfType)(nodes.bodiedSyncBlock)(tr);
}
if (!removeTr) {
return false;
}
// Tag the transaction so analytics can report this as `deleteButton` rather
// than a keyboard delete (both produce a plain ReplaceStep).
removeTr.setMeta(_main.deleteMechanismMetaKey, 'deleteButton');
dispatch(removeTr);
api === null || api === void 0 || api.core.actions.focus();
return true;
};
};
var removeSyncedBlockAtPos = exports.removeSyncedBlockAtPos = function removeSyncedBlockAtPos(api, pos) {
api === null || api === void 0 || api.core.actions.execute(function (_ref4) {
var tr = _ref4.tr;
var node = tr.doc.nodeAt(pos);
if ((node === null || node === void 0 ? void 0 : node.type.name) === 'syncBlock') {
var _node$nodeSize;
var removeTr = tr.replace(pos, pos + ((_node$nodeSize = node === null || node === void 0 ? void 0 : node.nodeSize) !== null && _node$nodeSize !== void 0 ? _node$nodeSize : 0));
if ((0, _expValEqualsNoExposure.expValEqualsNoExposure)('platform_editor_sync_block_activation', 'isEnabled', true)) {
removeTr.setMeta(_main.deleteMechanismMetaKey, 'deleteButton');
}
return removeTr;
}
return tr;
});
};
/**
* Deletes (bodied)SyncBlock node and paste its content to the editor
*/
var unsync = exports.unsync = function unsync(storeManager, isBodiedSyncBlock, view) {
var _storeManager$referen;
if (!view) {
return false;
}
var state = view.state;
var syncBlock = (0, _utils3.findSyncBlockOrBodiedSyncBlock)(state.schema, state.selection);
if (!syncBlock) {
return false;
}
if (isBodiedSyncBlock) {
// Signal the unsync intent. This transaction is intercepted by the plugin's
// filterTransaction, which shows the deletion-confirmation modal and, on confirm,
// recomputes the actual document change from the live document keyed off the
// `deletionReason: 'source-block-unsynced'` meta (see handleBodiedSyncBlockRemoval /
// recomputeUnsyncTransaction). The real unwrap-vs-delete decision therefore lives in the
// confirm path, not here (EDITOR-8230).
var content = syncBlock === null || syncBlock === void 0 ? void 0 : syncBlock.node.content;
var tr = state.tr;
tr.replaceWith(syncBlock.pos, syncBlock.pos + syncBlock.node.nodeSize, content).setMeta('deletionReason', 'source-block-unsynced');
view.dispatch(tr);
return true;
}
// handle syncBlock unsync
var syncBlockContent = (_storeManager$referen = storeManager.referenceManager.getFromCache(syncBlock.node.attrs.resourceId)) === null || _storeManager$referen === void 0 || (_storeManager$referen = _storeManager$referen.data) === null || _storeManager$referen === void 0 ? void 0 : _storeManager$referen.content;
if (!syncBlockContent) {
return false;
}
// use defaultSchema for serialization so we can serialize any type of nodes and marks despite current editor's schema might not allow it
var contentFragment = _model.Fragment.fromJSON(_schemaDefault.defaultSchema, syncBlockContent);
var contentDOM = _model.DOMSerializer.fromSchema(_schemaDefault.defaultSchema).serializeFragment(contentFragment);
return (0, _utils4.pasteSyncBlockHTMLContent)(contentDOM, view);
};