Introduce "annotation" plugin.
- Wrap mark around text.
- Store selected text in mark data.
- Colorize selected text.
function AnnotationPlugin(options) {
const { onChange } = options
return {
onSelect(event, data, state, editor) {
event.preventDefault()
const selection = data.selection;
const startOffset = selection.startOffset;
const endOffset = selection.endOffset;
if (selection.isCollapsed) {
return;
}
let nodes = [];
let hasStarted = false;
let hasEnded = false;
// Keep only the relevant nodes,
// i.e. nodes which are contained within selection
state.document.nodes.forEach((node) => {
if (selection.hasStartIn(node)) {
hasStarted = true;
}
if (hasStarted && !hasEnded) {
nodes.push(node);
}
if (selection.hasEndIn(node)) {
hasEnded = true;
}
});
let text = '';
// Concatenate the nodes text
if (nodes.length === 1) {
text = nodes[0].text.substring(startOffset, endOffset);
} else {
text = nodes.map((node) => {
if (selection.hasStartIn(node)) return node.text.substring(startOffset);
if (selection.hasEndIn(node)) return node.text.substring(0, endOffset);
return node.text;
}).join('\n');
}
if (onChange) {
onChange(text);
}
}
};
}
export default AnnotationPlugin;