@atlaskit/editor-plugin-list
Version:
List plugin for @atlaskit/editor-core
54 lines (51 loc) • 2.55 kB
JavaScript
import { JOIN_SCENARIOS_WHEN_TYPING_TO_INSERT_LIST } from '@atlaskit/editor-common/analytics';
import { createRule } from '@atlaskit/editor-common/utils';
import { canJoin, findWrapping } from '@atlaskit/editor-prosemirror/transform';
import { findParentNodeOfTypeClosestToPos } from '@atlaskit/editor-prosemirror/utils';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export var createWrappingJoinRule = function createWrappingJoinRule(_ref) {
var match = _ref.match,
nodeType = _ref.nodeType,
getAttrs = _ref.getAttrs,
joinPredicate = _ref.joinPredicate;
var handler = function handler(state, match, start, end) {
var attrs = (getAttrs instanceof Function ? getAttrs(match) : getAttrs) || {};
var tr = state.tr;
var fixedStart = Math.max(start, 1);
tr.delete(fixedStart, end);
var $start = tr.doc.resolve(fixedStart);
var range = $start.blockRange();
var wrapping = range && findWrapping(range, nodeType, attrs);
if (!wrapping || !range) {
return null;
}
var parentNodePosMapped = tr.mapping.map(range.start);
var parentNode = tr.doc.nodeAt(parentNodePosMapped);
var lastWrap = wrapping[wrapping.length - 1];
if (parentNode && lastWrap) {
var allowedMarks = lastWrap.type.allowedMarks(parentNode.marks) || [];
tr.setNodeMarkup(parentNodePosMapped, parentNode.type, parentNode.attrs, allowedMarks);
}
tr.wrap(range, wrapping);
// if an orderedList node would be inserted by the input rule match, and
// that orderedList node is being added directly after another orderedList
var $end = tr.doc.resolve(tr.mapping.map(end));
var nodeWithPos = findParentNodeOfTypeClosestToPos($end, nodeType);
if (nodeType === state.schema.nodes.orderedList) {
// otherwise join the lists
if (nodeWithPos) {
var nodeEnd = nodeWithPos.pos + nodeWithPos.node.nodeSize;
var after = tr.doc.resolve(nodeEnd).nodeAfter;
if (after && after.type === nodeType && canJoin(tr.doc, nodeEnd) && (!joinPredicate || joinPredicate(match, after, JOIN_SCENARIOS_WHEN_TYPING_TO_INSERT_LIST.JOINED_TO_LIST_BELOW))) {
tr.join(nodeEnd);
}
}
}
var before = tr.doc.resolve(fixedStart - 1).nodeBefore;
if (before && before.type === nodeType && canJoin(tr.doc, fixedStart - 1) && (!joinPredicate || joinPredicate(match, before, JOIN_SCENARIOS_WHEN_TYPING_TO_INSERT_LIST.JOINED_TO_LIST_ABOVE))) {
tr.join(fixedStart - 1);
}
return tr;
};
return createRule(match, handler);
};