@atlaskit/editor-plugin-block-menu
Version:
BlockMenu plugin for @atlaskit/editor-core
256 lines (254 loc) • 13.9 kB
JavaScript
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import { ACTION, ACTION_SUBJECT, ACTION_SUBJECT_ID, EVENT_TYPE, INPUT_METHOD } from '@atlaskit/editor-common/analytics';
import { expandedState } from '@atlaskit/editor-common/expand';
import { logException } from '@atlaskit/editor-common/monitoring';
import { startMeasure, stopMeasure } from '@atlaskit/editor-common/performance-measures';
import { expandSelectionToBlockRange, getSourceNodesFromSelectionRange } from '@atlaskit/editor-common/selection';
import { Fragment, Node } from '@atlaskit/editor-prosemirror/model';
import { NodeSelection, Selection } from '@atlaskit/editor-prosemirror/state';
import { Mapping, StepMap } from '@atlaskit/editor-prosemirror/transform';
import { CellSelection } from '@atlaskit/editor-tables';
import { isExperimentEnabled } from '@atlaskit/platform-feature-experiments/is-experiment-enabled';
import { getSingleTransformSourceNode, isExtensionTransformSource } from '../editor-actions/transformSource';
import { isNestedNode } from '../ui/utils/isNestedNode';
import { convertNodesToTargetType } from './transform-node-utils/transform';
import { isListNode } from './transform-node-utils/utils';
export var transformNode = function transformNode(api, transformRegistry) {
return function (targetType, metadata) {
return function (_ref) {
var _api$blockControls;
var tr = _ref.tr;
var preservedSelection = api === null || api === void 0 || (_api$blockControls = api.blockControls) === null || _api$blockControls === void 0 || (_api$blockControls = _api$blockControls.sharedState.currentState()) === null || _api$blockControls === void 0 ? void 0 : _api$blockControls.preservedSelection;
if (!preservedSelection) {
return tr;
}
if (isExperimentEnabled('platform_editor_block_menu_transform_extensions')) {
var _expandSelectionToBlo = expandSelectionToBlockRange(preservedSelection),
_$from = _expandSelectionToBlo.$from,
_$to = _expandSelectionToBlo.$to,
range = _expandSelectionToBlo.range;
var sourceNode = getSingleTransformSourceNode(preservedSelection, range);
if (isExtensionTransformSource(sourceNode)) {
var _metadata$targetTypeN;
var context = {
source: sourceNode.toJSON(),
targetTypeName: (_metadata$targetTypeN = metadata === null || metadata === void 0 ? void 0 : metadata.targetTypeName) !== null && _metadata$targetTypeN !== void 0 ? _metadata$targetTypeN : targetType.name
};
var resolution = transformRegistry === null || transformRegistry === void 0 ? void 0 : transformRegistry.resolve(context);
if (!resolution || resolution.status === 'unsupported') {
return tr;
}
var _measureId = "transformNode_".concat(targetType.name, "_").concat(Date.now());
startMeasure(_measureId);
try {
var _api$blockControls2, _api$blockControls3;
var transformResult = resolution.transform.transform(context);
if (!transformResult) {
stopMeasure(_measureId);
return tr;
}
if (!Array.isArray(transformResult.output) || transformResult.output.length === 0) {
throw new Error('Block menu transform returned no output');
}
var resultNodes = transformResult.output.map(function (nodeAdf) {
var node = Node.fromJSON(tr.doc.type.schema, nodeAdf);
node.check();
return node;
});
if (!range || !range.parent.canReplace(range.startIndex, range.endIndex, Fragment.from(resultNodes))) {
throw new Error('Block menu transform output is invalid at the selected position');
}
var sliceStart = _$from.pos;
tr.replaceWith(sliceStart, _$to.pos, resultNodes);
var insertedNode = tr.doc.nodeAt(sliceStart);
var nextSelection = insertedNode && NodeSelection.isSelectable(insertedNode) ? NodeSelection.create(tr.doc, sliceStart) : Selection.near(tr.doc.resolve(sliceStart));
tr.setSelection(nextSelection);
api === null || api === void 0 || (_api$blockControls2 = api.blockControls) === null || _api$blockControls2 === void 0 || _api$blockControls2.commands.stopPreservingSelection()({
tr: tr
});
api === null || api === void 0 || (_api$blockControls3 = api.blockControls) === null || _api$blockControls3 === void 0 || _api$blockControls3.commands.toggleBlockMenu({
closeMenu: true
})({
tr: tr
});
var _tr$doc$type$schema$n = tr.doc.type.schema.nodes,
expand = _tr$doc$type$schema$n.expand,
nestedExpand = _tr$doc$type$schema$n.nestedExpand;
resultNodes.forEach(function (node) {
if (node.type === expand || node.type === nestedExpand) {
expandedState.set(node, true);
}
});
stopMeasure(_measureId, function (duration, startTime) {
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.attachAnalyticsEvent({
action: ACTION.TRANSFORMED,
actionSubject: ACTION_SUBJECT.ELEMENT,
attributes: {
duration: duration,
isEmptyLine: false,
isNested: isNestedNode(preservedSelection, ''),
isSuggested: Boolean(metadata === null || metadata === void 0 ? void 0 : metadata.isSuggested),
sourceNodesCount: 1,
sourceNodesCountByType: _defineProperty({}, sourceNode.type.name, 1),
sourceNodeType: sourceNode.type.name,
startTime: startTime,
targetNodeType: targetType.name,
outputNodesCount: resultNodes.length,
inputMethod: INPUT_METHOD.BLOCK_MENU
},
eventType: EVENT_TYPE.TRACK
})(tr);
});
} catch (error) {
var _api$analytics2;
stopMeasure(_measureId);
logException(error, {
location: 'editor-plugin-block-menu'
});
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.attachAnalyticsEvent({
action: ACTION.ERRORED,
actionSubject: ACTION_SUBJECT.ELEMENT,
actionSubjectId: ACTION_SUBJECT_ID.TRANSFORM,
eventType: EVENT_TYPE.OPERATIONAL,
attributes: {
docSize: tr.doc.nodeSize,
error: error.message,
errorStack: error.stack,
from: sourceNode.type.name,
inputMethod: INPUT_METHOD.BLOCK_MENU,
selection: preservedSelection.toJSON(),
to: targetType.name
}
})(tr);
}
return tr;
}
}
var measureId = "transformNode_".concat(targetType.name, "_").concat(Date.now());
startMeasure(measureId);
var nodes = tr.doc.type.schema.nodes;
var _expandSelectionToBlo2 = expandSelectionToBlockRange(preservedSelection),
$from = _expandSelectionToBlo2.$from,
$to = _expandSelectionToBlo2.$to;
var selectedParent = $from.parent;
var isParentLayout = selectedParent.type === nodes.layoutColumn;
var isNested = isNestedNode(preservedSelection, '') && !isParentLayout;
var isList = isListNode(selectedParent);
var sourceNodes = getSourceNodesFromSelectionRange(tr, preservedSelection);
var sourceNodeTypes = {};
sourceNodes.forEach(function (node) {
var typeName = node.type.name;
sourceNodeTypes[typeName] = (sourceNodeTypes[typeName] || 0) + 1;
});
// Check if source node is empty paragraph or heading
var isEmptyLine = sourceNodes.length === 1 && (sourceNodes[0].type === nodes.paragraph || sourceNodes[0].type === nodes.heading) && (sourceNodes[0].content.size === 0 || sourceNodes[0].textContent.trim() === '');
var isSuggested = Boolean(metadata === null || metadata === void 0 ? void 0 : metadata.isSuggested);
try {
var _api$blockControls6;
var _resultNodes = convertNodesToTargetType({
sourceNodes: sourceNodes,
targetNodeType: targetType,
schema: tr.doc.type.schema,
isNested: isNested,
targetAttrs: metadata === null || metadata === void 0 ? void 0 : metadata.targetAttrs,
parentNode: selectedParent
});
var content = _resultNodes.length > 0 ? _resultNodes : sourceNodes;
var _sliceStart = isList ? $from.pos - 1 : $from.pos;
var _expand = nodes.expand,
_nestedExpand = nodes.nestedExpand;
content.forEach(function (node) {
if (node.type === _expand || node.type === _nestedExpand) {
expandedState.set(node, true);
}
});
if (preservedSelection instanceof NodeSelection && preservedSelection.node.type === nodes.mediaSingle) {
var _api$blockControls4;
// when node is media single, use tr.replaceWith freeze editor, if modify position, tr.replaceWith creates duplicats
var deleteFrom = $from.pos;
var deleteTo = $to.pos;
tr.delete(deleteFrom, deleteTo);
// After deletion, recalculate the insertion position to ensure it's valid
// especially when mediaSingle with caption is at the bottom of the document
var insertPos = Math.min(deleteFrom, tr.doc.content.size);
tr.insert(insertPos, content);
// when we replace and insert content, we need to manually map the preserved selection
// through the transaction, otherwise it will treat the selection as having been deleted
// and stop preserving it
var oldSize = sourceNodes.reduce(function (sum, node) {
return sum + node.nodeSize;
}, 0);
var newSize = content.reduce(function (sum, node) {
return sum + node.nodeSize;
}, 0);
api === null || api === void 0 || (_api$blockControls4 = api.blockControls) === null || _api$blockControls4 === void 0 || _api$blockControls4.commands.mapPreservedSelection(new Mapping([new StepMap([0, oldSize, newSize])]))({
tr: tr
});
} else {
tr.replaceWith(_sliceStart, $to.pos, content);
}
if (preservedSelection instanceof CellSelection) {
var _insertedNode = tr.doc.nodeAt($from.pos);
var isSelectable = _insertedNode && NodeSelection.isSelectable(_insertedNode);
if (isSelectable) {
var _api$blockControls5;
var nodeSelection = NodeSelection.create(tr.doc, $from.pos);
tr.setSelection(nodeSelection);
api === null || api === void 0 || (_api$blockControls5 = api.blockControls) === null || _api$blockControls5 === void 0 || _api$blockControls5.commands.startPreservingSelection()({
tr: tr
});
}
}
api === null || api === void 0 || (_api$blockControls6 = api.blockControls) === null || _api$blockControls6 === void 0 || _api$blockControls6.commands.toggleBlockMenu({
closeMenu: true
})({
tr: tr
});
stopMeasure(measureId, function (duration, startTime) {
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.attachAnalyticsEvent({
action: ACTION.TRANSFORMED,
actionSubject: ACTION_SUBJECT.ELEMENT,
attributes: {
duration: duration,
isEmptyLine: isEmptyLine,
isNested: isNested,
isSuggested: isSuggested,
sourceNodesCount: sourceNodes.length,
sourceNodesCountByType: sourceNodeTypes,
sourceNodeType: sourceNodes.length === 1 ? sourceNodes[0].type.name : 'multiple',
startTime: startTime,
targetNodeType: targetType.name,
outputNodesCount: content.length,
inputMethod: INPUT_METHOD.BLOCK_MENU
},
eventType: EVENT_TYPE.TRACK
})(tr);
});
} catch (error) {
var _api$analytics4;
stopMeasure(measureId);
logException(error, {
location: 'editor-plugin-block-menu'
});
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.attachAnalyticsEvent({
action: ACTION.ERRORED,
actionSubject: ACTION_SUBJECT.ELEMENT,
actionSubjectId: ACTION_SUBJECT_ID.TRANSFORM,
eventType: EVENT_TYPE.OPERATIONAL,
attributes: {
docSize: tr.doc.nodeSize,
error: error.message,
errorStack: error.stack,
from: sourceNodes.length === 1 ? sourceNodes[0].type.name : 'multiple',
inputMethod: INPUT_METHOD.BLOCK_MENU,
selection: preservedSelection.toJSON(),
to: targetType.name
}
})(tr);
}
return tr;
};
};
};