@atlaskit/editor-plugin-selection
Version:
Selection plugin for @atlaskit/editor-core
60 lines (58 loc) • 2.55 kB
JavaScript
import { SafePlugin } from '@atlaskit/editor-common/safe-plugin';
import { AllSelection, PluginKey, TextSelection } from '@atlaskit/editor-prosemirror/state';
import { Decoration, DecorationSet } from '@atlaskit/editor-prosemirror/view';
export var inlineNodeInRangeSelectionClassName = 'ak-editor-inline-node-in-range-selection';
/** Inline atom nodes that show a selection treatment instead of the native text highlight. */
export var inlineNodeRangeSelectionNodeTypeNames = ['inlineCard', 'mention', 'status', 'date', 'emoji'];
var pluginKey = new PluginKey('inlineNodeRangeSelectionPlugin');
var isNonEmptyRangeSelection = function isNonEmptyRangeSelection(selection) {
return !selection.empty && (selection instanceof TextSelection || selection instanceof AllSelection);
};
/**
* Marks every node of the given inline atom types that sits inside a text or all selection,
* so it can show a selection treatment instead of the native text highlight on its internals.
*/
var getInlineNodeRangeSelectionDecorations = function getInlineNodeRangeSelectionDecorations(_ref, nodeTypeNames) {
var doc = _ref.doc,
schema = _ref.schema,
selection = _ref.selection;
if (!isNonEmptyRangeSelection(selection)) {
return DecorationSet.empty;
}
var nodeTypes = new Set(nodeTypeNames.map(function (name) {
return schema.nodes[name];
}).filter(Boolean));
if (nodeTypes.size === 0) {
return DecorationSet.empty;
}
var decorations = [];
doc.nodesBetween(selection.from, selection.to, function (node, pos) {
if (!nodeTypes.has(node.type)) {
return true;
}
decorations.push(Decoration.node(pos, pos + node.nodeSize, {
class: inlineNodeInRangeSelectionClassName
}));
return false;
});
return DecorationSet.create(doc, decorations);
};
export var createInlineNodeRangeSelectionPlugin = function createInlineNodeRangeSelectionPlugin() {
var nodeTypeNames = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : inlineNodeRangeSelectionNodeTypeNames;
return new SafePlugin({
key: pluginKey,
state: {
init: function init(_config, state) {
return getInlineNodeRangeSelectionDecorations(state, nodeTypeNames);
},
apply: function apply(tr, decorations, _oldState, newState) {
return tr.docChanged || tr.selectionSet ? getInlineNodeRangeSelectionDecorations(newState, nodeTypeNames) : decorations;
}
},
props: {
decorations: function decorations(state) {
return pluginKey.getState(state);
}
}
});
};