@atlaskit/editor-plugin-selection
Version:
Selection plugin for @atlaskit/editor-core
66 lines (63 loc) • 2.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.inlineNodeRangeSelectionNodeTypeNames = exports.inlineNodeInRangeSelectionClassName = exports.createInlineNodeRangeSelectionPlugin = void 0;
var _safePlugin = require("@atlaskit/editor-common/safe-plugin");
var _state = require("@atlaskit/editor-prosemirror/state");
var _view = require("@atlaskit/editor-prosemirror/view");
var inlineNodeInRangeSelectionClassName = exports.inlineNodeInRangeSelectionClassName = 'ak-editor-inline-node-in-range-selection';
/** Inline atom nodes that show a selection treatment instead of the native text highlight. */
var inlineNodeRangeSelectionNodeTypeNames = exports.inlineNodeRangeSelectionNodeTypeNames = ['inlineCard', 'mention', 'status', 'date', 'emoji'];
var pluginKey = new _state.PluginKey('inlineNodeRangeSelectionPlugin');
var isNonEmptyRangeSelection = function isNonEmptyRangeSelection(selection) {
return !selection.empty && (selection instanceof _state.TextSelection || selection instanceof _state.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 _view.DecorationSet.empty;
}
var nodeTypes = new Set(nodeTypeNames.map(function (name) {
return schema.nodes[name];
}).filter(Boolean));
if (nodeTypes.size === 0) {
return _view.DecorationSet.empty;
}
var decorations = [];
doc.nodesBetween(selection.from, selection.to, function (node, pos) {
if (!nodeTypes.has(node.type)) {
return true;
}
decorations.push(_view.Decoration.node(pos, pos + node.nodeSize, {
class: inlineNodeInRangeSelectionClassName
}));
return false;
});
return _view.DecorationSet.create(doc, decorations);
};
var createInlineNodeRangeSelectionPlugin = exports.createInlineNodeRangeSelectionPlugin = function createInlineNodeRangeSelectionPlugin() {
var nodeTypeNames = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : inlineNodeRangeSelectionNodeTypeNames;
return new _safePlugin.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);
}
}
});
};