UNPKG

@atlaskit/editor-plugin-block-menu

Version:

BlockMenu plugin for @atlaskit/editor-core

257 lines (255 loc) 12.7 kB
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 const transformNode = (api, transformRegistry) => (targetType, metadata) => ({ tr }) => { var _api$blockControls, _api$blockControls$sh; const preservedSelection = api === null || api === void 0 ? void 0 : (_api$blockControls = api.blockControls) === null || _api$blockControls === void 0 ? void 0 : (_api$blockControls$sh = _api$blockControls.sharedState.currentState()) === null || _api$blockControls$sh === void 0 ? void 0 : _api$blockControls$sh.preservedSelection; if (!preservedSelection) { return tr; } if (isExperimentEnabled('platform_editor_block_menu_transform_extensions')) { const { $from, $to, range } = expandSelectionToBlockRange(preservedSelection); const sourceNode = getSingleTransformSourceNode(preservedSelection, range); if (isExtensionTransformSource(sourceNode)) { var _metadata$targetTypeN; const 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 }; const resolution = transformRegistry === null || transformRegistry === void 0 ? void 0 : transformRegistry.resolve(context); if (!resolution || resolution.status === 'unsupported') { return tr; } const measureId = `transformNode_${targetType.name}_${Date.now()}`; startMeasure(measureId); try { var _api$blockControls2, _api$blockControls3; const 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'); } const resultNodes = transformResult.output.map(nodeAdf => { const 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'); } const sliceStart = $from.pos; tr.replaceWith(sliceStart, $to.pos, resultNodes); const insertedNode = tr.doc.nodeAt(sliceStart); const nextSelection = insertedNode && NodeSelection.isSelectable(insertedNode) ? NodeSelection.create(tr.doc, sliceStart) : Selection.near(tr.doc.resolve(sliceStart)); tr.setSelection(nextSelection); api === null || api === void 0 ? void 0 : (_api$blockControls2 = api.blockControls) === null || _api$blockControls2 === void 0 ? void 0 : _api$blockControls2.commands.stopPreservingSelection()({ tr }); api === null || api === void 0 ? void 0 : (_api$blockControls3 = api.blockControls) === null || _api$blockControls3 === void 0 ? void 0 : _api$blockControls3.commands.toggleBlockMenu({ closeMenu: true })({ tr }); const { expand, nestedExpand } = tr.doc.type.schema.nodes; resultNodes.forEach(node => { if (node.type === expand || node.type === nestedExpand) { expandedState.set(node, true); } }); stopMeasure(measureId, (duration, startTime) => { var _api$analytics, _api$analytics$action; api === null || api === void 0 ? void 0 : (_api$analytics = api.analytics) === null || _api$analytics === void 0 ? void 0 : (_api$analytics$action = _api$analytics.actions) === null || _api$analytics$action === void 0 ? void 0 : _api$analytics$action.attachAnalyticsEvent({ action: ACTION.TRANSFORMED, actionSubject: ACTION_SUBJECT.ELEMENT, attributes: { duration, isEmptyLine: false, isNested: isNestedNode(preservedSelection, ''), isSuggested: Boolean(metadata === null || metadata === void 0 ? void 0 : metadata.isSuggested), sourceNodesCount: 1, sourceNodesCountByType: { [sourceNode.type.name]: 1 }, sourceNodeType: sourceNode.type.name, startTime, targetNodeType: targetType.name, outputNodesCount: resultNodes.length, inputMethod: INPUT_METHOD.BLOCK_MENU }, eventType: EVENT_TYPE.TRACK })(tr); }); } catch (error) { var _api$analytics2, _api$analytics2$actio; stopMeasure(measureId); logException(error, { location: 'editor-plugin-block-menu' }); api === null || api === void 0 ? void 0 : (_api$analytics2 = api.analytics) === null || _api$analytics2 === void 0 ? void 0 : (_api$analytics2$actio = _api$analytics2.actions) === null || _api$analytics2$actio === void 0 ? void 0 : _api$analytics2$actio.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; } } const measureId = `transformNode_${targetType.name}_${Date.now()}`; startMeasure(measureId); const { nodes } = tr.doc.type.schema; const { $from, $to } = expandSelectionToBlockRange(preservedSelection); const selectedParent = $from.parent; const isParentLayout = selectedParent.type === nodes.layoutColumn; const isNested = isNestedNode(preservedSelection, '') && !isParentLayout; const isList = isListNode(selectedParent); const sourceNodes = getSourceNodesFromSelectionRange(tr, preservedSelection); const sourceNodeTypes = {}; sourceNodes.forEach(node => { const typeName = node.type.name; sourceNodeTypes[typeName] = (sourceNodeTypes[typeName] || 0) + 1; }); // Check if source node is empty paragraph or heading const isEmptyLine = sourceNodes.length === 1 && (sourceNodes[0].type === nodes.paragraph || sourceNodes[0].type === nodes.heading) && (sourceNodes[0].content.size === 0 || sourceNodes[0].textContent.trim() === ''); const isSuggested = Boolean(metadata === null || metadata === void 0 ? void 0 : metadata.isSuggested); try { var _api$blockControls6; const resultNodes = convertNodesToTargetType({ sourceNodes, targetNodeType: targetType, schema: tr.doc.type.schema, isNested, targetAttrs: metadata === null || metadata === void 0 ? void 0 : metadata.targetAttrs, parentNode: selectedParent }); const content = resultNodes.length > 0 ? resultNodes : sourceNodes; const sliceStart = isList ? $from.pos - 1 : $from.pos; const { expand, nestedExpand } = nodes; content.forEach(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 const deleteFrom = $from.pos; const 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 const 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 const oldSize = sourceNodes.reduce((sum, node) => sum + node.nodeSize, 0); const newSize = content.reduce((sum, node) => sum + node.nodeSize, 0); api === null || api === void 0 ? void 0 : (_api$blockControls4 = api.blockControls) === null || _api$blockControls4 === void 0 ? void 0 : _api$blockControls4.commands.mapPreservedSelection(new Mapping([new StepMap([0, oldSize, newSize])]))({ tr }); } else { tr.replaceWith(sliceStart, $to.pos, content); } if (preservedSelection instanceof CellSelection) { const insertedNode = tr.doc.nodeAt($from.pos); const isSelectable = insertedNode && NodeSelection.isSelectable(insertedNode); if (isSelectable) { var _api$blockControls5; const nodeSelection = NodeSelection.create(tr.doc, $from.pos); tr.setSelection(nodeSelection); api === null || api === void 0 ? void 0 : (_api$blockControls5 = api.blockControls) === null || _api$blockControls5 === void 0 ? void 0 : _api$blockControls5.commands.startPreservingSelection()({ tr }); } } api === null || api === void 0 ? void 0 : (_api$blockControls6 = api.blockControls) === null || _api$blockControls6 === void 0 ? void 0 : _api$blockControls6.commands.toggleBlockMenu({ closeMenu: true })({ tr }); stopMeasure(measureId, (duration, startTime) => { var _api$analytics3, _api$analytics3$actio; api === null || api === void 0 ? void 0 : (_api$analytics3 = api.analytics) === null || _api$analytics3 === void 0 ? void 0 : (_api$analytics3$actio = _api$analytics3.actions) === null || _api$analytics3$actio === void 0 ? void 0 : _api$analytics3$actio.attachAnalyticsEvent({ action: ACTION.TRANSFORMED, actionSubject: ACTION_SUBJECT.ELEMENT, attributes: { duration, isEmptyLine, isNested, isSuggested, sourceNodesCount: sourceNodes.length, sourceNodesCountByType: sourceNodeTypes, sourceNodeType: sourceNodes.length === 1 ? sourceNodes[0].type.name : 'multiple', startTime, targetNodeType: targetType.name, outputNodesCount: content.length, inputMethod: INPUT_METHOD.BLOCK_MENU }, eventType: EVENT_TYPE.TRACK })(tr); }); } catch (error) { var _api$analytics4, _api$analytics4$actio; stopMeasure(measureId); logException(error, { location: 'editor-plugin-block-menu' }); api === null || api === void 0 ? void 0 : (_api$analytics4 = api.analytics) === null || _api$analytics4 === void 0 ? void 0 : (_api$analytics4$actio = _api$analytics4.actions) === null || _api$analytics4$actio === void 0 ? void 0 : _api$analytics4$actio.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; };